AudioFlinger.cpp revision 58123c3a8b5f34f9d1f70264a3c568ed90288501
1/* //device/include/server/AudioFlinger/AudioFlinger.cpp 2** 3** Copyright 2007, The Android Open Source Project 4** 5** Licensed under the Apache License, Version 2.0 (the "License"); 6** you may not use this file except in compliance with the License. 7** You may obtain a copy of the License at 8** 9** http://www.apache.org/licenses/LICENSE-2.0 10** 11** Unless required by applicable law or agreed to in writing, software 12** distributed under the License is distributed on an "AS IS" BASIS, 13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14** See the License for the specific language governing permissions and 15** limitations under the License. 16*/ 17 18 19#define LOG_TAG "AudioFlinger" 20//#define LOG_NDEBUG 0 21 22#include <math.h> 23#include <signal.h> 24#include <sys/time.h> 25#include <sys/resource.h> 26 27#include <binder/IPCThreadState.h> 28#include <binder/IServiceManager.h> 29#include <utils/Log.h> 30#include <binder/Parcel.h> 31#include <binder/IPCThreadState.h> 32#include <utils/String16.h> 33#include <utils/threads.h> 34#include <utils/Atomic.h> 35 36#include <cutils/bitops.h> 37#include <cutils/properties.h> 38#include <cutils/compiler.h> 39 40#include <media/IMediaPlayerService.h> 41#include <media/IMediaDeathNotifier.h> 42 43#include <private/media/AudioTrackShared.h> 44#include <private/media/AudioEffectShared.h> 45 46#include <system/audio.h> 47#include <hardware/audio.h> 48 49#include "AudioMixer.h" 50#include "AudioFlinger.h" 51 52#include <media/EffectsFactoryApi.h> 53#include <audio_effects/effect_visualizer.h> 54#include <audio_effects/effect_ns.h> 55#include <audio_effects/effect_aec.h> 56 57#include <audio_utils/primitives.h> 58 59#include <cpustats/ThreadCpuUsage.h> 60#include <powermanager/PowerManager.h> 61// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds 62 63// ---------------------------------------------------------------------------- 64 65 66namespace android { 67 68static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n"; 69static const char kHardwareLockedString[] = "Hardware lock is taken\n"; 70 71//static const nsecs_t kStandbyTimeInNsecs = seconds(3); 72static const float MAX_GAIN = 4096.0f; 73static const uint32_t MAX_GAIN_INT = 0x1000; 74 75// retry counts for buffer fill timeout 76// 50 * ~20msecs = 1 second 77static const int8_t kMaxTrackRetries = 50; 78static const int8_t kMaxTrackStartupRetries = 50; 79// allow less retry attempts on direct output thread. 80// direct outputs can be a scarce resource in audio hardware and should 81// be released as quickly as possible. 82static const int8_t kMaxTrackRetriesDirect = 2; 83 84static const int kDumpLockRetries = 50; 85static const int kDumpLockSleepUs = 20000; 86 87// don't warn about blocked writes or record buffer overflows more often than this 88static const nsecs_t kWarningThrottleNs = seconds(5); 89 90// RecordThread loop sleep time upon application overrun or audio HAL read error 91static const int kRecordThreadSleepUs = 5000; 92 93// maximum time to wait for setParameters to complete 94static const nsecs_t kSetParametersTimeoutNs = seconds(2); 95 96// minimum sleep time for the mixer thread loop when tracks are active but in underrun 97static const uint32_t kMinThreadSleepTimeUs = 5000; 98// maximum divider applied to the active sleep time in the mixer thread loop 99static const uint32_t kMaxThreadSleepTimeShift = 2; 100 101 102// ---------------------------------------------------------------------------- 103 104static bool recordingAllowed() { 105 if (getpid() == IPCThreadState::self()->getCallingPid()) return true; 106 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO")); 107 if (!ok) ALOGE("Request requires android.permission.RECORD_AUDIO"); 108 return ok; 109} 110 111static bool settingsAllowed() { 112 if (getpid() == IPCThreadState::self()->getCallingPid()) return true; 113 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS")); 114 if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS"); 115 return ok; 116} 117 118// To collect the amplifier usage 119static void addBatteryData(uint32_t params) { 120 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService(); 121 if (service == NULL) { 122 // it already logged 123 return; 124 } 125 126 service->addBatteryData(params); 127} 128 129static int load_audio_interface(const char *if_name, const hw_module_t **mod, 130 audio_hw_device_t **dev) 131{ 132 int rc; 133 134 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod); 135 if (rc) 136 goto out; 137 138 rc = audio_hw_device_open(*mod, dev); 139 ALOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)", 140 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc)); 141 if (rc) 142 goto out; 143 144 return 0; 145 146out: 147 *mod = NULL; 148 *dev = NULL; 149 return rc; 150} 151 152static const char * const audio_interfaces[] = { 153 "primary", 154 "a2dp", 155 "usb", 156}; 157#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0]))) 158 159// ---------------------------------------------------------------------------- 160 161AudioFlinger::AudioFlinger() 162 : BnAudioFlinger(), 163 mPrimaryHardwareDev(NULL), 164 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef() 165 mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1), 166 mMode(AUDIO_MODE_INVALID), 167 mBtNrecIsOff(false) 168{ 169} 170 171void AudioFlinger::onFirstRef() 172{ 173 int rc = 0; 174 175 Mutex::Autolock _l(mLock); 176 177 /* TODO: move all this work into an Init() function */ 178 179 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) { 180 const hw_module_t *mod; 181 audio_hw_device_t *dev; 182 183 rc = load_audio_interface(audio_interfaces[i], &mod, &dev); 184 if (rc) 185 continue; 186 187 ALOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i], 188 mod->name, mod->id); 189 mAudioHwDevs.push(dev); 190 191 if (!mPrimaryHardwareDev) { 192 mPrimaryHardwareDev = dev; 193 ALOGI("Using '%s' (%s.%s) as the primary audio interface", 194 mod->name, mod->id, audio_interfaces[i]); 195 } 196 } 197 198 mHardwareStatus = AUDIO_HW_INIT; 199 200 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) { 201 ALOGE("Primary audio interface not found"); 202 return; 203 } 204 205 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 206 audio_hw_device_t *dev = mAudioHwDevs[i]; 207 208 mHardwareStatus = AUDIO_HW_INIT; 209 rc = dev->init_check(dev); 210 if (rc == 0) { 211 AutoMutex lock(mHardwareLock); 212 213 mMode = AUDIO_MODE_NORMAL; 214 mHardwareStatus = AUDIO_HW_SET_MODE; 215 dev->set_mode(dev, mMode); 216 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME; 217 dev->set_master_volume(dev, 1.0f); 218 mHardwareStatus = AUDIO_HW_IDLE; 219 } 220 } 221} 222 223status_t AudioFlinger::initCheck() const 224{ 225 Mutex::Autolock _l(mLock); 226 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0) 227 return NO_INIT; 228 return NO_ERROR; 229} 230 231AudioFlinger::~AudioFlinger() 232{ 233 int num_devs = mAudioHwDevs.size(); 234 235 while (!mRecordThreads.isEmpty()) { 236 // closeInput() will remove first entry from mRecordThreads 237 closeInput(mRecordThreads.keyAt(0)); 238 } 239 while (!mPlaybackThreads.isEmpty()) { 240 // closeOutput() will remove first entry from mPlaybackThreads 241 closeOutput(mPlaybackThreads.keyAt(0)); 242 } 243 244 for (int i = 0; i < num_devs; i++) { 245 audio_hw_device_t *dev = mAudioHwDevs[i]; 246 audio_hw_device_close(dev); 247 } 248} 249 250audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices) 251{ 252 /* first matching HW device is returned */ 253 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 254 audio_hw_device_t *dev = mAudioHwDevs[i]; 255 if ((dev->get_supported_devices(dev) & devices) == devices) 256 return dev; 257 } 258 return NULL; 259} 260 261status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args) 262{ 263 const size_t SIZE = 256; 264 char buffer[SIZE]; 265 String8 result; 266 267 result.append("Clients:\n"); 268 for (size_t i = 0; i < mClients.size(); ++i) { 269 sp<Client> client = mClients.valueAt(i).promote(); 270 if (client != 0) { 271 snprintf(buffer, SIZE, " pid: %d\n", client->pid()); 272 result.append(buffer); 273 } 274 } 275 276 result.append("Global session refs:\n"); 277 result.append(" session pid cnt\n"); 278 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) { 279 AudioSessionRef *r = mAudioSessionRefs[i]; 280 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt); 281 result.append(buffer); 282 } 283 write(fd, result.string(), result.size()); 284 return NO_ERROR; 285} 286 287 288status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args) 289{ 290 const size_t SIZE = 256; 291 char buffer[SIZE]; 292 String8 result; 293 hardware_call_state hardwareStatus = mHardwareStatus; 294 295 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus); 296 result.append(buffer); 297 write(fd, result.string(), result.size()); 298 return NO_ERROR; 299} 300 301status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args) 302{ 303 const size_t SIZE = 256; 304 char buffer[SIZE]; 305 String8 result; 306 snprintf(buffer, SIZE, "Permission Denial: " 307 "can't dump AudioFlinger from pid=%d, uid=%d\n", 308 IPCThreadState::self()->getCallingPid(), 309 IPCThreadState::self()->getCallingUid()); 310 result.append(buffer); 311 write(fd, result.string(), result.size()); 312 return NO_ERROR; 313} 314 315static bool tryLock(Mutex& mutex) 316{ 317 bool locked = false; 318 for (int i = 0; i < kDumpLockRetries; ++i) { 319 if (mutex.tryLock() == NO_ERROR) { 320 locked = true; 321 break; 322 } 323 usleep(kDumpLockSleepUs); 324 } 325 return locked; 326} 327 328status_t AudioFlinger::dump(int fd, const Vector<String16>& args) 329{ 330 if (!checkCallingPermission(String16("android.permission.DUMP"))) { 331 dumpPermissionDenial(fd, args); 332 } else { 333 // get state of hardware lock 334 bool hardwareLocked = tryLock(mHardwareLock); 335 if (!hardwareLocked) { 336 String8 result(kHardwareLockedString); 337 write(fd, result.string(), result.size()); 338 } else { 339 mHardwareLock.unlock(); 340 } 341 342 bool locked = tryLock(mLock); 343 344 // failed to lock - AudioFlinger is probably deadlocked 345 if (!locked) { 346 String8 result(kDeadlockedString); 347 write(fd, result.string(), result.size()); 348 } 349 350 dumpClients(fd, args); 351 dumpInternals(fd, args); 352 353 // dump playback threads 354 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 355 mPlaybackThreads.valueAt(i)->dump(fd, args); 356 } 357 358 // dump record threads 359 for (size_t i = 0; i < mRecordThreads.size(); i++) { 360 mRecordThreads.valueAt(i)->dump(fd, args); 361 } 362 363 // dump all hardware devs 364 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 365 audio_hw_device_t *dev = mAudioHwDevs[i]; 366 dev->dump(dev, fd); 367 } 368 if (locked) mLock.unlock(); 369 } 370 return NO_ERROR; 371} 372 373sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid) 374{ 375 // If pid is already in the mClients wp<> map, then use that entry 376 // (for which promote() is always != 0), otherwise create a new entry and Client. 377 sp<Client> client = mClients.valueFor(pid).promote(); 378 if (client == 0) { 379 client = new Client(this, pid); 380 mClients.add(pid, client); 381 } 382 383 return client; 384} 385 386// IAudioFlinger interface 387 388 389sp<IAudioTrack> AudioFlinger::createTrack( 390 pid_t pid, 391 audio_stream_type_t streamType, 392 uint32_t sampleRate, 393 audio_format_t format, 394 uint32_t channelMask, 395 int frameCount, 396 uint32_t flags, 397 const sp<IMemory>& sharedBuffer, 398 audio_io_handle_t output, 399 int *sessionId, 400 status_t *status) 401{ 402 sp<PlaybackThread::Track> track; 403 sp<TrackHandle> trackHandle; 404 sp<Client> client; 405 status_t lStatus; 406 int lSessionId; 407 408 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC, 409 // but if someone uses binder directly they could bypass that and cause us to crash 410 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) { 411 ALOGE("createTrack() invalid stream type %d", streamType); 412 lStatus = BAD_VALUE; 413 goto Exit; 414 } 415 416 { 417 Mutex::Autolock _l(mLock); 418 PlaybackThread *thread = checkPlaybackThread_l(output); 419 PlaybackThread *effectThread = NULL; 420 if (thread == NULL) { 421 ALOGE("unknown output thread"); 422 lStatus = BAD_VALUE; 423 goto Exit; 424 } 425 426 client = registerPid_l(pid); 427 428 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId); 429 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) { 430 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 431 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i); 432 if (mPlaybackThreads.keyAt(i) != output) { 433 // prevent same audio session on different output threads 434 uint32_t sessions = t->hasAudioSession(*sessionId); 435 if (sessions & PlaybackThread::TRACK_SESSION) { 436 ALOGE("createTrack() session ID %d already in use", *sessionId); 437 lStatus = BAD_VALUE; 438 goto Exit; 439 } 440 // check if an effect with same session ID is waiting for a track to be created 441 if (sessions & PlaybackThread::EFFECT_SESSION) { 442 effectThread = t.get(); 443 } 444 } 445 } 446 lSessionId = *sessionId; 447 } else { 448 // if no audio session id is provided, create one here 449 lSessionId = nextUniqueId(); 450 if (sessionId != NULL) { 451 *sessionId = lSessionId; 452 } 453 } 454 ALOGV("createTrack() lSessionId: %d", lSessionId); 455 456 track = thread->createTrack_l(client, streamType, sampleRate, format, 457 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus); 458 459 // move effect chain to this output thread if an effect on same session was waiting 460 // for a track to be created 461 if (lStatus == NO_ERROR && effectThread != NULL) { 462 Mutex::Autolock _dl(thread->mLock); 463 Mutex::Autolock _sl(effectThread->mLock); 464 moveEffectChain_l(lSessionId, effectThread, thread, true); 465 } 466 } 467 if (lStatus == NO_ERROR) { 468 trackHandle = new TrackHandle(track); 469 } else { 470 // remove local strong reference to Client before deleting the Track so that the Client 471 // destructor is called by the TrackBase destructor with mLock held 472 client.clear(); 473 track.clear(); 474 } 475 476Exit: 477 if(status) { 478 *status = lStatus; 479 } 480 return trackHandle; 481} 482 483uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const 484{ 485 Mutex::Autolock _l(mLock); 486 PlaybackThread *thread = checkPlaybackThread_l(output); 487 if (thread == NULL) { 488 ALOGW("sampleRate() unknown thread %d", output); 489 return 0; 490 } 491 return thread->sampleRate(); 492} 493 494int AudioFlinger::channelCount(audio_io_handle_t output) const 495{ 496 Mutex::Autolock _l(mLock); 497 PlaybackThread *thread = checkPlaybackThread_l(output); 498 if (thread == NULL) { 499 ALOGW("channelCount() unknown thread %d", output); 500 return 0; 501 } 502 return thread->channelCount(); 503} 504 505audio_format_t AudioFlinger::format(audio_io_handle_t output) const 506{ 507 Mutex::Autolock _l(mLock); 508 PlaybackThread *thread = checkPlaybackThread_l(output); 509 if (thread == NULL) { 510 ALOGW("format() unknown thread %d", output); 511 return AUDIO_FORMAT_INVALID; 512 } 513 return thread->format(); 514} 515 516size_t AudioFlinger::frameCount(audio_io_handle_t output) const 517{ 518 Mutex::Autolock _l(mLock); 519 PlaybackThread *thread = checkPlaybackThread_l(output); 520 if (thread == NULL) { 521 ALOGW("frameCount() unknown thread %d", output); 522 return 0; 523 } 524 return thread->frameCount(); 525} 526 527uint32_t AudioFlinger::latency(audio_io_handle_t output) const 528{ 529 Mutex::Autolock _l(mLock); 530 PlaybackThread *thread = checkPlaybackThread_l(output); 531 if (thread == NULL) { 532 ALOGW("latency() unknown thread %d", output); 533 return 0; 534 } 535 return thread->latency(); 536} 537 538status_t AudioFlinger::setMasterVolume(float value) 539{ 540 status_t ret = initCheck(); 541 if (ret != NO_ERROR) { 542 return ret; 543 } 544 545 // check calling permissions 546 if (!settingsAllowed()) { 547 return PERMISSION_DENIED; 548 } 549 550 // when hw supports master volume, don't scale in sw mixer 551 { // scope for the lock 552 AutoMutex lock(mHardwareLock); 553 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME; 554 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) { 555 value = 1.0f; 556 } 557 mHardwareStatus = AUDIO_HW_IDLE; 558 } 559 560 Mutex::Autolock _l(mLock); 561 mMasterVolume = value; 562 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) 563 mPlaybackThreads.valueAt(i)->setMasterVolume(value); 564 565 return NO_ERROR; 566} 567 568status_t AudioFlinger::setMode(audio_mode_t mode) 569{ 570 status_t ret = initCheck(); 571 if (ret != NO_ERROR) { 572 return ret; 573 } 574 575 // check calling permissions 576 if (!settingsAllowed()) { 577 return PERMISSION_DENIED; 578 } 579 if (uint32_t(mode) >= AUDIO_MODE_CNT) { 580 ALOGW("Illegal value: setMode(%d)", mode); 581 return BAD_VALUE; 582 } 583 584 { // scope for the lock 585 AutoMutex lock(mHardwareLock); 586 mHardwareStatus = AUDIO_HW_SET_MODE; 587 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode); 588 mHardwareStatus = AUDIO_HW_IDLE; 589 } 590 591 if (NO_ERROR == ret) { 592 Mutex::Autolock _l(mLock); 593 mMode = mode; 594 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) 595 mPlaybackThreads.valueAt(i)->setMode(mode); 596 } 597 598 return ret; 599} 600 601status_t AudioFlinger::setMicMute(bool state) 602{ 603 status_t ret = initCheck(); 604 if (ret != NO_ERROR) { 605 return ret; 606 } 607 608 // check calling permissions 609 if (!settingsAllowed()) { 610 return PERMISSION_DENIED; 611 } 612 613 AutoMutex lock(mHardwareLock); 614 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE; 615 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state); 616 mHardwareStatus = AUDIO_HW_IDLE; 617 return ret; 618} 619 620bool AudioFlinger::getMicMute() const 621{ 622 status_t ret = initCheck(); 623 if (ret != NO_ERROR) { 624 return false; 625 } 626 627 bool state = AUDIO_MODE_INVALID; 628 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE; 629 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state); 630 mHardwareStatus = AUDIO_HW_IDLE; 631 return state; 632} 633 634status_t AudioFlinger::setMasterMute(bool muted) 635{ 636 // check calling permissions 637 if (!settingsAllowed()) { 638 return PERMISSION_DENIED; 639 } 640 641 Mutex::Autolock _l(mLock); 642 mMasterMute = muted; 643 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) 644 mPlaybackThreads.valueAt(i)->setMasterMute(muted); 645 646 return NO_ERROR; 647} 648 649float AudioFlinger::masterVolume() const 650{ 651 Mutex::Autolock _l(mLock); 652 return masterVolume_l(); 653} 654 655bool AudioFlinger::masterMute() const 656{ 657 Mutex::Autolock _l(mLock); 658 return masterMute_l(); 659} 660 661status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value, 662 audio_io_handle_t output) 663{ 664 // check calling permissions 665 if (!settingsAllowed()) { 666 return PERMISSION_DENIED; 667 } 668 669 if (uint32_t(stream) >= AUDIO_STREAM_CNT) { 670 ALOGE("setStreamVolume() invalid stream %d", stream); 671 return BAD_VALUE; 672 } 673 674 AutoMutex lock(mLock); 675 PlaybackThread *thread = NULL; 676 if (output) { 677 thread = checkPlaybackThread_l(output); 678 if (thread == NULL) { 679 return BAD_VALUE; 680 } 681 } 682 683 mStreamTypes[stream].volume = value; 684 685 if (thread == NULL) { 686 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) { 687 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value); 688 } 689 } else { 690 thread->setStreamVolume(stream, value); 691 } 692 693 return NO_ERROR; 694} 695 696status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted) 697{ 698 // check calling permissions 699 if (!settingsAllowed()) { 700 return PERMISSION_DENIED; 701 } 702 703 if (uint32_t(stream) >= AUDIO_STREAM_CNT || 704 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) { 705 ALOGE("setStreamMute() invalid stream %d", stream); 706 return BAD_VALUE; 707 } 708 709 AutoMutex lock(mLock); 710 mStreamTypes[stream].mute = muted; 711 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) 712 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted); 713 714 return NO_ERROR; 715} 716 717float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const 718{ 719 if (uint32_t(stream) >= AUDIO_STREAM_CNT) { 720 return 0.0f; 721 } 722 723 AutoMutex lock(mLock); 724 float volume; 725 if (output) { 726 PlaybackThread *thread = checkPlaybackThread_l(output); 727 if (thread == NULL) { 728 return 0.0f; 729 } 730 volume = thread->streamVolume(stream); 731 } else { 732 volume = mStreamTypes[stream].volume; 733 } 734 735 return volume; 736} 737 738bool AudioFlinger::streamMute(audio_stream_type_t stream) const 739{ 740 if (uint32_t(stream) >= AUDIO_STREAM_CNT) { 741 return true; 742 } 743 744 return mStreamTypes[stream].mute; 745} 746 747status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs) 748{ 749 status_t result; 750 751 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d", 752 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid()); 753 // check calling permissions 754 if (!settingsAllowed()) { 755 return PERMISSION_DENIED; 756 } 757 758 // ioHandle == 0 means the parameters are global to the audio hardware interface 759 if (ioHandle == 0) { 760 AutoMutex lock(mHardwareLock); 761 mHardwareStatus = AUDIO_SET_PARAMETER; 762 status_t final_result = NO_ERROR; 763 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 764 audio_hw_device_t *dev = mAudioHwDevs[i]; 765 result = dev->set_parameters(dev, keyValuePairs.string()); 766 final_result = result ?: final_result; 767 } 768 mHardwareStatus = AUDIO_HW_IDLE; 769 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 770 AudioParameter param = AudioParameter(keyValuePairs); 771 String8 value; 772 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) { 773 Mutex::Autolock _l(mLock); 774 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF); 775 if (mBtNrecIsOff != btNrecIsOff) { 776 for (size_t i = 0; i < mRecordThreads.size(); i++) { 777 sp<RecordThread> thread = mRecordThreads.valueAt(i); 778 RecordThread::RecordTrack *track = thread->track(); 779 if (track != NULL) { 780 audio_devices_t device = (audio_devices_t)( 781 thread->device() & AUDIO_DEVICE_IN_ALL); 782 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff; 783 thread->setEffectSuspended(FX_IID_AEC, 784 suspend, 785 track->sessionId()); 786 thread->setEffectSuspended(FX_IID_NS, 787 suspend, 788 track->sessionId()); 789 } 790 } 791 mBtNrecIsOff = btNrecIsOff; 792 } 793 } 794 return final_result; 795 } 796 797 // hold a strong ref on thread in case closeOutput() or closeInput() is called 798 // and the thread is exited once the lock is released 799 sp<ThreadBase> thread; 800 { 801 Mutex::Autolock _l(mLock); 802 thread = checkPlaybackThread_l(ioHandle); 803 if (thread == NULL) { 804 thread = checkRecordThread_l(ioHandle); 805 } else if (thread == primaryPlaybackThread_l()) { 806 // indicate output device change to all input threads for pre processing 807 AudioParameter param = AudioParameter(keyValuePairs); 808 int value; 809 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 810 for (size_t i = 0; i < mRecordThreads.size(); i++) { 811 mRecordThreads.valueAt(i)->setParameters(keyValuePairs); 812 } 813 } 814 } 815 } 816 if (thread != 0) { 817 return thread->setParameters(keyValuePairs); 818 } 819 return BAD_VALUE; 820} 821 822String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const 823{ 824// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d", 825// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid()); 826 827 if (ioHandle == 0) { 828 String8 out_s8; 829 830 for (size_t i = 0; i < mAudioHwDevs.size(); i++) { 831 audio_hw_device_t *dev = mAudioHwDevs[i]; 832 char *s = dev->get_parameters(dev, keys.string()); 833 out_s8 += String8(s); 834 free(s); 835 } 836 return out_s8; 837 } 838 839 Mutex::Autolock _l(mLock); 840 841 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle); 842 if (playbackThread != NULL) { 843 return playbackThread->getParameters(keys); 844 } 845 RecordThread *recordThread = checkRecordThread_l(ioHandle); 846 if (recordThread != NULL) { 847 return recordThread->getParameters(keys); 848 } 849 return String8(""); 850} 851 852size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const 853{ 854 status_t ret = initCheck(); 855 if (ret != NO_ERROR) { 856 return 0; 857 } 858 859 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount); 860} 861 862unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const 863{ 864 if (ioHandle == 0) { 865 return 0; 866 } 867 868 Mutex::Autolock _l(mLock); 869 870 RecordThread *recordThread = checkRecordThread_l(ioHandle); 871 if (recordThread != NULL) { 872 return recordThread->getInputFramesLost(); 873 } 874 return 0; 875} 876 877status_t AudioFlinger::setVoiceVolume(float value) 878{ 879 status_t ret = initCheck(); 880 if (ret != NO_ERROR) { 881 return ret; 882 } 883 884 // check calling permissions 885 if (!settingsAllowed()) { 886 return PERMISSION_DENIED; 887 } 888 889 AutoMutex lock(mHardwareLock); 890 mHardwareStatus = AUDIO_SET_VOICE_VOLUME; 891 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value); 892 mHardwareStatus = AUDIO_HW_IDLE; 893 894 return ret; 895} 896 897status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, 898 audio_io_handle_t output) const 899{ 900 status_t status; 901 902 Mutex::Autolock _l(mLock); 903 904 PlaybackThread *playbackThread = checkPlaybackThread_l(output); 905 if (playbackThread != NULL) { 906 return playbackThread->getRenderPosition(halFrames, dspFrames); 907 } 908 909 return BAD_VALUE; 910} 911 912void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client) 913{ 914 915 Mutex::Autolock _l(mLock); 916 917 pid_t pid = IPCThreadState::self()->getCallingPid(); 918 if (mNotificationClients.indexOfKey(pid) < 0) { 919 sp<NotificationClient> notificationClient = new NotificationClient(this, 920 client, 921 pid); 922 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid); 923 924 mNotificationClients.add(pid, notificationClient); 925 926 sp<IBinder> binder = client->asBinder(); 927 binder->linkToDeath(notificationClient); 928 929 // the config change is always sent from playback or record threads to avoid deadlock 930 // with AudioSystem::gLock 931 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 932 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED); 933 } 934 935 for (size_t i = 0; i < mRecordThreads.size(); i++) { 936 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED); 937 } 938 } 939} 940 941void AudioFlinger::removeNotificationClient(pid_t pid) 942{ 943 Mutex::Autolock _l(mLock); 944 945 int index = mNotificationClients.indexOfKey(pid); 946 if (index >= 0) { 947 sp <NotificationClient> client = mNotificationClients.valueFor(pid); 948 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid); 949 mNotificationClients.removeItem(pid); 950 } 951 952 ALOGV("%d died, releasing its sessions", pid); 953 int num = mAudioSessionRefs.size(); 954 bool removed = false; 955 for (int i = 0; i< num; i++) { 956 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i); 957 ALOGV(" pid %d @ %d", ref->pid, i); 958 if (ref->pid == pid) { 959 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid); 960 mAudioSessionRefs.removeAt(i); 961 delete ref; 962 removed = true; 963 i--; 964 num--; 965 } 966 } 967 if (removed) { 968 purgeStaleEffects_l(); 969 } 970} 971 972// audioConfigChanged_l() must be called with AudioFlinger::mLock held 973void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, void *param2) 974{ 975 size_t size = mNotificationClients.size(); 976 for (size_t i = 0; i < size; i++) { 977 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle, 978 param2); 979 } 980} 981 982// removeClient_l() must be called with AudioFlinger::mLock held 983void AudioFlinger::removeClient_l(pid_t pid) 984{ 985 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid()); 986 mClients.removeItem(pid); 987} 988 989 990// ---------------------------------------------------------------------------- 991 992AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id, 993 uint32_t device, type_t type) 994 : Thread(false), 995 mType(type), 996 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), 997 // mChannelMask 998 mChannelCount(0), 999 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID), 1000 mParamStatus(NO_ERROR), 1001 mStandby(false), mId(id), mExiting(false), 1002 mDevice(device), 1003 mDeathRecipient(new PMDeathRecipient(this)) 1004{ 1005} 1006 1007AudioFlinger::ThreadBase::~ThreadBase() 1008{ 1009 mParamCond.broadcast(); 1010 // do not lock the mutex in destructor 1011 releaseWakeLock_l(); 1012 if (mPowerManager != 0) { 1013 sp<IBinder> binder = mPowerManager->asBinder(); 1014 binder->unlinkToDeath(mDeathRecipient); 1015 } 1016} 1017 1018void AudioFlinger::ThreadBase::exit() 1019{ 1020 // keep a strong ref on ourself so that we won't get 1021 // destroyed in the middle of requestExitAndWait() 1022 sp <ThreadBase> strongMe = this; 1023 1024 ALOGV("ThreadBase::exit"); 1025 { 1026 AutoMutex lock(mLock); 1027 mExiting = true; 1028 requestExit(); 1029 mWaitWorkCV.signal(); 1030 } 1031 requestExitAndWait(); 1032} 1033 1034status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs) 1035{ 1036 status_t status; 1037 1038 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string()); 1039 Mutex::Autolock _l(mLock); 1040 1041 mNewParameters.add(keyValuePairs); 1042 mWaitWorkCV.signal(); 1043 // wait condition with timeout in case the thread loop has exited 1044 // before the request could be processed 1045 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) { 1046 status = mParamStatus; 1047 mWaitWorkCV.signal(); 1048 } else { 1049 status = TIMED_OUT; 1050 } 1051 return status; 1052} 1053 1054void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param) 1055{ 1056 Mutex::Autolock _l(mLock); 1057 sendConfigEvent_l(event, param); 1058} 1059 1060// sendConfigEvent_l() must be called with ThreadBase::mLock held 1061void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param) 1062{ 1063 ConfigEvent configEvent; 1064 configEvent.mEvent = event; 1065 configEvent.mParam = param; 1066 mConfigEvents.add(configEvent); 1067 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param); 1068 mWaitWorkCV.signal(); 1069} 1070 1071void AudioFlinger::ThreadBase::processConfigEvents() 1072{ 1073 mLock.lock(); 1074 while(!mConfigEvents.isEmpty()) { 1075 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size()); 1076 ConfigEvent configEvent = mConfigEvents[0]; 1077 mConfigEvents.removeAt(0); 1078 // release mLock before locking AudioFlinger mLock: lock order is always 1079 // AudioFlinger then ThreadBase to avoid cross deadlock 1080 mLock.unlock(); 1081 mAudioFlinger->mLock.lock(); 1082 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam); 1083 mAudioFlinger->mLock.unlock(); 1084 mLock.lock(); 1085 } 1086 mLock.unlock(); 1087} 1088 1089status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args) 1090{ 1091 const size_t SIZE = 256; 1092 char buffer[SIZE]; 1093 String8 result; 1094 1095 bool locked = tryLock(mLock); 1096 if (!locked) { 1097 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this); 1098 write(fd, buffer, strlen(buffer)); 1099 } 1100 1101 snprintf(buffer, SIZE, "standby: %d\n", mStandby); 1102 result.append(buffer); 1103 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate); 1104 result.append(buffer); 1105 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount); 1106 result.append(buffer); 1107 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount); 1108 result.append(buffer); 1109 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask); 1110 result.append(buffer); 1111 snprintf(buffer, SIZE, "Format: %d\n", mFormat); 1112 result.append(buffer); 1113 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize); 1114 result.append(buffer); 1115 1116 snprintf(buffer, SIZE, "\nPending setParameters commands: \n"); 1117 result.append(buffer); 1118 result.append(" Index Command"); 1119 for (size_t i = 0; i < mNewParameters.size(); ++i) { 1120 snprintf(buffer, SIZE, "\n %02d ", i); 1121 result.append(buffer); 1122 result.append(mNewParameters[i]); 1123 } 1124 1125 snprintf(buffer, SIZE, "\n\nPending config events: \n"); 1126 result.append(buffer); 1127 snprintf(buffer, SIZE, " Index event param\n"); 1128 result.append(buffer); 1129 for (size_t i = 0; i < mConfigEvents.size(); i++) { 1130 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam); 1131 result.append(buffer); 1132 } 1133 result.append("\n"); 1134 1135 write(fd, result.string(), result.size()); 1136 1137 if (locked) { 1138 mLock.unlock(); 1139 } 1140 return NO_ERROR; 1141} 1142 1143status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args) 1144{ 1145 const size_t SIZE = 256; 1146 char buffer[SIZE]; 1147 String8 result; 1148 1149 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size()); 1150 write(fd, buffer, strlen(buffer)); 1151 1152 for (size_t i = 0; i < mEffectChains.size(); ++i) { 1153 sp<EffectChain> chain = mEffectChains[i]; 1154 if (chain != 0) { 1155 chain->dump(fd, args); 1156 } 1157 } 1158 return NO_ERROR; 1159} 1160 1161void AudioFlinger::ThreadBase::acquireWakeLock() 1162{ 1163 Mutex::Autolock _l(mLock); 1164 acquireWakeLock_l(); 1165} 1166 1167void AudioFlinger::ThreadBase::acquireWakeLock_l() 1168{ 1169 if (mPowerManager == 0) { 1170 // use checkService() to avoid blocking if power service is not up yet 1171 sp<IBinder> binder = 1172 defaultServiceManager()->checkService(String16("power")); 1173 if (binder == 0) { 1174 ALOGW("Thread %s cannot connect to the power manager service", mName); 1175 } else { 1176 mPowerManager = interface_cast<IPowerManager>(binder); 1177 binder->linkToDeath(mDeathRecipient); 1178 } 1179 } 1180 if (mPowerManager != 0) { 1181 sp<IBinder> binder = new BBinder(); 1182 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK, 1183 binder, 1184 String16(mName)); 1185 if (status == NO_ERROR) { 1186 mWakeLockToken = binder; 1187 } 1188 ALOGV("acquireWakeLock_l() %s status %d", mName, status); 1189 } 1190} 1191 1192void AudioFlinger::ThreadBase::releaseWakeLock() 1193{ 1194 Mutex::Autolock _l(mLock); 1195 releaseWakeLock_l(); 1196} 1197 1198void AudioFlinger::ThreadBase::releaseWakeLock_l() 1199{ 1200 if (mWakeLockToken != 0) { 1201 ALOGV("releaseWakeLock_l() %s", mName); 1202 if (mPowerManager != 0) { 1203 mPowerManager->releaseWakeLock(mWakeLockToken, 0); 1204 } 1205 mWakeLockToken.clear(); 1206 } 1207} 1208 1209void AudioFlinger::ThreadBase::clearPowerManager() 1210{ 1211 Mutex::Autolock _l(mLock); 1212 releaseWakeLock_l(); 1213 mPowerManager.clear(); 1214} 1215 1216void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who) 1217{ 1218 sp<ThreadBase> thread = mThread.promote(); 1219 if (thread != 0) { 1220 thread->clearPowerManager(); 1221 } 1222 ALOGW("power manager service died !!!"); 1223} 1224 1225void AudioFlinger::ThreadBase::setEffectSuspended( 1226 const effect_uuid_t *type, bool suspend, int sessionId) 1227{ 1228 Mutex::Autolock _l(mLock); 1229 setEffectSuspended_l(type, suspend, sessionId); 1230} 1231 1232void AudioFlinger::ThreadBase::setEffectSuspended_l( 1233 const effect_uuid_t *type, bool suspend, int sessionId) 1234{ 1235 sp<EffectChain> chain = getEffectChain_l(sessionId); 1236 if (chain != 0) { 1237 if (type != NULL) { 1238 chain->setEffectSuspended_l(type, suspend); 1239 } else { 1240 chain->setEffectSuspendedAll_l(suspend); 1241 } 1242 } 1243 1244 updateSuspendedSessions_l(type, suspend, sessionId); 1245} 1246 1247void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain) 1248{ 1249 int index = mSuspendedSessions.indexOfKey(chain->sessionId()); 1250 if (index < 0) { 1251 return; 1252 } 1253 1254 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects = 1255 mSuspendedSessions.editValueAt(index); 1256 1257 for (size_t i = 0; i < sessionEffects.size(); i++) { 1258 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i); 1259 for (int j = 0; j < desc->mRefCount; j++) { 1260 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) { 1261 chain->setEffectSuspendedAll_l(true); 1262 } else { 1263 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x", 1264 desc->mType.timeLow); 1265 chain->setEffectSuspended_l(&desc->mType, true); 1266 } 1267 } 1268 } 1269} 1270 1271void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type, 1272 bool suspend, 1273 int sessionId) 1274{ 1275 int index = mSuspendedSessions.indexOfKey(sessionId); 1276 1277 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects; 1278 1279 if (suspend) { 1280 if (index >= 0) { 1281 sessionEffects = mSuspendedSessions.editValueAt(index); 1282 } else { 1283 mSuspendedSessions.add(sessionId, sessionEffects); 1284 } 1285 } else { 1286 if (index < 0) { 1287 return; 1288 } 1289 sessionEffects = mSuspendedSessions.editValueAt(index); 1290 } 1291 1292 1293 int key = EffectChain::kKeyForSuspendAll; 1294 if (type != NULL) { 1295 key = type->timeLow; 1296 } 1297 index = sessionEffects.indexOfKey(key); 1298 1299 sp <SuspendedSessionDesc> desc; 1300 if (suspend) { 1301 if (index >= 0) { 1302 desc = sessionEffects.valueAt(index); 1303 } else { 1304 desc = new SuspendedSessionDesc(); 1305 if (type != NULL) { 1306 memcpy(&desc->mType, type, sizeof(effect_uuid_t)); 1307 } 1308 sessionEffects.add(key, desc); 1309 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key); 1310 } 1311 desc->mRefCount++; 1312 } else { 1313 if (index < 0) { 1314 return; 1315 } 1316 desc = sessionEffects.valueAt(index); 1317 if (--desc->mRefCount == 0) { 1318 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key); 1319 sessionEffects.removeItemsAt(index); 1320 if (sessionEffects.isEmpty()) { 1321 ALOGV("updateSuspendedSessions_l() restore removing session %d", 1322 sessionId); 1323 mSuspendedSessions.removeItem(sessionId); 1324 } 1325 } 1326 } 1327 if (!sessionEffects.isEmpty()) { 1328 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects); 1329 } 1330} 1331 1332void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect, 1333 bool enabled, 1334 int sessionId) 1335{ 1336 Mutex::Autolock _l(mLock); 1337 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId); 1338} 1339 1340void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect, 1341 bool enabled, 1342 int sessionId) 1343{ 1344 if (mType != RECORD) { 1345 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on 1346 // another session. This gives the priority to well behaved effect control panels 1347 // and applications not using global effects. 1348 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) { 1349 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX); 1350 } 1351 } 1352 1353 sp<EffectChain> chain = getEffectChain_l(sessionId); 1354 if (chain != 0) { 1355 chain->checkSuspendOnEffectEnabled(effect, enabled); 1356 } 1357} 1358 1359// ---------------------------------------------------------------------------- 1360 1361AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, 1362 AudioStreamOut* output, 1363 audio_io_handle_t id, 1364 uint32_t device, 1365 type_t type) 1366 : ThreadBase(audioFlinger, id, device, type), 1367 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0), 1368 // Assumes constructor is called by AudioFlinger with it's mLock held, 1369 // but it would be safer to explicitly pass initial masterMute as parameter 1370 mMasterMute(audioFlinger->masterMute_l()), 1371 // mStreamTypes[] initialized in constructor body 1372 mOutput(output), 1373 // Assumes constructor is called by AudioFlinger with it's mLock held, 1374 // but it would be safer to explicitly pass initial masterVolume as parameter 1375 mMasterVolume(audioFlinger->masterVolume_l()), 1376 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false) 1377{ 1378 snprintf(mName, kNameLength, "AudioOut_%d", id); 1379 1380 readOutputParameters(); 1381 1382 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor 1383 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile 1384 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT; 1385 stream = (audio_stream_type_t) (stream + 1)) { 1386 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream); 1387 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream); 1388 // initialized by stream_type_t default constructor 1389 // mStreamTypes[stream].valid = true; 1390 } 1391} 1392 1393AudioFlinger::PlaybackThread::~PlaybackThread() 1394{ 1395 delete [] mMixBuffer; 1396} 1397 1398status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args) 1399{ 1400 dumpInternals(fd, args); 1401 dumpTracks(fd, args); 1402 dumpEffectChains(fd, args); 1403 return NO_ERROR; 1404} 1405 1406status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args) 1407{ 1408 const size_t SIZE = 256; 1409 char buffer[SIZE]; 1410 String8 result; 1411 1412 snprintf(buffer, SIZE, "Output thread %p tracks\n", this); 1413 result.append(buffer); 1414 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n"); 1415 for (size_t i = 0; i < mTracks.size(); ++i) { 1416 sp<Track> track = mTracks[i]; 1417 if (track != 0) { 1418 track->dump(buffer, SIZE); 1419 result.append(buffer); 1420 } 1421 } 1422 1423 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this); 1424 result.append(buffer); 1425 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n"); 1426 for (size_t i = 0; i < mActiveTracks.size(); ++i) { 1427 sp<Track> track = mActiveTracks[i].promote(); 1428 if (track != 0) { 1429 track->dump(buffer, SIZE); 1430 result.append(buffer); 1431 } 1432 } 1433 write(fd, result.string(), result.size()); 1434 return NO_ERROR; 1435} 1436 1437status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args) 1438{ 1439 const size_t SIZE = 256; 1440 char buffer[SIZE]; 1441 String8 result; 1442 1443 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this); 1444 result.append(buffer); 1445 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime)); 1446 result.append(buffer); 1447 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites); 1448 result.append(buffer); 1449 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites); 1450 result.append(buffer); 1451 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite); 1452 result.append(buffer); 1453 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended); 1454 result.append(buffer); 1455 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer); 1456 result.append(buffer); 1457 write(fd, result.string(), result.size()); 1458 1459 dumpBase(fd, args); 1460 1461 return NO_ERROR; 1462} 1463 1464// Thread virtuals 1465status_t AudioFlinger::PlaybackThread::readyToRun() 1466{ 1467 status_t status = initCheck(); 1468 if (status == NO_ERROR) { 1469 ALOGI("AudioFlinger's thread %p ready to run", this); 1470 } else { 1471 ALOGE("No working audio driver found."); 1472 } 1473 return status; 1474} 1475 1476void AudioFlinger::PlaybackThread::onFirstRef() 1477{ 1478 run(mName, ANDROID_PRIORITY_URGENT_AUDIO); 1479} 1480 1481// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held 1482sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l( 1483 const sp<AudioFlinger::Client>& client, 1484 audio_stream_type_t streamType, 1485 uint32_t sampleRate, 1486 audio_format_t format, 1487 uint32_t channelMask, 1488 int frameCount, 1489 const sp<IMemory>& sharedBuffer, 1490 int sessionId, 1491 status_t *status) 1492{ 1493 sp<Track> track; 1494 status_t lStatus; 1495 1496 if (mType == DIRECT) { 1497 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) { 1498 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) { 1499 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \"" 1500 "for output %p with format %d", 1501 sampleRate, format, channelMask, mOutput, mFormat); 1502 lStatus = BAD_VALUE; 1503 goto Exit; 1504 } 1505 } 1506 } else { 1507 // Resampler implementation limits input sampling rate to 2 x output sampling rate. 1508 if (sampleRate > mSampleRate*2) { 1509 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate); 1510 lStatus = BAD_VALUE; 1511 goto Exit; 1512 } 1513 } 1514 1515 lStatus = initCheck(); 1516 if (lStatus != NO_ERROR) { 1517 ALOGE("Audio driver not initialized."); 1518 goto Exit; 1519 } 1520 1521 { // scope for mLock 1522 Mutex::Autolock _l(mLock); 1523 1524 // all tracks in same audio session must share the same routing strategy otherwise 1525 // conflicts will happen when tracks are moved from one output to another by audio policy 1526 // manager 1527 uint32_t strategy = 1528 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType); 1529 for (size_t i = 0; i < mTracks.size(); ++i) { 1530 sp<Track> t = mTracks[i]; 1531 if (t != 0) { 1532 uint32_t actual = AudioSystem::getStrategyForStream((audio_stream_type_t)t->type()); 1533 if (sessionId == t->sessionId() && strategy != actual) { 1534 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u", 1535 strategy, actual); 1536 lStatus = BAD_VALUE; 1537 goto Exit; 1538 } 1539 } 1540 } 1541 1542 track = new Track(this, client, streamType, sampleRate, format, 1543 channelMask, frameCount, sharedBuffer, sessionId); 1544 if (track->getCblk() == NULL || track->name() < 0) { 1545 lStatus = NO_MEMORY; 1546 goto Exit; 1547 } 1548 mTracks.add(track); 1549 1550 sp<EffectChain> chain = getEffectChain_l(sessionId); 1551 if (chain != 0) { 1552 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer()); 1553 track->setMainBuffer(chain->inBuffer()); 1554 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type())); 1555 chain->incTrackCnt(); 1556 } 1557 1558 // invalidate track immediately if the stream type was moved to another thread since 1559 // createTrack() was called by the client process. 1560 if (!mStreamTypes[streamType].valid) { 1561 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d", 1562 this, streamType); 1563 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags); 1564 } 1565 } 1566 lStatus = NO_ERROR; 1567 1568Exit: 1569 if(status) { 1570 *status = lStatus; 1571 } 1572 return track; 1573} 1574 1575uint32_t AudioFlinger::PlaybackThread::latency() const 1576{ 1577 Mutex::Autolock _l(mLock); 1578 if (initCheck() == NO_ERROR) { 1579 return mOutput->stream->get_latency(mOutput->stream); 1580 } else { 1581 return 0; 1582 } 1583} 1584 1585status_t AudioFlinger::PlaybackThread::setMasterVolume(float value) 1586{ 1587 mMasterVolume = value; 1588 return NO_ERROR; 1589} 1590 1591status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted) 1592{ 1593 mMasterMute = muted; 1594 return NO_ERROR; 1595} 1596 1597status_t AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value) 1598{ 1599 mStreamTypes[stream].volume = value; 1600 return NO_ERROR; 1601} 1602 1603status_t AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted) 1604{ 1605 mStreamTypes[stream].mute = muted; 1606 return NO_ERROR; 1607} 1608 1609float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const 1610{ 1611 return mStreamTypes[stream].volume; 1612} 1613 1614bool AudioFlinger::PlaybackThread::streamMute(audio_stream_type_t stream) const 1615{ 1616 return mStreamTypes[stream].mute; 1617} 1618 1619// addTrack_l() must be called with ThreadBase::mLock held 1620status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track) 1621{ 1622 status_t status = ALREADY_EXISTS; 1623 1624 // set retry count for buffer fill 1625 track->mRetryCount = kMaxTrackStartupRetries; 1626 if (mActiveTracks.indexOf(track) < 0) { 1627 // the track is newly added, make sure it fills up all its 1628 // buffers before playing. This is to ensure the client will 1629 // effectively get the latency it requested. 1630 track->mFillingUpStatus = Track::FS_FILLING; 1631 track->mResetDone = false; 1632 mActiveTracks.add(track); 1633 if (track->mainBuffer() != mMixBuffer) { 1634 sp<EffectChain> chain = getEffectChain_l(track->sessionId()); 1635 if (chain != 0) { 1636 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId()); 1637 chain->incActiveTrackCnt(); 1638 } 1639 } 1640 1641 status = NO_ERROR; 1642 } 1643 1644 ALOGV("mWaitWorkCV.broadcast"); 1645 mWaitWorkCV.broadcast(); 1646 1647 return status; 1648} 1649 1650// destroyTrack_l() must be called with ThreadBase::mLock held 1651void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track) 1652{ 1653 track->mState = TrackBase::TERMINATED; 1654 if (mActiveTracks.indexOf(track) < 0) { 1655 removeTrack_l(track); 1656 } 1657} 1658 1659void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track) 1660{ 1661 mTracks.remove(track); 1662 deleteTrackName_l(track->name()); 1663 sp<EffectChain> chain = getEffectChain_l(track->sessionId()); 1664 if (chain != 0) { 1665 chain->decTrackCnt(); 1666 } 1667} 1668 1669String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys) 1670{ 1671 String8 out_s8 = String8(""); 1672 char *s; 1673 1674 Mutex::Autolock _l(mLock); 1675 if (initCheck() != NO_ERROR) { 1676 return out_s8; 1677 } 1678 1679 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string()); 1680 out_s8 = String8(s); 1681 free(s); 1682 return out_s8; 1683} 1684 1685// audioConfigChanged_l() must be called with AudioFlinger::mLock held 1686void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) { 1687 AudioSystem::OutputDescriptor desc; 1688 void *param2 = NULL; 1689 1690 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param); 1691 1692 switch (event) { 1693 case AudioSystem::OUTPUT_OPENED: 1694 case AudioSystem::OUTPUT_CONFIG_CHANGED: 1695 desc.channels = mChannelMask; 1696 desc.samplingRate = mSampleRate; 1697 desc.format = mFormat; 1698 desc.frameCount = mFrameCount; 1699 desc.latency = latency(); 1700 param2 = &desc; 1701 break; 1702 1703 case AudioSystem::STREAM_CONFIG_CHANGED: 1704 param2 = ¶m; 1705 case AudioSystem::OUTPUT_CLOSED: 1706 default: 1707 break; 1708 } 1709 mAudioFlinger->audioConfigChanged_l(event, mId, param2); 1710} 1711 1712void AudioFlinger::PlaybackThread::readOutputParameters() 1713{ 1714 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common); 1715 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common); 1716 mChannelCount = (uint16_t)popcount(mChannelMask); 1717 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common); 1718 mFrameSize = audio_stream_frame_size(&mOutput->stream->common); 1719 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize; 1720 1721 // FIXME - Current mixer implementation only supports stereo output: Always 1722 // Allocate a stereo buffer even if HW output is mono. 1723 delete[] mMixBuffer; 1724 mMixBuffer = new int16_t[mFrameCount * 2]; 1725 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t)); 1726 1727 // force reconfiguration of effect chains and engines to take new buffer size and audio 1728 // parameters into account 1729 // Note that mLock is not held when readOutputParameters() is called from the constructor 1730 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't 1731 // matter. 1732 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains 1733 Vector< sp<EffectChain> > effectChains = mEffectChains; 1734 for (size_t i = 0; i < effectChains.size(); i ++) { 1735 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false); 1736 } 1737} 1738 1739status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames) 1740{ 1741 if (halFrames == NULL || dspFrames == NULL) { 1742 return BAD_VALUE; 1743 } 1744 Mutex::Autolock _l(mLock); 1745 if (initCheck() != NO_ERROR) { 1746 return INVALID_OPERATION; 1747 } 1748 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common); 1749 1750 return mOutput->stream->get_render_position(mOutput->stream, dspFrames); 1751} 1752 1753uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) 1754{ 1755 Mutex::Autolock _l(mLock); 1756 uint32_t result = 0; 1757 if (getEffectChain_l(sessionId) != 0) { 1758 result = EFFECT_SESSION; 1759 } 1760 1761 for (size_t i = 0; i < mTracks.size(); ++i) { 1762 sp<Track> track = mTracks[i]; 1763 if (sessionId == track->sessionId() && 1764 !(track->mCblk->flags & CBLK_INVALID_MSK)) { 1765 result |= TRACK_SESSION; 1766 break; 1767 } 1768 } 1769 1770 return result; 1771} 1772 1773uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId) 1774{ 1775 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that 1776 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected 1777 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) { 1778 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); 1779 } 1780 for (size_t i = 0; i < mTracks.size(); i++) { 1781 sp<Track> track = mTracks[i]; 1782 if (sessionId == track->sessionId() && 1783 !(track->mCblk->flags & CBLK_INVALID_MSK)) { 1784 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type()); 1785 } 1786 } 1787 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); 1788} 1789 1790 1791AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const 1792{ 1793 Mutex::Autolock _l(mLock); 1794 return mOutput; 1795} 1796 1797AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput() 1798{ 1799 Mutex::Autolock _l(mLock); 1800 AudioStreamOut *output = mOutput; 1801 mOutput = NULL; 1802 return output; 1803} 1804 1805// this method must always be called either with ThreadBase mLock held or inside the thread loop 1806audio_stream_t* AudioFlinger::PlaybackThread::stream() 1807{ 1808 if (mOutput == NULL) { 1809 return NULL; 1810 } 1811 return &mOutput->stream->common; 1812} 1813 1814uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() 1815{ 1816 // A2DP output latency is not due only to buffering capacity. It also reflects encoding, 1817 // decoding and transfer time. So sleeping for half of the latency would likely cause 1818 // underruns 1819 if (audio_is_a2dp_device((audio_devices_t)mDevice)) { 1820 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000); 1821 } else { 1822 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2; 1823 } 1824} 1825 1826// ---------------------------------------------------------------------------- 1827 1828AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, 1829 audio_io_handle_t id, uint32_t device, type_t type) 1830 : PlaybackThread(audioFlinger, output, id, device, type), 1831 mAudioMixer(new AudioMixer(mFrameCount, mSampleRate)), 1832 mPrevMixerStatus(MIXER_IDLE) 1833{ 1834 // FIXME - Current mixer implementation only supports stereo output 1835 if (mChannelCount == 1) { 1836 ALOGE("Invalid audio hardware channel count"); 1837 } 1838} 1839 1840AudioFlinger::MixerThread::~MixerThread() 1841{ 1842 delete mAudioMixer; 1843} 1844 1845bool AudioFlinger::MixerThread::threadLoop() 1846{ 1847 Vector< sp<Track> > tracksToRemove; 1848 mixer_state mixerStatus = MIXER_IDLE; 1849 nsecs_t standbyTime = systemTime(); 1850 size_t mixBufferSize = mFrameCount * mFrameSize; 1851 // FIXME: Relaxed timing because of a certain device that can't meet latency 1852 // Should be reduced to 2x after the vendor fixes the driver issue 1853 // increase threshold again due to low power audio mode. The way this warning threshold is 1854 // calculated and its usefulness should be reconsidered anyway. 1855 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15; 1856 nsecs_t lastWarning = 0; 1857 bool longStandbyExit = false; 1858 uint32_t activeSleepTime = activeSleepTimeUs(); 1859 uint32_t idleSleepTime = idleSleepTimeUs(); 1860 uint32_t sleepTime = idleSleepTime; 1861 uint32_t sleepTimeShift = 0; 1862 Vector< sp<EffectChain> > effectChains; 1863#ifdef DEBUG_CPU_USAGE 1864 ThreadCpuUsage cpu; 1865 const CentralTendencyStatistics& stats = cpu.statistics(); 1866#endif 1867 1868 acquireWakeLock(); 1869 1870 while (!exitPending()) 1871 { 1872#ifdef DEBUG_CPU_USAGE 1873 cpu.sampleAndEnable(); 1874 unsigned n = stats.n(); 1875 // cpu.elapsed() is expensive, so don't call it every loop 1876 if ((n & 127) == 1) { 1877 long long elapsed = cpu.elapsed(); 1878 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) { 1879 double perLoop = elapsed / (double) n; 1880 double perLoop100 = perLoop * 0.01; 1881 double mean = stats.mean(); 1882 double stddev = stats.stddev(); 1883 double minimum = stats.minimum(); 1884 double maximum = stats.maximum(); 1885 cpu.resetStatistics(); 1886 ALOGI("CPU usage over past %.1f secs (%u mixer loops at %.1f mean ms per loop):\n us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f", 1887 elapsed * .000000001, n, perLoop * .000001, 1888 mean * .001, 1889 stddev * .001, 1890 minimum * .001, 1891 maximum * .001, 1892 mean / perLoop100, 1893 stddev / perLoop100, 1894 minimum / perLoop100, 1895 maximum / perLoop100); 1896 } 1897 } 1898#endif 1899 processConfigEvents(); 1900 1901 mixerStatus = MIXER_IDLE; 1902 { // scope for mLock 1903 1904 Mutex::Autolock _l(mLock); 1905 1906 if (checkForNewParameters_l()) { 1907 mixBufferSize = mFrameCount * mFrameSize; 1908 // FIXME: Relaxed timing because of a certain device that can't meet latency 1909 // Should be reduced to 2x after the vendor fixes the driver issue 1910 // increase threshold again due to low power audio mode. The way this warning 1911 // threshold is calculated and its usefulness should be reconsidered anyway. 1912 maxPeriod = seconds(mFrameCount) / mSampleRate * 15; 1913 activeSleepTime = activeSleepTimeUs(); 1914 idleSleepTime = idleSleepTimeUs(); 1915 } 1916 1917 const SortedVector< wp<Track> >& activeTracks = mActiveTracks; 1918 1919 // put audio hardware into standby after short delay 1920 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) || 1921 mSuspended)) { 1922 if (!mStandby) { 1923 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended); 1924 mOutput->stream->common.standby(&mOutput->stream->common); 1925 mStandby = true; 1926 mBytesWritten = 0; 1927 } 1928 1929 if (!activeTracks.size() && mConfigEvents.isEmpty()) { 1930 // we're about to wait, flush the binder command buffer 1931 IPCThreadState::self()->flushCommands(); 1932 1933 if (exitPending()) break; 1934 1935 releaseWakeLock_l(); 1936 // wait until we have something to do... 1937 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid()); 1938 mWaitWorkCV.wait(mLock); 1939 ALOGV("MixerThread %p TID %d waking up\n", this, gettid()); 1940 acquireWakeLock_l(); 1941 1942 mPrevMixerStatus = MIXER_IDLE; 1943 if (!mMasterMute) { 1944 char value[PROPERTY_VALUE_MAX]; 1945 property_get("ro.audio.silent", value, "0"); 1946 if (atoi(value)) { 1947 ALOGD("Silence is golden"); 1948 setMasterMute(true); 1949 } 1950 } 1951 1952 standbyTime = systemTime() + kStandbyTimeInNsecs; 1953 sleepTime = idleSleepTime; 1954 sleepTimeShift = 0; 1955 continue; 1956 } 1957 } 1958 1959 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove); 1960 1961 // prevent any changes in effect chain list and in each effect chain 1962 // during mixing and effect process as the audio buffers could be deleted 1963 // or modified if an effect is created or deleted 1964 lockEffectChains_l(effectChains); 1965 } 1966 1967 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) { 1968 // mix buffers... 1969 mAudioMixer->process(); 1970 // increase sleep time progressively when application underrun condition clears. 1971 // Only increase sleep time if the mixer is ready for two consecutive times to avoid 1972 // that a steady state of alternating ready/not ready conditions keeps the sleep time 1973 // such that we would underrun the audio HAL. 1974 if ((sleepTime == 0) && (sleepTimeShift > 0)) { 1975 sleepTimeShift--; 1976 } 1977 sleepTime = 0; 1978 standbyTime = systemTime() + kStandbyTimeInNsecs; 1979 //TODO: delay standby when effects have a tail 1980 } else { 1981 // If no tracks are ready, sleep once for the duration of an output 1982 // buffer size, then write 0s to the output 1983 if (sleepTime == 0) { 1984 if (mixerStatus == MIXER_TRACKS_ENABLED) { 1985 sleepTime = activeSleepTime >> sleepTimeShift; 1986 if (sleepTime < kMinThreadSleepTimeUs) { 1987 sleepTime = kMinThreadSleepTimeUs; 1988 } 1989 // reduce sleep time in case of consecutive application underruns to avoid 1990 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer 1991 // duration we would end up writing less data than needed by the audio HAL if 1992 // the condition persists. 1993 if (sleepTimeShift < kMaxThreadSleepTimeShift) { 1994 sleepTimeShift++; 1995 } 1996 } else { 1997 sleepTime = idleSleepTime; 1998 } 1999 } else if (mBytesWritten != 0 || 2000 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) { 2001 memset (mMixBuffer, 0, mixBufferSize); 2002 sleepTime = 0; 2003 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start"); 2004 } 2005 // TODO add standby time extension fct of effect tail 2006 } 2007 2008 if (mSuspended) { 2009 sleepTime = suspendSleepTimeUs(); 2010 } 2011 // sleepTime == 0 means we must write to audio hardware 2012 if (sleepTime == 0) { 2013 for (size_t i = 0; i < effectChains.size(); i ++) { 2014 effectChains[i]->process_l(); 2015 } 2016 // enable changes in effect chain 2017 unlockEffectChains(effectChains); 2018 mLastWriteTime = systemTime(); 2019 mInWrite = true; 2020 mBytesWritten += mixBufferSize; 2021 2022 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize); 2023 if (bytesWritten < 0) mBytesWritten -= mixBufferSize; 2024 mNumWrites++; 2025 mInWrite = false; 2026 nsecs_t now = systemTime(); 2027 nsecs_t delta = now - mLastWriteTime; 2028 if (!mStandby && delta > maxPeriod) { 2029 mNumDelayedWrites++; 2030 if ((now - lastWarning) > kWarningThrottleNs) { 2031 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p", 2032 ns2ms(delta), mNumDelayedWrites, this); 2033 lastWarning = now; 2034 } 2035 if (mStandby) { 2036 longStandbyExit = true; 2037 } 2038 } 2039 mStandby = false; 2040 } else { 2041 // enable changes in effect chain 2042 unlockEffectChains(effectChains); 2043 usleep(sleepTime); 2044 } 2045 2046 // finally let go of all our tracks, without the lock held 2047 // since we can't guarantee the destructors won't acquire that 2048 // same lock. 2049 tracksToRemove.clear(); 2050 2051 // Effect chains will be actually deleted here if they were removed from 2052 // mEffectChains list during mixing or effects processing 2053 effectChains.clear(); 2054 } 2055 2056 if (!mStandby) { 2057 mOutput->stream->common.standby(&mOutput->stream->common); 2058 } 2059 2060 releaseWakeLock(); 2061 2062 ALOGV("MixerThread %p exiting", this); 2063 return false; 2064} 2065 2066// prepareTracks_l() must be called with ThreadBase::mLock held 2067AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l( 2068 const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove) 2069{ 2070 2071 mixer_state mixerStatus = MIXER_IDLE; 2072 // find out which tracks need to be processed 2073 size_t count = activeTracks.size(); 2074 size_t mixedTracks = 0; 2075 size_t tracksWithEffect = 0; 2076 2077 float masterVolume = mMasterVolume; 2078 bool masterMute = mMasterMute; 2079 2080 if (masterMute) { 2081 masterVolume = 0; 2082 } 2083 // Delegate master volume control to effect in output mix effect chain if needed 2084 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); 2085 if (chain != 0) { 2086 uint32_t v = (uint32_t)(masterVolume * (1 << 24)); 2087 chain->setVolume_l(&v, &v); 2088 masterVolume = (float)((v + (1 << 23)) >> 24); 2089 chain.clear(); 2090 } 2091 2092 for (size_t i=0 ; i<count ; i++) { 2093 sp<Track> t = activeTracks[i].promote(); 2094 if (t == 0) continue; 2095 2096 // this const just means the local variable doesn't change 2097 Track* const track = t.get(); 2098 audio_track_cblk_t* cblk = track->cblk(); 2099 2100 // The first time a track is added we wait 2101 // for all its buffers to be filled before processing it 2102 int name = track->name(); 2103 // make sure that we have enough frames to mix one full buffer. 2104 // enforce this condition only once to enable draining the buffer in case the client 2105 // app does not call stop() and relies on underrun to stop: 2106 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed 2107 // during last round 2108 uint32_t minFrames = 1; 2109 if (!track->isStopped() && !track->isPausing() && 2110 (mPrevMixerStatus == MIXER_TRACKS_READY)) { 2111 if (t->sampleRate() == (int)mSampleRate) { 2112 minFrames = mFrameCount; 2113 } else { 2114 // +1 for rounding and +1 for additional sample needed for interpolation 2115 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1; 2116 // add frames already consumed but not yet released by the resampler 2117 // because cblk->framesReady() will include these frames 2118 minFrames += mAudioMixer->getUnreleasedFrames(track->name()); 2119 // the minimum track buffer size is normally twice the number of frames necessary 2120 // to fill one buffer and the resampler should not leave more than one buffer worth 2121 // of unreleased frames after each pass, but just in case... 2122 ALOG_ASSERT(minFrames <= cblk->frameCount); 2123 } 2124 } 2125 if ((cblk->framesReady() >= minFrames) && track->isReady() && 2126 !track->isPaused() && !track->isTerminated()) 2127 { 2128 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this); 2129 2130 mixedTracks++; 2131 2132 // track->mainBuffer() != mMixBuffer means there is an effect chain 2133 // connected to the track 2134 chain.clear(); 2135 if (track->mainBuffer() != mMixBuffer) { 2136 chain = getEffectChain_l(track->sessionId()); 2137 // Delegate volume control to effect in track effect chain if needed 2138 if (chain != 0) { 2139 tracksWithEffect++; 2140 } else { 2141 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d", 2142 name, track->sessionId()); 2143 } 2144 } 2145 2146 2147 int param = AudioMixer::VOLUME; 2148 if (track->mFillingUpStatus == Track::FS_FILLED) { 2149 // no ramp for the first volume setting 2150 track->mFillingUpStatus = Track::FS_ACTIVE; 2151 if (track->mState == TrackBase::RESUMING) { 2152 track->mState = TrackBase::ACTIVE; 2153 param = AudioMixer::RAMP_VOLUME; 2154 } 2155 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL); 2156 } else if (cblk->server != 0) { 2157 // If the track is stopped before the first frame was mixed, 2158 // do not apply ramp 2159 param = AudioMixer::RAMP_VOLUME; 2160 } 2161 2162 // compute volume for this track 2163 uint32_t vl, vr, va; 2164 if (track->isMuted() || track->isPausing() || 2165 mStreamTypes[track->type()].mute) { 2166 vl = vr = va = 0; 2167 if (track->isPausing()) { 2168 track->setPaused(); 2169 } 2170 } else { 2171 2172 // read original volumes with volume control 2173 float typeVolume = mStreamTypes[track->type()].volume; 2174 float v = masterVolume * typeVolume; 2175 uint32_t vlr = cblk->getVolumeLR(); 2176 vl = vlr & 0xFFFF; 2177 vr = vlr >> 16; 2178 // track volumes come from shared memory, so can't be trusted and must be clamped 2179 if (vl > MAX_GAIN_INT) { 2180 ALOGV("Track left volume out of range: %04X", vl); 2181 vl = MAX_GAIN_INT; 2182 } 2183 if (vr > MAX_GAIN_INT) { 2184 ALOGV("Track right volume out of range: %04X", vr); 2185 vr = MAX_GAIN_INT; 2186 } 2187 // now apply the master volume and stream type volume 2188 vl = (uint32_t)(v * vl) << 12; 2189 vr = (uint32_t)(v * vr) << 12; 2190 // assuming master volume and stream type volume each go up to 1.0, 2191 // vl and vr are now in 8.24 format 2192 2193 uint16_t sendLevel = cblk->getSendLevel_U4_12(); 2194 // send level comes from shared memory and so may be corrupt 2195 if (sendLevel >= MAX_GAIN_INT) { 2196 ALOGV("Track send level out of range: %04X", sendLevel); 2197 sendLevel = MAX_GAIN_INT; 2198 } 2199 va = (uint32_t)(v * sendLevel); 2200 } 2201 // Delegate volume control to effect in track effect chain if needed 2202 if (chain != 0 && chain->setVolume_l(&vl, &vr)) { 2203 // Do not ramp volume if volume is controlled by effect 2204 param = AudioMixer::VOLUME; 2205 track->mHasVolumeController = true; 2206 } else { 2207 // force no volume ramp when volume controller was just disabled or removed 2208 // from effect chain to avoid volume spike 2209 if (track->mHasVolumeController) { 2210 param = AudioMixer::VOLUME; 2211 } 2212 track->mHasVolumeController = false; 2213 } 2214 2215 // Convert volumes from 8.24 to 4.12 format 2216 int16_t left, right, aux; 2217 // This additional clamping is needed in case chain->setVolume_l() overshot 2218 uint32_t v_clamped = (vl + (1 << 11)) >> 12; 2219 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT; 2220 left = int16_t(v_clamped); 2221 v_clamped = (vr + (1 << 11)) >> 12; 2222 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT; 2223 right = int16_t(v_clamped); 2224 2225 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT; 2226 aux = int16_t(va); 2227 2228 // XXX: these things DON'T need to be done each time 2229 mAudioMixer->setBufferProvider(name, track); 2230 mAudioMixer->enable(name); 2231 2232 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left); 2233 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right); 2234 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux); 2235 mAudioMixer->setParameter( 2236 name, 2237 AudioMixer::TRACK, 2238 AudioMixer::FORMAT, (void *)track->format()); 2239 mAudioMixer->setParameter( 2240 name, 2241 AudioMixer::TRACK, 2242 AudioMixer::CHANNEL_MASK, (void *)track->channelMask()); 2243 mAudioMixer->setParameter( 2244 name, 2245 AudioMixer::RESAMPLE, 2246 AudioMixer::SAMPLE_RATE, 2247 (void *)(cblk->sampleRate)); 2248 mAudioMixer->setParameter( 2249 name, 2250 AudioMixer::TRACK, 2251 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer()); 2252 mAudioMixer->setParameter( 2253 name, 2254 AudioMixer::TRACK, 2255 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer()); 2256 2257 // reset retry count 2258 track->mRetryCount = kMaxTrackRetries; 2259 // If one track is ready, set the mixer ready if: 2260 // - the mixer was not ready during previous round OR 2261 // - no other track is not ready 2262 if (mPrevMixerStatus != MIXER_TRACKS_READY || 2263 mixerStatus != MIXER_TRACKS_ENABLED) { 2264 mixerStatus = MIXER_TRACKS_READY; 2265 } 2266 } else { 2267 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this); 2268 if (track->isStopped()) { 2269 track->reset(); 2270 } 2271 if (track->isTerminated() || track->isStopped() || track->isPaused()) { 2272 // We have consumed all the buffers of this track. 2273 // Remove it from the list of active tracks. 2274 tracksToRemove->add(track); 2275 } else { 2276 // No buffers for this track. Give it a few chances to 2277 // fill a buffer, then remove it from active list. 2278 if (--(track->mRetryCount) <= 0) { 2279 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this); 2280 tracksToRemove->add(track); 2281 // indicate to client process that the track was disabled because of underrun 2282 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags); 2283 // If one track is not ready, mark the mixer also not ready if: 2284 // - the mixer was ready during previous round OR 2285 // - no other track is ready 2286 } else if (mPrevMixerStatus == MIXER_TRACKS_READY || 2287 mixerStatus != MIXER_TRACKS_READY) { 2288 mixerStatus = MIXER_TRACKS_ENABLED; 2289 } 2290 } 2291 mAudioMixer->disable(name); 2292 } 2293 } 2294 2295 // remove all the tracks that need to be... 2296 count = tracksToRemove->size(); 2297 if (CC_UNLIKELY(count)) { 2298 for (size_t i=0 ; i<count ; i++) { 2299 const sp<Track>& track = tracksToRemove->itemAt(i); 2300 mActiveTracks.remove(track); 2301 if (track->mainBuffer() != mMixBuffer) { 2302 chain = getEffectChain_l(track->sessionId()); 2303 if (chain != 0) { 2304 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId()); 2305 chain->decActiveTrackCnt(); 2306 } 2307 } 2308 if (track->isTerminated()) { 2309 removeTrack_l(track); 2310 } 2311 } 2312 } 2313 2314 // mix buffer must be cleared if all tracks are connected to an 2315 // effect chain as in this case the mixer will not write to 2316 // mix buffer and track effects will accumulate into it 2317 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) { 2318 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t)); 2319 } 2320 2321 mPrevMixerStatus = mixerStatus; 2322 return mixerStatus; 2323} 2324 2325void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType) 2326{ 2327 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d", 2328 this, streamType, mTracks.size()); 2329 Mutex::Autolock _l(mLock); 2330 2331 size_t size = mTracks.size(); 2332 for (size_t i = 0; i < size; i++) { 2333 sp<Track> t = mTracks[i]; 2334 if (t->type() == streamType) { 2335 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags); 2336 t->mCblk->cv.signal(); 2337 } 2338 } 2339} 2340 2341void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid) 2342{ 2343 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d", 2344 this, streamType, valid); 2345 Mutex::Autolock _l(mLock); 2346 2347 mStreamTypes[streamType].valid = valid; 2348} 2349 2350// getTrackName_l() must be called with ThreadBase::mLock held 2351int AudioFlinger::MixerThread::getTrackName_l() 2352{ 2353 return mAudioMixer->getTrackName(); 2354} 2355 2356// deleteTrackName_l() must be called with ThreadBase::mLock held 2357void AudioFlinger::MixerThread::deleteTrackName_l(int name) 2358{ 2359 ALOGV("remove track (%d) and delete from mixer", name); 2360 mAudioMixer->deleteTrackName(name); 2361} 2362 2363// checkForNewParameters_l() must be called with ThreadBase::mLock held 2364bool AudioFlinger::MixerThread::checkForNewParameters_l() 2365{ 2366 bool reconfig = false; 2367 2368 while (!mNewParameters.isEmpty()) { 2369 status_t status = NO_ERROR; 2370 String8 keyValuePair = mNewParameters[0]; 2371 AudioParameter param = AudioParameter(keyValuePair); 2372 int value; 2373 2374 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { 2375 reconfig = true; 2376 } 2377 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { 2378 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) { 2379 status = BAD_VALUE; 2380 } else { 2381 reconfig = true; 2382 } 2383 } 2384 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { 2385 if (value != AUDIO_CHANNEL_OUT_STEREO) { 2386 status = BAD_VALUE; 2387 } else { 2388 reconfig = true; 2389 } 2390 } 2391 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 2392 // do not accept frame count changes if tracks are open as the track buffer 2393 // size depends on frame count and correct behavior would not be guaranteed 2394 // if frame count is changed after track creation 2395 if (!mTracks.isEmpty()) { 2396 status = INVALID_OPERATION; 2397 } else { 2398 reconfig = true; 2399 } 2400 } 2401 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 2402 // when changing the audio output device, call addBatteryData to notify 2403 // the change 2404 if ((int)mDevice != value) { 2405 uint32_t params = 0; 2406 // check whether speaker is on 2407 if (value & AUDIO_DEVICE_OUT_SPEAKER) { 2408 params |= IMediaPlayerService::kBatteryDataSpeakerOn; 2409 } 2410 2411 int deviceWithoutSpeaker 2412 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER; 2413 // check if any other device (except speaker) is on 2414 if (value & deviceWithoutSpeaker ) { 2415 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn; 2416 } 2417 2418 if (params != 0) { 2419 addBatteryData(params); 2420 } 2421 } 2422 2423 // forward device change to effects that have requested to be 2424 // aware of attached audio device. 2425 mDevice = (uint32_t)value; 2426 for (size_t i = 0; i < mEffectChains.size(); i++) { 2427 mEffectChains[i]->setDevice_l(mDevice); 2428 } 2429 } 2430 2431 if (status == NO_ERROR) { 2432 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 2433 keyValuePair.string()); 2434 if (!mStandby && status == INVALID_OPERATION) { 2435 mOutput->stream->common.standby(&mOutput->stream->common); 2436 mStandby = true; 2437 mBytesWritten = 0; 2438 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 2439 keyValuePair.string()); 2440 } 2441 if (status == NO_ERROR && reconfig) { 2442 delete mAudioMixer; 2443 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't) 2444 mAudioMixer = NULL; 2445 readOutputParameters(); 2446 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate); 2447 for (size_t i = 0; i < mTracks.size() ; i++) { 2448 int name = getTrackName_l(); 2449 if (name < 0) break; 2450 mTracks[i]->mName = name; 2451 // limit track sample rate to 2 x new output sample rate 2452 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) { 2453 mTracks[i]->mCblk->sampleRate = 2 * sampleRate(); 2454 } 2455 } 2456 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED); 2457 } 2458 } 2459 2460 mNewParameters.removeAt(0); 2461 2462 mParamStatus = status; 2463 mParamCond.signal(); 2464 // wait for condition with time out in case the thread calling ThreadBase::setParameters() 2465 // already timed out waiting for the status and will never signal the condition. 2466 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); 2467 } 2468 return reconfig; 2469} 2470 2471status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args) 2472{ 2473 const size_t SIZE = 256; 2474 char buffer[SIZE]; 2475 String8 result; 2476 2477 PlaybackThread::dumpInternals(fd, args); 2478 2479 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames()); 2480 result.append(buffer); 2481 write(fd, result.string(), result.size()); 2482 return NO_ERROR; 2483} 2484 2485uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() 2486{ 2487 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2; 2488} 2489 2490uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() 2491{ 2492 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000); 2493} 2494 2495// ---------------------------------------------------------------------------- 2496AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, 2497 AudioStreamOut* output, audio_io_handle_t id, uint32_t device) 2498 : PlaybackThread(audioFlinger, output, id, device, DIRECT) 2499 // mLeftVolFloat, mRightVolFloat 2500 // mLeftVolShort, mRightVolShort 2501{ 2502} 2503 2504AudioFlinger::DirectOutputThread::~DirectOutputThread() 2505{ 2506} 2507 2508static inline 2509int32_t mul(int16_t in, int16_t v) 2510{ 2511#if defined(__arm__) && !defined(__thumb__) 2512 int32_t out; 2513 asm( "smulbb %[out], %[in], %[v] \n" 2514 : [out]"=r"(out) 2515 : [in]"%r"(in), [v]"r"(v) 2516 : ); 2517 return out; 2518#else 2519 return in * int32_t(v); 2520#endif 2521} 2522 2523void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp) 2524{ 2525 // Do not apply volume on compressed audio 2526 if (!audio_is_linear_pcm(mFormat)) { 2527 return; 2528 } 2529 2530 // convert to signed 16 bit before volume calculation 2531 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) { 2532 size_t count = mFrameCount * mChannelCount; 2533 uint8_t *src = (uint8_t *)mMixBuffer + count-1; 2534 int16_t *dst = mMixBuffer + count-1; 2535 while(count--) { 2536 *dst-- = (int16_t)(*src--^0x80) << 8; 2537 } 2538 } 2539 2540 size_t frameCount = mFrameCount; 2541 int16_t *out = mMixBuffer; 2542 if (ramp) { 2543 if (mChannelCount == 1) { 2544 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16; 2545 int32_t vlInc = d / (int32_t)frameCount; 2546 int32_t vl = ((int32_t)mLeftVolShort << 16); 2547 do { 2548 out[0] = clamp16(mul(out[0], vl >> 16) >> 12); 2549 out++; 2550 vl += vlInc; 2551 } while (--frameCount); 2552 2553 } else { 2554 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16; 2555 int32_t vlInc = d / (int32_t)frameCount; 2556 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16; 2557 int32_t vrInc = d / (int32_t)frameCount; 2558 int32_t vl = ((int32_t)mLeftVolShort << 16); 2559 int32_t vr = ((int32_t)mRightVolShort << 16); 2560 do { 2561 out[0] = clamp16(mul(out[0], vl >> 16) >> 12); 2562 out[1] = clamp16(mul(out[1], vr >> 16) >> 12); 2563 out += 2; 2564 vl += vlInc; 2565 vr += vrInc; 2566 } while (--frameCount); 2567 } 2568 } else { 2569 if (mChannelCount == 1) { 2570 do { 2571 out[0] = clamp16(mul(out[0], leftVol) >> 12); 2572 out++; 2573 } while (--frameCount); 2574 } else { 2575 do { 2576 out[0] = clamp16(mul(out[0], leftVol) >> 12); 2577 out[1] = clamp16(mul(out[1], rightVol) >> 12); 2578 out += 2; 2579 } while (--frameCount); 2580 } 2581 } 2582 2583 // convert back to unsigned 8 bit after volume calculation 2584 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) { 2585 size_t count = mFrameCount * mChannelCount; 2586 int16_t *src = mMixBuffer; 2587 uint8_t *dst = (uint8_t *)mMixBuffer; 2588 while(count--) { 2589 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80; 2590 } 2591 } 2592 2593 mLeftVolShort = leftVol; 2594 mRightVolShort = rightVol; 2595} 2596 2597bool AudioFlinger::DirectOutputThread::threadLoop() 2598{ 2599 mixer_state mixerStatus = MIXER_IDLE; 2600 sp<Track> trackToRemove; 2601 sp<Track> activeTrack; 2602 nsecs_t standbyTime = systemTime(); 2603 int8_t *curBuf; 2604 size_t mixBufferSize = mFrameCount*mFrameSize; 2605 uint32_t activeSleepTime = activeSleepTimeUs(); 2606 uint32_t idleSleepTime = idleSleepTimeUs(); 2607 uint32_t sleepTime = idleSleepTime; 2608 // use shorter standby delay as on normal output to release 2609 // hardware resources as soon as possible 2610 nsecs_t standbyDelay = microseconds(activeSleepTime*2); 2611 2612 acquireWakeLock(); 2613 2614 while (!exitPending()) 2615 { 2616 bool rampVolume; 2617 uint16_t leftVol; 2618 uint16_t rightVol; 2619 Vector< sp<EffectChain> > effectChains; 2620 2621 processConfigEvents(); 2622 2623 mixerStatus = MIXER_IDLE; 2624 2625 { // scope for the mLock 2626 2627 Mutex::Autolock _l(mLock); 2628 2629 if (checkForNewParameters_l()) { 2630 mixBufferSize = mFrameCount*mFrameSize; 2631 activeSleepTime = activeSleepTimeUs(); 2632 idleSleepTime = idleSleepTimeUs(); 2633 standbyDelay = microseconds(activeSleepTime*2); 2634 } 2635 2636 // put audio hardware into standby after short delay 2637 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) || 2638 mSuspended)) { 2639 // wait until we have something to do... 2640 if (!mStandby) { 2641 ALOGV("Audio hardware entering standby, mixer %p\n", this); 2642 mOutput->stream->common.standby(&mOutput->stream->common); 2643 mStandby = true; 2644 mBytesWritten = 0; 2645 } 2646 2647 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) { 2648 // we're about to wait, flush the binder command buffer 2649 IPCThreadState::self()->flushCommands(); 2650 2651 if (exitPending()) break; 2652 2653 releaseWakeLock_l(); 2654 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid()); 2655 mWaitWorkCV.wait(mLock); 2656 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid()); 2657 acquireWakeLock_l(); 2658 2659 if (!mMasterMute) { 2660 char value[PROPERTY_VALUE_MAX]; 2661 property_get("ro.audio.silent", value, "0"); 2662 if (atoi(value)) { 2663 ALOGD("Silence is golden"); 2664 setMasterMute(true); 2665 } 2666 } 2667 2668 standbyTime = systemTime() + standbyDelay; 2669 sleepTime = idleSleepTime; 2670 continue; 2671 } 2672 } 2673 2674 effectChains = mEffectChains; 2675 2676 // find out which tracks need to be processed 2677 if (mActiveTracks.size() != 0) { 2678 sp<Track> t = mActiveTracks[0].promote(); 2679 if (t == 0) continue; 2680 2681 Track* const track = t.get(); 2682 audio_track_cblk_t* cblk = track->cblk(); 2683 2684 // The first time a track is added we wait 2685 // for all its buffers to be filled before processing it 2686 if (cblk->framesReady() && track->isReady() && 2687 !track->isPaused() && !track->isTerminated()) 2688 { 2689 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server); 2690 2691 if (track->mFillingUpStatus == Track::FS_FILLED) { 2692 track->mFillingUpStatus = Track::FS_ACTIVE; 2693 mLeftVolFloat = mRightVolFloat = 0; 2694 mLeftVolShort = mRightVolShort = 0; 2695 if (track->mState == TrackBase::RESUMING) { 2696 track->mState = TrackBase::ACTIVE; 2697 rampVolume = true; 2698 } 2699 } else if (cblk->server != 0) { 2700 // If the track is stopped before the first frame was mixed, 2701 // do not apply ramp 2702 rampVolume = true; 2703 } 2704 // compute volume for this track 2705 float left, right; 2706 if (track->isMuted() || mMasterMute || track->isPausing() || 2707 mStreamTypes[track->type()].mute) { 2708 left = right = 0; 2709 if (track->isPausing()) { 2710 track->setPaused(); 2711 } 2712 } else { 2713 float typeVolume = mStreamTypes[track->type()].volume; 2714 float v = mMasterVolume * typeVolume; 2715 uint32_t vlr = cblk->getVolumeLR(); 2716 float v_clamped = v * (vlr & 0xFFFF); 2717 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN; 2718 left = v_clamped/MAX_GAIN; 2719 v_clamped = v * (vlr >> 16); 2720 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN; 2721 right = v_clamped/MAX_GAIN; 2722 } 2723 2724 if (left != mLeftVolFloat || right != mRightVolFloat) { 2725 mLeftVolFloat = left; 2726 mRightVolFloat = right; 2727 2728 // If audio HAL implements volume control, 2729 // force software volume to nominal value 2730 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) { 2731 left = 1.0f; 2732 right = 1.0f; 2733 } 2734 2735 // Convert volumes from float to 8.24 2736 uint32_t vl = (uint32_t)(left * (1 << 24)); 2737 uint32_t vr = (uint32_t)(right * (1 << 24)); 2738 2739 // Delegate volume control to effect in track effect chain if needed 2740 // only one effect chain can be present on DirectOutputThread, so if 2741 // there is one, the track is connected to it 2742 if (!effectChains.isEmpty()) { 2743 // Do not ramp volume if volume is controlled by effect 2744 if(effectChains[0]->setVolume_l(&vl, &vr)) { 2745 rampVolume = false; 2746 } 2747 } 2748 2749 // Convert volumes from 8.24 to 4.12 format 2750 uint32_t v_clamped = (vl + (1 << 11)) >> 12; 2751 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT; 2752 leftVol = (uint16_t)v_clamped; 2753 v_clamped = (vr + (1 << 11)) >> 12; 2754 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT; 2755 rightVol = (uint16_t)v_clamped; 2756 } else { 2757 leftVol = mLeftVolShort; 2758 rightVol = mRightVolShort; 2759 rampVolume = false; 2760 } 2761 2762 // reset retry count 2763 track->mRetryCount = kMaxTrackRetriesDirect; 2764 activeTrack = t; 2765 mixerStatus = MIXER_TRACKS_READY; 2766 } else { 2767 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server); 2768 if (track->isStopped()) { 2769 track->reset(); 2770 } 2771 if (track->isTerminated() || track->isStopped() || track->isPaused()) { 2772 // We have consumed all the buffers of this track. 2773 // Remove it from the list of active tracks. 2774 trackToRemove = track; 2775 } else { 2776 // No buffers for this track. Give it a few chances to 2777 // fill a buffer, then remove it from active list. 2778 if (--(track->mRetryCount) <= 0) { 2779 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name()); 2780 trackToRemove = track; 2781 } else { 2782 mixerStatus = MIXER_TRACKS_ENABLED; 2783 } 2784 } 2785 } 2786 } 2787 2788 // remove all the tracks that need to be... 2789 if (CC_UNLIKELY(trackToRemove != 0)) { 2790 mActiveTracks.remove(trackToRemove); 2791 if (!effectChains.isEmpty()) { 2792 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(), 2793 trackToRemove->sessionId()); 2794 effectChains[0]->decActiveTrackCnt(); 2795 } 2796 if (trackToRemove->isTerminated()) { 2797 removeTrack_l(trackToRemove); 2798 } 2799 } 2800 2801 lockEffectChains_l(effectChains); 2802 } 2803 2804 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) { 2805 AudioBufferProvider::Buffer buffer; 2806 size_t frameCount = mFrameCount; 2807 curBuf = (int8_t *)mMixBuffer; 2808 // output audio to hardware 2809 while (frameCount) { 2810 buffer.frameCount = frameCount; 2811 activeTrack->getNextBuffer(&buffer); 2812 if (CC_UNLIKELY(buffer.raw == NULL)) { 2813 memset(curBuf, 0, frameCount * mFrameSize); 2814 break; 2815 } 2816 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize); 2817 frameCount -= buffer.frameCount; 2818 curBuf += buffer.frameCount * mFrameSize; 2819 activeTrack->releaseBuffer(&buffer); 2820 } 2821 sleepTime = 0; 2822 standbyTime = systemTime() + standbyDelay; 2823 } else { 2824 if (sleepTime == 0) { 2825 if (mixerStatus == MIXER_TRACKS_ENABLED) { 2826 sleepTime = activeSleepTime; 2827 } else { 2828 sleepTime = idleSleepTime; 2829 } 2830 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) { 2831 memset (mMixBuffer, 0, mFrameCount * mFrameSize); 2832 sleepTime = 0; 2833 } 2834 } 2835 2836 if (mSuspended) { 2837 sleepTime = suspendSleepTimeUs(); 2838 } 2839 // sleepTime == 0 means we must write to audio hardware 2840 if (sleepTime == 0) { 2841 if (mixerStatus == MIXER_TRACKS_READY) { 2842 applyVolume(leftVol, rightVol, rampVolume); 2843 } 2844 for (size_t i = 0; i < effectChains.size(); i ++) { 2845 effectChains[i]->process_l(); 2846 } 2847 unlockEffectChains(effectChains); 2848 2849 mLastWriteTime = systemTime(); 2850 mInWrite = true; 2851 mBytesWritten += mixBufferSize; 2852 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize); 2853 if (bytesWritten < 0) mBytesWritten -= mixBufferSize; 2854 mNumWrites++; 2855 mInWrite = false; 2856 mStandby = false; 2857 } else { 2858 unlockEffectChains(effectChains); 2859 usleep(sleepTime); 2860 } 2861 2862 // finally let go of removed track, without the lock held 2863 // since we can't guarantee the destructors won't acquire that 2864 // same lock. 2865 trackToRemove.clear(); 2866 activeTrack.clear(); 2867 2868 // Effect chains will be actually deleted here if they were removed from 2869 // mEffectChains list during mixing or effects processing 2870 effectChains.clear(); 2871 } 2872 2873 if (!mStandby) { 2874 mOutput->stream->common.standby(&mOutput->stream->common); 2875 } 2876 2877 releaseWakeLock(); 2878 2879 ALOGV("DirectOutputThread %p exiting", this); 2880 return false; 2881} 2882 2883// getTrackName_l() must be called with ThreadBase::mLock held 2884int AudioFlinger::DirectOutputThread::getTrackName_l() 2885{ 2886 return 0; 2887} 2888 2889// deleteTrackName_l() must be called with ThreadBase::mLock held 2890void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name) 2891{ 2892} 2893 2894// checkForNewParameters_l() must be called with ThreadBase::mLock held 2895bool AudioFlinger::DirectOutputThread::checkForNewParameters_l() 2896{ 2897 bool reconfig = false; 2898 2899 while (!mNewParameters.isEmpty()) { 2900 status_t status = NO_ERROR; 2901 String8 keyValuePair = mNewParameters[0]; 2902 AudioParameter param = AudioParameter(keyValuePair); 2903 int value; 2904 2905 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 2906 // do not accept frame count changes if tracks are open as the track buffer 2907 // size depends on frame count and correct behavior would not be garantied 2908 // if frame count is changed after track creation 2909 if (!mTracks.isEmpty()) { 2910 status = INVALID_OPERATION; 2911 } else { 2912 reconfig = true; 2913 } 2914 } 2915 if (status == NO_ERROR) { 2916 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 2917 keyValuePair.string()); 2918 if (!mStandby && status == INVALID_OPERATION) { 2919 mOutput->stream->common.standby(&mOutput->stream->common); 2920 mStandby = true; 2921 mBytesWritten = 0; 2922 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 2923 keyValuePair.string()); 2924 } 2925 if (status == NO_ERROR && reconfig) { 2926 readOutputParameters(); 2927 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED); 2928 } 2929 } 2930 2931 mNewParameters.removeAt(0); 2932 2933 mParamStatus = status; 2934 mParamCond.signal(); 2935 // wait for condition with time out in case the thread calling ThreadBase::setParameters() 2936 // already timed out waiting for the status and will never signal the condition. 2937 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); 2938 } 2939 return reconfig; 2940} 2941 2942uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() 2943{ 2944 uint32_t time; 2945 if (audio_is_linear_pcm(mFormat)) { 2946 time = PlaybackThread::activeSleepTimeUs(); 2947 } else { 2948 time = 10000; 2949 } 2950 return time; 2951} 2952 2953uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() 2954{ 2955 uint32_t time; 2956 if (audio_is_linear_pcm(mFormat)) { 2957 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2; 2958 } else { 2959 time = 10000; 2960 } 2961 return time; 2962} 2963 2964uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() 2965{ 2966 uint32_t time; 2967 if (audio_is_linear_pcm(mFormat)) { 2968 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000); 2969 } else { 2970 time = 10000; 2971 } 2972 return time; 2973} 2974 2975 2976// ---------------------------------------------------------------------------- 2977 2978AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, 2979 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id) 2980 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING), 2981 mWaitTimeMs(UINT_MAX) 2982{ 2983 addOutputTrack(mainThread); 2984} 2985 2986AudioFlinger::DuplicatingThread::~DuplicatingThread() 2987{ 2988 for (size_t i = 0; i < mOutputTracks.size(); i++) { 2989 mOutputTracks[i]->destroy(); 2990 } 2991} 2992 2993bool AudioFlinger::DuplicatingThread::threadLoop() 2994{ 2995 Vector< sp<Track> > tracksToRemove; 2996 mixer_state mixerStatus = MIXER_IDLE; 2997 nsecs_t standbyTime = systemTime(); 2998 size_t mixBufferSize = mFrameCount*mFrameSize; 2999 SortedVector< sp<OutputTrack> > outputTracks; 3000 uint32_t writeFrames = 0; 3001 uint32_t activeSleepTime = activeSleepTimeUs(); 3002 uint32_t idleSleepTime = idleSleepTimeUs(); 3003 uint32_t sleepTime = idleSleepTime; 3004 Vector< sp<EffectChain> > effectChains; 3005 3006 acquireWakeLock(); 3007 3008 while (!exitPending()) 3009 { 3010 processConfigEvents(); 3011 3012 mixerStatus = MIXER_IDLE; 3013 { // scope for the mLock 3014 3015 Mutex::Autolock _l(mLock); 3016 3017 if (checkForNewParameters_l()) { 3018 mixBufferSize = mFrameCount*mFrameSize; 3019 updateWaitTime(); 3020 activeSleepTime = activeSleepTimeUs(); 3021 idleSleepTime = idleSleepTimeUs(); 3022 } 3023 3024 const SortedVector< wp<Track> >& activeTracks = mActiveTracks; 3025 3026 for (size_t i = 0; i < mOutputTracks.size(); i++) { 3027 outputTracks.add(mOutputTracks[i]); 3028 } 3029 3030 // put audio hardware into standby after short delay 3031 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) || 3032 mSuspended)) { 3033 if (!mStandby) { 3034 for (size_t i = 0; i < outputTracks.size(); i++) { 3035 outputTracks[i]->stop(); 3036 } 3037 mStandby = true; 3038 mBytesWritten = 0; 3039 } 3040 3041 if (!activeTracks.size() && mConfigEvents.isEmpty()) { 3042 // we're about to wait, flush the binder command buffer 3043 IPCThreadState::self()->flushCommands(); 3044 outputTracks.clear(); 3045 3046 if (exitPending()) break; 3047 3048 releaseWakeLock_l(); 3049 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid()); 3050 mWaitWorkCV.wait(mLock); 3051 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid()); 3052 acquireWakeLock_l(); 3053 3054 mPrevMixerStatus = MIXER_IDLE; 3055 if (!mMasterMute) { 3056 char value[PROPERTY_VALUE_MAX]; 3057 property_get("ro.audio.silent", value, "0"); 3058 if (atoi(value)) { 3059 ALOGD("Silence is golden"); 3060 setMasterMute(true); 3061 } 3062 } 3063 3064 standbyTime = systemTime() + kStandbyTimeInNsecs; 3065 sleepTime = idleSleepTime; 3066 continue; 3067 } 3068 } 3069 3070 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove); 3071 3072 // prevent any changes in effect chain list and in each effect chain 3073 // during mixing and effect process as the audio buffers could be deleted 3074 // or modified if an effect is created or deleted 3075 lockEffectChains_l(effectChains); 3076 } 3077 3078 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) { 3079 // mix buffers... 3080 if (outputsReady(outputTracks)) { 3081 mAudioMixer->process(); 3082 } else { 3083 memset(mMixBuffer, 0, mixBufferSize); 3084 } 3085 sleepTime = 0; 3086 writeFrames = mFrameCount; 3087 } else { 3088 if (sleepTime == 0) { 3089 if (mixerStatus == MIXER_TRACKS_ENABLED) { 3090 sleepTime = activeSleepTime; 3091 } else { 3092 sleepTime = idleSleepTime; 3093 } 3094 } else if (mBytesWritten != 0) { 3095 // flush remaining overflow buffers in output tracks 3096 for (size_t i = 0; i < outputTracks.size(); i++) { 3097 if (outputTracks[i]->isActive()) { 3098 sleepTime = 0; 3099 writeFrames = 0; 3100 memset(mMixBuffer, 0, mixBufferSize); 3101 break; 3102 } 3103 } 3104 } 3105 } 3106 3107 if (mSuspended) { 3108 sleepTime = suspendSleepTimeUs(); 3109 } 3110 // sleepTime == 0 means we must write to audio hardware 3111 if (sleepTime == 0) { 3112 for (size_t i = 0; i < effectChains.size(); i ++) { 3113 effectChains[i]->process_l(); 3114 } 3115 // enable changes in effect chain 3116 unlockEffectChains(effectChains); 3117 3118 standbyTime = systemTime() + kStandbyTimeInNsecs; 3119 for (size_t i = 0; i < outputTracks.size(); i++) { 3120 outputTracks[i]->write(mMixBuffer, writeFrames); 3121 } 3122 mStandby = false; 3123 mBytesWritten += mixBufferSize; 3124 } else { 3125 // enable changes in effect chain 3126 unlockEffectChains(effectChains); 3127 usleep(sleepTime); 3128 } 3129 3130 // finally let go of all our tracks, without the lock held 3131 // since we can't guarantee the destructors won't acquire that 3132 // same lock. 3133 tracksToRemove.clear(); 3134 outputTracks.clear(); 3135 3136 // Effect chains will be actually deleted here if they were removed from 3137 // mEffectChains list during mixing or effects processing 3138 effectChains.clear(); 3139 } 3140 3141 releaseWakeLock(); 3142 3143 return false; 3144} 3145 3146void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread) 3147{ 3148 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate(); 3149 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread, 3150 this, 3151 mSampleRate, 3152 mFormat, 3153 mChannelMask, 3154 frameCount); 3155 if (outputTrack->cblk() != NULL) { 3156 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f); 3157 mOutputTracks.add(outputTrack); 3158 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread); 3159 updateWaitTime(); 3160 } 3161} 3162 3163void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread) 3164{ 3165 Mutex::Autolock _l(mLock); 3166 for (size_t i = 0; i < mOutputTracks.size(); i++) { 3167 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) { 3168 mOutputTracks[i]->destroy(); 3169 mOutputTracks.removeAt(i); 3170 updateWaitTime(); 3171 return; 3172 } 3173 } 3174 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread); 3175} 3176 3177void AudioFlinger::DuplicatingThread::updateWaitTime() 3178{ 3179 mWaitTimeMs = UINT_MAX; 3180 for (size_t i = 0; i < mOutputTracks.size(); i++) { 3181 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote(); 3182 if (strong != 0) { 3183 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate(); 3184 if (waitTimeMs < mWaitTimeMs) { 3185 mWaitTimeMs = waitTimeMs; 3186 } 3187 } 3188 } 3189} 3190 3191 3192bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks) 3193{ 3194 for (size_t i = 0; i < outputTracks.size(); i++) { 3195 sp <ThreadBase> thread = outputTracks[i]->thread().promote(); 3196 if (thread == 0) { 3197 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get()); 3198 return false; 3199 } 3200 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 3201 if (playbackThread->standby() && !playbackThread->isSuspended()) { 3202 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get()); 3203 return false; 3204 } 3205 } 3206 return true; 3207} 3208 3209uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() 3210{ 3211 return (mWaitTimeMs * 1000) / 2; 3212} 3213 3214// ---------------------------------------------------------------------------- 3215 3216// TrackBase constructor must be called with AudioFlinger::mLock held 3217AudioFlinger::ThreadBase::TrackBase::TrackBase( 3218 const wp<ThreadBase>& thread, 3219 const sp<Client>& client, 3220 uint32_t sampleRate, 3221 audio_format_t format, 3222 uint32_t channelMask, 3223 int frameCount, 3224 uint32_t flags, 3225 const sp<IMemory>& sharedBuffer, 3226 int sessionId) 3227 : RefBase(), 3228 mThread(thread), 3229 mClient(client), 3230 mCblk(NULL), 3231 // mBuffer 3232 // mBufferEnd 3233 mFrameCount(0), 3234 mState(IDLE), 3235 mFormat(format), 3236 mFlags(flags & ~SYSTEM_FLAGS_MASK), 3237 mSessionId(sessionId) 3238 // mChannelCount 3239 // mChannelMask 3240{ 3241 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size()); 3242 3243 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize); 3244 size_t size = sizeof(audio_track_cblk_t); 3245 uint8_t channelCount = popcount(channelMask); 3246 size_t bufferSize = frameCount*channelCount*sizeof(int16_t); 3247 if (sharedBuffer == 0) { 3248 size += bufferSize; 3249 } 3250 3251 if (client != NULL) { 3252 mCblkMemory = client->heap()->allocate(size); 3253 if (mCblkMemory != 0) { 3254 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer()); 3255 if (mCblk != NULL) { // construct the shared structure in-place. 3256 new(mCblk) audio_track_cblk_t(); 3257 // clear all buffers 3258 mCblk->frameCount = frameCount; 3259 mCblk->sampleRate = sampleRate; 3260 mChannelCount = channelCount; 3261 mChannelMask = channelMask; 3262 if (sharedBuffer == 0) { 3263 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t); 3264 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t)); 3265 // Force underrun condition to avoid false underrun callback until first data is 3266 // written to buffer (other flags are cleared) 3267 mCblk->flags = CBLK_UNDERRUN_ON; 3268 } else { 3269 mBuffer = sharedBuffer->pointer(); 3270 } 3271 mBufferEnd = (uint8_t *)mBuffer + bufferSize; 3272 } 3273 } else { 3274 ALOGE("not enough memory for AudioTrack size=%u", size); 3275 client->heap()->dump("AudioTrack"); 3276 return; 3277 } 3278 } else { 3279 mCblk = (audio_track_cblk_t *)(new uint8_t[size]); 3280 // construct the shared structure in-place. 3281 new(mCblk) audio_track_cblk_t(); 3282 // clear all buffers 3283 mCblk->frameCount = frameCount; 3284 mCblk->sampleRate = sampleRate; 3285 mChannelCount = channelCount; 3286 mChannelMask = channelMask; 3287 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t); 3288 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t)); 3289 // Force underrun condition to avoid false underrun callback until first data is 3290 // written to buffer (other flags are cleared) 3291 mCblk->flags = CBLK_UNDERRUN_ON; 3292 mBufferEnd = (uint8_t *)mBuffer + bufferSize; 3293 } 3294} 3295 3296AudioFlinger::ThreadBase::TrackBase::~TrackBase() 3297{ 3298 if (mCblk != NULL) { 3299 if (mClient == 0) { 3300 delete mCblk; 3301 } else { 3302 mCblk->~audio_track_cblk_t(); // destroy our shared-structure. 3303 } 3304 } 3305 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to 3306 if (mClient != 0) { 3307 // Client destructor must run with AudioFlinger mutex locked 3308 Mutex::Autolock _l(mClient->audioFlinger()->mLock); 3309 // If the client's reference count drops to zero, the associated destructor 3310 // must run with AudioFlinger lock held. Thus the explicit clear() rather than 3311 // relying on the automatic clear() at end of scope. 3312 mClient.clear(); 3313 } 3314} 3315 3316void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer) 3317{ 3318 buffer->raw = NULL; 3319 mFrameCount = buffer->frameCount; 3320 step(); 3321 buffer->frameCount = 0; 3322} 3323 3324bool AudioFlinger::ThreadBase::TrackBase::step() { 3325 bool result; 3326 audio_track_cblk_t* cblk = this->cblk(); 3327 3328 result = cblk->stepServer(mFrameCount); 3329 if (!result) { 3330 ALOGV("stepServer failed acquiring cblk mutex"); 3331 mFlags |= STEPSERVER_FAILED; 3332 } 3333 return result; 3334} 3335 3336void AudioFlinger::ThreadBase::TrackBase::reset() { 3337 audio_track_cblk_t* cblk = this->cblk(); 3338 3339 cblk->user = 0; 3340 cblk->server = 0; 3341 cblk->userBase = 0; 3342 cblk->serverBase = 0; 3343 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK); 3344 ALOGV("TrackBase::reset"); 3345} 3346 3347int AudioFlinger::ThreadBase::TrackBase::sampleRate() const { 3348 return (int)mCblk->sampleRate; 3349} 3350 3351void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const { 3352 audio_track_cblk_t* cblk = this->cblk(); 3353 size_t frameSize = cblk->frameSize; 3354 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize; 3355 int8_t *bufferEnd = bufferStart + frames * frameSize; 3356 3357 // Check validity of returned pointer in case the track control block would have been corrupted. 3358 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd || 3359 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) { 3360 ALOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \ 3361 server %d, serverBase %d, user %d, userBase %d", 3362 bufferStart, bufferEnd, mBuffer, mBufferEnd, 3363 cblk->server, cblk->serverBase, cblk->user, cblk->userBase); 3364 return NULL; 3365 } 3366 3367 return bufferStart; 3368} 3369 3370// ---------------------------------------------------------------------------- 3371 3372// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held 3373AudioFlinger::PlaybackThread::Track::Track( 3374 const wp<ThreadBase>& thread, 3375 const sp<Client>& client, 3376 audio_stream_type_t streamType, 3377 uint32_t sampleRate, 3378 audio_format_t format, 3379 uint32_t channelMask, 3380 int frameCount, 3381 const sp<IMemory>& sharedBuffer, 3382 int sessionId) 3383 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId), 3384 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL), 3385 mAuxEffectId(0), mHasVolumeController(false) 3386{ 3387 if (mCblk != NULL) { 3388 sp<ThreadBase> baseThread = thread.promote(); 3389 if (baseThread != 0) { 3390 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get(); 3391 mName = playbackThread->getTrackName_l(); 3392 mMainBuffer = playbackThread->mixBuffer(); 3393 } 3394 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid()); 3395 if (mName < 0) { 3396 ALOGE("no more track names available"); 3397 } 3398 mStreamType = streamType; 3399 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of 3400 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack 3401 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t); 3402 } 3403} 3404 3405AudioFlinger::PlaybackThread::Track::~Track() 3406{ 3407 ALOGV("PlaybackThread::Track destructor"); 3408 sp<ThreadBase> thread = mThread.promote(); 3409 if (thread != 0) { 3410 Mutex::Autolock _l(thread->mLock); 3411 mState = TERMINATED; 3412 } 3413} 3414 3415void AudioFlinger::PlaybackThread::Track::destroy() 3416{ 3417 // NOTE: destroyTrack_l() can remove a strong reference to this Track 3418 // by removing it from mTracks vector, so there is a risk that this Tracks's 3419 // desctructor is called. As the destructor needs to lock mLock, 3420 // we must acquire a strong reference on this Track before locking mLock 3421 // here so that the destructor is called only when exiting this function. 3422 // On the other hand, as long as Track::destroy() is only called by 3423 // TrackHandle destructor, the TrackHandle still holds a strong ref on 3424 // this Track with its member mTrack. 3425 sp<Track> keep(this); 3426 { // scope for mLock 3427 sp<ThreadBase> thread = mThread.promote(); 3428 if (thread != 0) { 3429 if (!isOutputTrack()) { 3430 if (mState == ACTIVE || mState == RESUMING) { 3431 AudioSystem::stopOutput(thread->id(), 3432 (audio_stream_type_t)mStreamType, 3433 mSessionId); 3434 3435 // to track the speaker usage 3436 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop); 3437 } 3438 AudioSystem::releaseOutput(thread->id()); 3439 } 3440 Mutex::Autolock _l(thread->mLock); 3441 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 3442 playbackThread->destroyTrack_l(this); 3443 } 3444 } 3445} 3446 3447void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size) 3448{ 3449 uint32_t vlr = mCblk->getVolumeLR(); 3450 snprintf(buffer, size, " %05d %05d %03u %03u 0x%08x %05u %04u %1d %1d %1d %05u %05u %05u 0x%08x 0x%08x 0x%08x 0x%08x\n", 3451 mName - AudioMixer::TRACK0, 3452 (mClient == 0) ? getpid() : mClient->pid(), 3453 mStreamType, 3454 mFormat, 3455 mChannelMask, 3456 mSessionId, 3457 mFrameCount, 3458 mState, 3459 mMute, 3460 mFillingUpStatus, 3461 mCblk->sampleRate, 3462 vlr & 0xFFFF, 3463 vlr >> 16, 3464 mCblk->server, 3465 mCblk->user, 3466 (int)mMainBuffer, 3467 (int)mAuxBuffer); 3468} 3469 3470status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer) 3471{ 3472 audio_track_cblk_t* cblk = this->cblk(); 3473 uint32_t framesReady; 3474 uint32_t framesReq = buffer->frameCount; 3475 3476 // Check if last stepServer failed, try to step now 3477 if (mFlags & TrackBase::STEPSERVER_FAILED) { 3478 if (!step()) goto getNextBuffer_exit; 3479 ALOGV("stepServer recovered"); 3480 mFlags &= ~TrackBase::STEPSERVER_FAILED; 3481 } 3482 3483 framesReady = cblk->framesReady(); 3484 3485 if (CC_LIKELY(framesReady)) { 3486 uint32_t s = cblk->server; 3487 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount; 3488 3489 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd; 3490 if (framesReq > framesReady) { 3491 framesReq = framesReady; 3492 } 3493 if (s + framesReq > bufferEnd) { 3494 framesReq = bufferEnd - s; 3495 } 3496 3497 buffer->raw = getBuffer(s, framesReq); 3498 if (buffer->raw == NULL) goto getNextBuffer_exit; 3499 3500 buffer->frameCount = framesReq; 3501 return NO_ERROR; 3502 } 3503 3504getNextBuffer_exit: 3505 buffer->raw = NULL; 3506 buffer->frameCount = 0; 3507 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get()); 3508 return NOT_ENOUGH_DATA; 3509} 3510 3511bool AudioFlinger::PlaybackThread::Track::isReady() const { 3512 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true; 3513 3514 if (mCblk->framesReady() >= mCblk->frameCount || 3515 (mCblk->flags & CBLK_FORCEREADY_MSK)) { 3516 mFillingUpStatus = FS_FILLED; 3517 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags); 3518 return true; 3519 } 3520 return false; 3521} 3522 3523status_t AudioFlinger::PlaybackThread::Track::start() 3524{ 3525 status_t status = NO_ERROR; 3526 ALOGV("start(%d), calling thread %d session %d", 3527 mName, IPCThreadState::self()->getCallingPid(), mSessionId); 3528 sp<ThreadBase> thread = mThread.promote(); 3529 if (thread != 0) { 3530 Mutex::Autolock _l(thread->mLock); 3531 track_state state = mState; 3532 // here the track could be either new, or restarted 3533 // in both cases "unstop" the track 3534 if (mState == PAUSED) { 3535 mState = TrackBase::RESUMING; 3536 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this); 3537 } else { 3538 mState = TrackBase::ACTIVE; 3539 ALOGV("? => ACTIVE (%d) on thread %p", mName, this); 3540 } 3541 3542 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) { 3543 thread->mLock.unlock(); 3544 status = AudioSystem::startOutput(thread->id(), 3545 (audio_stream_type_t)mStreamType, 3546 mSessionId); 3547 thread->mLock.lock(); 3548 3549 // to track the speaker usage 3550 if (status == NO_ERROR) { 3551 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart); 3552 } 3553 } 3554 if (status == NO_ERROR) { 3555 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 3556 playbackThread->addTrack_l(this); 3557 } else { 3558 mState = state; 3559 } 3560 } else { 3561 status = BAD_VALUE; 3562 } 3563 return status; 3564} 3565 3566void AudioFlinger::PlaybackThread::Track::stop() 3567{ 3568 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid()); 3569 sp<ThreadBase> thread = mThread.promote(); 3570 if (thread != 0) { 3571 Mutex::Autolock _l(thread->mLock); 3572 track_state state = mState; 3573 if (mState > STOPPED) { 3574 mState = STOPPED; 3575 // If the track is not active (PAUSED and buffers full), flush buffers 3576 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 3577 if (playbackThread->mActiveTracks.indexOf(this) < 0) { 3578 reset(); 3579 } 3580 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread); 3581 } 3582 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) { 3583 thread->mLock.unlock(); 3584 AudioSystem::stopOutput(thread->id(), 3585 (audio_stream_type_t)mStreamType, 3586 mSessionId); 3587 thread->mLock.lock(); 3588 3589 // to track the speaker usage 3590 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop); 3591 } 3592 } 3593} 3594 3595void AudioFlinger::PlaybackThread::Track::pause() 3596{ 3597 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid()); 3598 sp<ThreadBase> thread = mThread.promote(); 3599 if (thread != 0) { 3600 Mutex::Autolock _l(thread->mLock); 3601 if (mState == ACTIVE || mState == RESUMING) { 3602 mState = PAUSING; 3603 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get()); 3604 if (!isOutputTrack()) { 3605 thread->mLock.unlock(); 3606 AudioSystem::stopOutput(thread->id(), 3607 (audio_stream_type_t)mStreamType, 3608 mSessionId); 3609 thread->mLock.lock(); 3610 3611 // to track the speaker usage 3612 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop); 3613 } 3614 } 3615 } 3616} 3617 3618void AudioFlinger::PlaybackThread::Track::flush() 3619{ 3620 ALOGV("flush(%d)", mName); 3621 sp<ThreadBase> thread = mThread.promote(); 3622 if (thread != 0) { 3623 Mutex::Autolock _l(thread->mLock); 3624 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) { 3625 return; 3626 } 3627 // No point remaining in PAUSED state after a flush => go to 3628 // STOPPED state 3629 mState = STOPPED; 3630 3631 // do not reset the track if it is still in the process of being stopped or paused. 3632 // this will be done by prepareTracks_l() when the track is stopped. 3633 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 3634 if (playbackThread->mActiveTracks.indexOf(this) < 0) { 3635 reset(); 3636 } 3637 } 3638} 3639 3640void AudioFlinger::PlaybackThread::Track::reset() 3641{ 3642 // Do not reset twice to avoid discarding data written just after a flush and before 3643 // the audioflinger thread detects the track is stopped. 3644 if (!mResetDone) { 3645 TrackBase::reset(); 3646 // Force underrun condition to avoid false underrun callback until first data is 3647 // written to buffer 3648 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags); 3649 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags); 3650 mFillingUpStatus = FS_FILLING; 3651 mResetDone = true; 3652 } 3653} 3654 3655void AudioFlinger::PlaybackThread::Track::mute(bool muted) 3656{ 3657 mMute = muted; 3658} 3659 3660status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId) 3661{ 3662 status_t status = DEAD_OBJECT; 3663 sp<ThreadBase> thread = mThread.promote(); 3664 if (thread != 0) { 3665 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 3666 status = playbackThread->attachAuxEffect(this, EffectId); 3667 } 3668 return status; 3669} 3670 3671void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer) 3672{ 3673 mAuxEffectId = EffectId; 3674 mAuxBuffer = buffer; 3675} 3676 3677// ---------------------------------------------------------------------------- 3678 3679// RecordTrack constructor must be called with AudioFlinger::mLock held 3680AudioFlinger::RecordThread::RecordTrack::RecordTrack( 3681 const wp<ThreadBase>& thread, 3682 const sp<Client>& client, 3683 uint32_t sampleRate, 3684 audio_format_t format, 3685 uint32_t channelMask, 3686 int frameCount, 3687 uint32_t flags, 3688 int sessionId) 3689 : TrackBase(thread, client, sampleRate, format, 3690 channelMask, frameCount, flags, 0, sessionId), 3691 mOverflow(false) 3692{ 3693 if (mCblk != NULL) { 3694 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer); 3695 if (format == AUDIO_FORMAT_PCM_16_BIT) { 3696 mCblk->frameSize = mChannelCount * sizeof(int16_t); 3697 } else if (format == AUDIO_FORMAT_PCM_8_BIT) { 3698 mCblk->frameSize = mChannelCount * sizeof(int8_t); 3699 } else { 3700 mCblk->frameSize = sizeof(int8_t); 3701 } 3702 } 3703} 3704 3705AudioFlinger::RecordThread::RecordTrack::~RecordTrack() 3706{ 3707 sp<ThreadBase> thread = mThread.promote(); 3708 if (thread != 0) { 3709 AudioSystem::releaseInput(thread->id()); 3710 } 3711} 3712 3713status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer) 3714{ 3715 audio_track_cblk_t* cblk = this->cblk(); 3716 uint32_t framesAvail; 3717 uint32_t framesReq = buffer->frameCount; 3718 3719 // Check if last stepServer failed, try to step now 3720 if (mFlags & TrackBase::STEPSERVER_FAILED) { 3721 if (!step()) goto getNextBuffer_exit; 3722 ALOGV("stepServer recovered"); 3723 mFlags &= ~TrackBase::STEPSERVER_FAILED; 3724 } 3725 3726 framesAvail = cblk->framesAvailable_l(); 3727 3728 if (CC_LIKELY(framesAvail)) { 3729 uint32_t s = cblk->server; 3730 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount; 3731 3732 if (framesReq > framesAvail) { 3733 framesReq = framesAvail; 3734 } 3735 if (s + framesReq > bufferEnd) { 3736 framesReq = bufferEnd - s; 3737 } 3738 3739 buffer->raw = getBuffer(s, framesReq); 3740 if (buffer->raw == NULL) goto getNextBuffer_exit; 3741 3742 buffer->frameCount = framesReq; 3743 return NO_ERROR; 3744 } 3745 3746getNextBuffer_exit: 3747 buffer->raw = NULL; 3748 buffer->frameCount = 0; 3749 return NOT_ENOUGH_DATA; 3750} 3751 3752status_t AudioFlinger::RecordThread::RecordTrack::start() 3753{ 3754 sp<ThreadBase> thread = mThread.promote(); 3755 if (thread != 0) { 3756 RecordThread *recordThread = (RecordThread *)thread.get(); 3757 return recordThread->start(this); 3758 } else { 3759 return BAD_VALUE; 3760 } 3761} 3762 3763void AudioFlinger::RecordThread::RecordTrack::stop() 3764{ 3765 sp<ThreadBase> thread = mThread.promote(); 3766 if (thread != 0) { 3767 RecordThread *recordThread = (RecordThread *)thread.get(); 3768 recordThread->stop(this); 3769 TrackBase::reset(); 3770 // Force overerrun condition to avoid false overrun callback until first data is 3771 // read from buffer 3772 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags); 3773 } 3774} 3775 3776void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size) 3777{ 3778 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n", 3779 (mClient == 0) ? getpid() : mClient->pid(), 3780 mFormat, 3781 mChannelMask, 3782 mSessionId, 3783 mFrameCount, 3784 mState, 3785 mCblk->sampleRate, 3786 mCblk->server, 3787 mCblk->user); 3788} 3789 3790 3791// ---------------------------------------------------------------------------- 3792 3793AudioFlinger::PlaybackThread::OutputTrack::OutputTrack( 3794 const wp<ThreadBase>& thread, 3795 DuplicatingThread *sourceThread, 3796 uint32_t sampleRate, 3797 audio_format_t format, 3798 uint32_t channelMask, 3799 int frameCount) 3800 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0), 3801 mActive(false), mSourceThread(sourceThread) 3802{ 3803 3804 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get(); 3805 if (mCblk != NULL) { 3806 mCblk->flags |= CBLK_DIRECTION_OUT; 3807 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t); 3808 mOutBuffer.frameCount = 0; 3809 playbackThread->mTracks.add(this); 3810 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \ 3811 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p", 3812 mCblk, mBuffer, mCblk->buffers, 3813 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd); 3814 } else { 3815 ALOGW("Error creating output track on thread %p", playbackThread); 3816 } 3817} 3818 3819AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack() 3820{ 3821 clearBufferQueue(); 3822} 3823 3824status_t AudioFlinger::PlaybackThread::OutputTrack::start() 3825{ 3826 status_t status = Track::start(); 3827 if (status != NO_ERROR) { 3828 return status; 3829 } 3830 3831 mActive = true; 3832 mRetryCount = 127; 3833 return status; 3834} 3835 3836void AudioFlinger::PlaybackThread::OutputTrack::stop() 3837{ 3838 Track::stop(); 3839 clearBufferQueue(); 3840 mOutBuffer.frameCount = 0; 3841 mActive = false; 3842} 3843 3844bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames) 3845{ 3846 Buffer *pInBuffer; 3847 Buffer inBuffer; 3848 uint32_t channelCount = mChannelCount; 3849 bool outputBufferFull = false; 3850 inBuffer.frameCount = frames; 3851 inBuffer.i16 = data; 3852 3853 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs(); 3854 3855 if (!mActive && frames != 0) { 3856 start(); 3857 sp<ThreadBase> thread = mThread.promote(); 3858 if (thread != 0) { 3859 MixerThread *mixerThread = (MixerThread *)thread.get(); 3860 if (mCblk->frameCount > frames){ 3861 if (mBufferQueue.size() < kMaxOverFlowBuffers) { 3862 uint32_t startFrames = (mCblk->frameCount - frames); 3863 pInBuffer = new Buffer; 3864 pInBuffer->mBuffer = new int16_t[startFrames * channelCount]; 3865 pInBuffer->frameCount = startFrames; 3866 pInBuffer->i16 = pInBuffer->mBuffer; 3867 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t)); 3868 mBufferQueue.add(pInBuffer); 3869 } else { 3870 ALOGW ("OutputTrack::write() %p no more buffers in queue", this); 3871 } 3872 } 3873 } 3874 } 3875 3876 while (waitTimeLeftMs) { 3877 // First write pending buffers, then new data 3878 if (mBufferQueue.size()) { 3879 pInBuffer = mBufferQueue.itemAt(0); 3880 } else { 3881 pInBuffer = &inBuffer; 3882 } 3883 3884 if (pInBuffer->frameCount == 0) { 3885 break; 3886 } 3887 3888 if (mOutBuffer.frameCount == 0) { 3889 mOutBuffer.frameCount = pInBuffer->frameCount; 3890 nsecs_t startTime = systemTime(); 3891 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) { 3892 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get()); 3893 outputBufferFull = true; 3894 break; 3895 } 3896 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime); 3897 if (waitTimeLeftMs >= waitTimeMs) { 3898 waitTimeLeftMs -= waitTimeMs; 3899 } else { 3900 waitTimeLeftMs = 0; 3901 } 3902 } 3903 3904 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount; 3905 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t)); 3906 mCblk->stepUser(outFrames); 3907 pInBuffer->frameCount -= outFrames; 3908 pInBuffer->i16 += outFrames * channelCount; 3909 mOutBuffer.frameCount -= outFrames; 3910 mOutBuffer.i16 += outFrames * channelCount; 3911 3912 if (pInBuffer->frameCount == 0) { 3913 if (mBufferQueue.size()) { 3914 mBufferQueue.removeAt(0); 3915 delete [] pInBuffer->mBuffer; 3916 delete pInBuffer; 3917 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size()); 3918 } else { 3919 break; 3920 } 3921 } 3922 } 3923 3924 // If we could not write all frames, allocate a buffer and queue it for next time. 3925 if (inBuffer.frameCount) { 3926 sp<ThreadBase> thread = mThread.promote(); 3927 if (thread != 0 && !thread->standby()) { 3928 if (mBufferQueue.size() < kMaxOverFlowBuffers) { 3929 pInBuffer = new Buffer; 3930 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount]; 3931 pInBuffer->frameCount = inBuffer.frameCount; 3932 pInBuffer->i16 = pInBuffer->mBuffer; 3933 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t)); 3934 mBufferQueue.add(pInBuffer); 3935 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size()); 3936 } else { 3937 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this); 3938 } 3939 } 3940 } 3941 3942 // Calling write() with a 0 length buffer, means that no more data will be written: 3943 // If no more buffers are pending, fill output track buffer to make sure it is started 3944 // by output mixer. 3945 if (frames == 0 && mBufferQueue.size() == 0) { 3946 if (mCblk->user < mCblk->frameCount) { 3947 frames = mCblk->frameCount - mCblk->user; 3948 pInBuffer = new Buffer; 3949 pInBuffer->mBuffer = new int16_t[frames * channelCount]; 3950 pInBuffer->frameCount = frames; 3951 pInBuffer->i16 = pInBuffer->mBuffer; 3952 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t)); 3953 mBufferQueue.add(pInBuffer); 3954 } else if (mActive) { 3955 stop(); 3956 } 3957 } 3958 3959 return outputBufferFull; 3960} 3961 3962status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs) 3963{ 3964 int active; 3965 status_t result; 3966 audio_track_cblk_t* cblk = mCblk; 3967 uint32_t framesReq = buffer->frameCount; 3968 3969// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server); 3970 buffer->frameCount = 0; 3971 3972 uint32_t framesAvail = cblk->framesAvailable(); 3973 3974 3975 if (framesAvail == 0) { 3976 Mutex::Autolock _l(cblk->lock); 3977 goto start_loop_here; 3978 while (framesAvail == 0) { 3979 active = mActive; 3980 if (CC_UNLIKELY(!active)) { 3981 ALOGV("Not active and NO_MORE_BUFFERS"); 3982 return NO_MORE_BUFFERS; 3983 } 3984 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs)); 3985 if (result != NO_ERROR) { 3986 return NO_MORE_BUFFERS; 3987 } 3988 // read the server count again 3989 start_loop_here: 3990 framesAvail = cblk->framesAvailable_l(); 3991 } 3992 } 3993 3994// if (framesAvail < framesReq) { 3995// return NO_MORE_BUFFERS; 3996// } 3997 3998 if (framesReq > framesAvail) { 3999 framesReq = framesAvail; 4000 } 4001 4002 uint32_t u = cblk->user; 4003 uint32_t bufferEnd = cblk->userBase + cblk->frameCount; 4004 4005 if (u + framesReq > bufferEnd) { 4006 framesReq = bufferEnd - u; 4007 } 4008 4009 buffer->frameCount = framesReq; 4010 buffer->raw = (void *)cblk->buffer(u); 4011 return NO_ERROR; 4012} 4013 4014 4015void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue() 4016{ 4017 size_t size = mBufferQueue.size(); 4018 Buffer *pBuffer; 4019 4020 for (size_t i = 0; i < size; i++) { 4021 pBuffer = mBufferQueue.itemAt(i); 4022 delete [] pBuffer->mBuffer; 4023 delete pBuffer; 4024 } 4025 mBufferQueue.clear(); 4026} 4027 4028// ---------------------------------------------------------------------------- 4029 4030AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid) 4031 : RefBase(), 4032 mAudioFlinger(audioFlinger), 4033 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")), 4034 mPid(pid) 4035{ 4036 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer 4037} 4038 4039// Client destructor must be called with AudioFlinger::mLock held 4040AudioFlinger::Client::~Client() 4041{ 4042 mAudioFlinger->removeClient_l(mPid); 4043} 4044 4045sp<MemoryDealer> AudioFlinger::Client::heap() const 4046{ 4047 return mMemoryDealer; 4048} 4049 4050// ---------------------------------------------------------------------------- 4051 4052AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger, 4053 const sp<IAudioFlingerClient>& client, 4054 pid_t pid) 4055 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client) 4056{ 4057} 4058 4059AudioFlinger::NotificationClient::~NotificationClient() 4060{ 4061} 4062 4063void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who) 4064{ 4065 sp<NotificationClient> keep(this); 4066 { 4067 mAudioFlinger->removeNotificationClient(mPid); 4068 } 4069} 4070 4071// ---------------------------------------------------------------------------- 4072 4073AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track) 4074 : BnAudioTrack(), 4075 mTrack(track) 4076{ 4077} 4078 4079AudioFlinger::TrackHandle::~TrackHandle() { 4080 // just stop the track on deletion, associated resources 4081 // will be freed from the main thread once all pending buffers have 4082 // been played. Unless it's not in the active track list, in which 4083 // case we free everything now... 4084 mTrack->destroy(); 4085} 4086 4087sp<IMemory> AudioFlinger::TrackHandle::getCblk() const { 4088 return mTrack->getCblk(); 4089} 4090 4091status_t AudioFlinger::TrackHandle::start() { 4092 return mTrack->start(); 4093} 4094 4095void AudioFlinger::TrackHandle::stop() { 4096 mTrack->stop(); 4097} 4098 4099void AudioFlinger::TrackHandle::flush() { 4100 mTrack->flush(); 4101} 4102 4103void AudioFlinger::TrackHandle::mute(bool e) { 4104 mTrack->mute(e); 4105} 4106 4107void AudioFlinger::TrackHandle::pause() { 4108 mTrack->pause(); 4109} 4110 4111status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId) 4112{ 4113 return mTrack->attachAuxEffect(EffectId); 4114} 4115 4116status_t AudioFlinger::TrackHandle::onTransact( 4117 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 4118{ 4119 return BnAudioTrack::onTransact(code, data, reply, flags); 4120} 4121 4122// ---------------------------------------------------------------------------- 4123 4124sp<IAudioRecord> AudioFlinger::openRecord( 4125 pid_t pid, 4126 audio_io_handle_t input, 4127 uint32_t sampleRate, 4128 audio_format_t format, 4129 uint32_t channelMask, 4130 int frameCount, 4131 uint32_t flags, 4132 int *sessionId, 4133 status_t *status) 4134{ 4135 sp<RecordThread::RecordTrack> recordTrack; 4136 sp<RecordHandle> recordHandle; 4137 sp<Client> client; 4138 status_t lStatus; 4139 RecordThread *thread; 4140 size_t inFrameCount; 4141 int lSessionId; 4142 4143 // check calling permissions 4144 if (!recordingAllowed()) { 4145 lStatus = PERMISSION_DENIED; 4146 goto Exit; 4147 } 4148 4149 // add client to list 4150 { // scope for mLock 4151 Mutex::Autolock _l(mLock); 4152 thread = checkRecordThread_l(input); 4153 if (thread == NULL) { 4154 lStatus = BAD_VALUE; 4155 goto Exit; 4156 } 4157 4158 client = registerPid_l(pid); 4159 4160 // If no audio session id is provided, create one here 4161 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) { 4162 lSessionId = *sessionId; 4163 } else { 4164 lSessionId = nextUniqueId(); 4165 if (sessionId != NULL) { 4166 *sessionId = lSessionId; 4167 } 4168 } 4169 // create new record track. The record track uses one track in mHardwareMixerThread by convention. 4170 recordTrack = thread->createRecordTrack_l(client, 4171 sampleRate, 4172 format, 4173 channelMask, 4174 frameCount, 4175 flags, 4176 lSessionId, 4177 &lStatus); 4178 } 4179 if (lStatus != NO_ERROR) { 4180 // remove local strong reference to Client before deleting the RecordTrack so that the Client 4181 // destructor is called by the TrackBase destructor with mLock held 4182 client.clear(); 4183 recordTrack.clear(); 4184 goto Exit; 4185 } 4186 4187 // return to handle to client 4188 recordHandle = new RecordHandle(recordTrack); 4189 lStatus = NO_ERROR; 4190 4191Exit: 4192 if (status) { 4193 *status = lStatus; 4194 } 4195 return recordHandle; 4196} 4197 4198// ---------------------------------------------------------------------------- 4199 4200AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack) 4201 : BnAudioRecord(), 4202 mRecordTrack(recordTrack) 4203{ 4204} 4205 4206AudioFlinger::RecordHandle::~RecordHandle() { 4207 stop(); 4208} 4209 4210sp<IMemory> AudioFlinger::RecordHandle::getCblk() const { 4211 return mRecordTrack->getCblk(); 4212} 4213 4214status_t AudioFlinger::RecordHandle::start() { 4215 ALOGV("RecordHandle::start()"); 4216 return mRecordTrack->start(); 4217} 4218 4219void AudioFlinger::RecordHandle::stop() { 4220 ALOGV("RecordHandle::stop()"); 4221 mRecordTrack->stop(); 4222} 4223 4224status_t AudioFlinger::RecordHandle::onTransact( 4225 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 4226{ 4227 return BnAudioRecord::onTransact(code, data, reply, flags); 4228} 4229 4230// ---------------------------------------------------------------------------- 4231 4232AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, 4233 AudioStreamIn *input, 4234 uint32_t sampleRate, 4235 uint32_t channels, 4236 audio_io_handle_t id, 4237 uint32_t device) : 4238 ThreadBase(audioFlinger, id, device, RECORD), 4239 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL), 4240 // mRsmpInIndex and mInputBytes set by readInputParameters() 4241 mReqChannelCount(popcount(channels)), 4242 mReqSampleRate(sampleRate) 4243 // mBytesRead is only meaningful while active, and so is cleared in start() 4244 // (but might be better to also clear here for dump?) 4245{ 4246 snprintf(mName, kNameLength, "AudioIn_%d", id); 4247 4248 readInputParameters(); 4249} 4250 4251 4252AudioFlinger::RecordThread::~RecordThread() 4253{ 4254 delete[] mRsmpInBuffer; 4255 delete mResampler; 4256 delete[] mRsmpOutBuffer; 4257} 4258 4259void AudioFlinger::RecordThread::onFirstRef() 4260{ 4261 run(mName, PRIORITY_URGENT_AUDIO); 4262} 4263 4264status_t AudioFlinger::RecordThread::readyToRun() 4265{ 4266 status_t status = initCheck(); 4267 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this); 4268 return status; 4269} 4270 4271bool AudioFlinger::RecordThread::threadLoop() 4272{ 4273 AudioBufferProvider::Buffer buffer; 4274 sp<RecordTrack> activeTrack; 4275 Vector< sp<EffectChain> > effectChains; 4276 4277 nsecs_t lastWarning = 0; 4278 4279 acquireWakeLock(); 4280 4281 // start recording 4282 while (!exitPending()) { 4283 4284 processConfigEvents(); 4285 4286 { // scope for mLock 4287 Mutex::Autolock _l(mLock); 4288 checkForNewParameters_l(); 4289 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) { 4290 if (!mStandby) { 4291 mInput->stream->common.standby(&mInput->stream->common); 4292 mStandby = true; 4293 } 4294 4295 if (exitPending()) break; 4296 4297 releaseWakeLock_l(); 4298 ALOGV("RecordThread: loop stopping"); 4299 // go to sleep 4300 mWaitWorkCV.wait(mLock); 4301 ALOGV("RecordThread: loop starting"); 4302 acquireWakeLock_l(); 4303 continue; 4304 } 4305 if (mActiveTrack != 0) { 4306 if (mActiveTrack->mState == TrackBase::PAUSING) { 4307 if (!mStandby) { 4308 mInput->stream->common.standby(&mInput->stream->common); 4309 mStandby = true; 4310 } 4311 mActiveTrack.clear(); 4312 mStartStopCond.broadcast(); 4313 } else if (mActiveTrack->mState == TrackBase::RESUMING) { 4314 if (mReqChannelCount != mActiveTrack->channelCount()) { 4315 mActiveTrack.clear(); 4316 mStartStopCond.broadcast(); 4317 } else if (mBytesRead != 0) { 4318 // record start succeeds only if first read from audio input 4319 // succeeds 4320 if (mBytesRead > 0) { 4321 mActiveTrack->mState = TrackBase::ACTIVE; 4322 } else { 4323 mActiveTrack.clear(); 4324 } 4325 mStartStopCond.broadcast(); 4326 } 4327 mStandby = false; 4328 } 4329 } 4330 lockEffectChains_l(effectChains); 4331 } 4332 4333 if (mActiveTrack != 0) { 4334 if (mActiveTrack->mState != TrackBase::ACTIVE && 4335 mActiveTrack->mState != TrackBase::RESUMING) { 4336 unlockEffectChains(effectChains); 4337 usleep(kRecordThreadSleepUs); 4338 continue; 4339 } 4340 for (size_t i = 0; i < effectChains.size(); i ++) { 4341 effectChains[i]->process_l(); 4342 } 4343 4344 buffer.frameCount = mFrameCount; 4345 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) { 4346 size_t framesOut = buffer.frameCount; 4347 if (mResampler == NULL) { 4348 // no resampling 4349 while (framesOut) { 4350 size_t framesIn = mFrameCount - mRsmpInIndex; 4351 if (framesIn) { 4352 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize; 4353 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize; 4354 if (framesIn > framesOut) 4355 framesIn = framesOut; 4356 mRsmpInIndex += framesIn; 4357 framesOut -= framesIn; 4358 if ((int)mChannelCount == mReqChannelCount || 4359 mFormat != AUDIO_FORMAT_PCM_16_BIT) { 4360 memcpy(dst, src, framesIn * mFrameSize); 4361 } else { 4362 int16_t *src16 = (int16_t *)src; 4363 int16_t *dst16 = (int16_t *)dst; 4364 if (mChannelCount == 1) { 4365 while (framesIn--) { 4366 *dst16++ = *src16; 4367 *dst16++ = *src16++; 4368 } 4369 } else { 4370 while (framesIn--) { 4371 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1); 4372 src16 += 2; 4373 } 4374 } 4375 } 4376 } 4377 if (framesOut && mFrameCount == mRsmpInIndex) { 4378 if (framesOut == mFrameCount && 4379 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) { 4380 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes); 4381 framesOut = 0; 4382 } else { 4383 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes); 4384 mRsmpInIndex = 0; 4385 } 4386 if (mBytesRead < 0) { 4387 ALOGE("Error reading audio input"); 4388 if (mActiveTrack->mState == TrackBase::ACTIVE) { 4389 // Force input into standby so that it tries to 4390 // recover at next read attempt 4391 mInput->stream->common.standby(&mInput->stream->common); 4392 usleep(kRecordThreadSleepUs); 4393 } 4394 mRsmpInIndex = mFrameCount; 4395 framesOut = 0; 4396 buffer.frameCount = 0; 4397 } 4398 } 4399 } 4400 } else { 4401 // resampling 4402 4403 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t)); 4404 // alter output frame count as if we were expecting stereo samples 4405 if (mChannelCount == 1 && mReqChannelCount == 1) { 4406 framesOut >>= 1; 4407 } 4408 mResampler->resample(mRsmpOutBuffer, framesOut, this); 4409 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer() 4410 // are 32 bit aligned which should be always true. 4411 if (mChannelCount == 2 && mReqChannelCount == 1) { 4412 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut); 4413 // the resampler always outputs stereo samples: do post stereo to mono conversion 4414 int16_t *src = (int16_t *)mRsmpOutBuffer; 4415 int16_t *dst = buffer.i16; 4416 while (framesOut--) { 4417 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1); 4418 src += 2; 4419 } 4420 } else { 4421 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut); 4422 } 4423 4424 } 4425 mActiveTrack->releaseBuffer(&buffer); 4426 mActiveTrack->overflow(); 4427 } 4428 // client isn't retrieving buffers fast enough 4429 else { 4430 if (!mActiveTrack->setOverflow()) { 4431 nsecs_t now = systemTime(); 4432 if ((now - lastWarning) > kWarningThrottleNs) { 4433 ALOGW("RecordThread: buffer overflow"); 4434 lastWarning = now; 4435 } 4436 } 4437 // Release the processor for a while before asking for a new buffer. 4438 // This will give the application more chance to read from the buffer and 4439 // clear the overflow. 4440 usleep(kRecordThreadSleepUs); 4441 } 4442 } 4443 // enable changes in effect chain 4444 unlockEffectChains(effectChains); 4445 effectChains.clear(); 4446 } 4447 4448 if (!mStandby) { 4449 mInput->stream->common.standby(&mInput->stream->common); 4450 } 4451 mActiveTrack.clear(); 4452 4453 mStartStopCond.broadcast(); 4454 4455 releaseWakeLock(); 4456 4457 ALOGV("RecordThread %p exiting", this); 4458 return false; 4459} 4460 4461 4462sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l( 4463 const sp<AudioFlinger::Client>& client, 4464 uint32_t sampleRate, 4465 audio_format_t format, 4466 int channelMask, 4467 int frameCount, 4468 uint32_t flags, 4469 int sessionId, 4470 status_t *status) 4471{ 4472 sp<RecordTrack> track; 4473 status_t lStatus; 4474 4475 lStatus = initCheck(); 4476 if (lStatus != NO_ERROR) { 4477 ALOGE("Audio driver not initialized."); 4478 goto Exit; 4479 } 4480 4481 { // scope for mLock 4482 Mutex::Autolock _l(mLock); 4483 4484 track = new RecordTrack(this, client, sampleRate, 4485 format, channelMask, frameCount, flags, sessionId); 4486 4487 if (track->getCblk() == 0) { 4488 lStatus = NO_MEMORY; 4489 goto Exit; 4490 } 4491 4492 mTrack = track.get(); 4493 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 4494 bool suspend = audio_is_bluetooth_sco_device( 4495 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff(); 4496 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId); 4497 setEffectSuspended_l(FX_IID_NS, suspend, sessionId); 4498 } 4499 lStatus = NO_ERROR; 4500 4501Exit: 4502 if (status) { 4503 *status = lStatus; 4504 } 4505 return track; 4506} 4507 4508status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack) 4509{ 4510 ALOGV("RecordThread::start"); 4511 sp <ThreadBase> strongMe = this; 4512 status_t status = NO_ERROR; 4513 { 4514 AutoMutex lock(mLock); 4515 if (mActiveTrack != 0) { 4516 if (recordTrack != mActiveTrack.get()) { 4517 status = -EBUSY; 4518 } else if (mActiveTrack->mState == TrackBase::PAUSING) { 4519 mActiveTrack->mState = TrackBase::ACTIVE; 4520 } 4521 return status; 4522 } 4523 4524 recordTrack->mState = TrackBase::IDLE; 4525 mActiveTrack = recordTrack; 4526 mLock.unlock(); 4527 status_t status = AudioSystem::startInput(mId); 4528 mLock.lock(); 4529 if (status != NO_ERROR) { 4530 mActiveTrack.clear(); 4531 return status; 4532 } 4533 mRsmpInIndex = mFrameCount; 4534 mBytesRead = 0; 4535 if (mResampler != NULL) { 4536 mResampler->reset(); 4537 } 4538 mActiveTrack->mState = TrackBase::RESUMING; 4539 // signal thread to start 4540 ALOGV("Signal record thread"); 4541 mWaitWorkCV.signal(); 4542 // do not wait for mStartStopCond if exiting 4543 if (mExiting) { 4544 mActiveTrack.clear(); 4545 status = INVALID_OPERATION; 4546 goto startError; 4547 } 4548 mStartStopCond.wait(mLock); 4549 if (mActiveTrack == 0) { 4550 ALOGV("Record failed to start"); 4551 status = BAD_VALUE; 4552 goto startError; 4553 } 4554 ALOGV("Record started OK"); 4555 return status; 4556 } 4557startError: 4558 AudioSystem::stopInput(mId); 4559 return status; 4560} 4561 4562void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) { 4563 ALOGV("RecordThread::stop"); 4564 sp <ThreadBase> strongMe = this; 4565 { 4566 AutoMutex lock(mLock); 4567 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) { 4568 mActiveTrack->mState = TrackBase::PAUSING; 4569 // do not wait for mStartStopCond if exiting 4570 if (mExiting) { 4571 return; 4572 } 4573 mStartStopCond.wait(mLock); 4574 // if we have been restarted, recordTrack == mActiveTrack.get() here 4575 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) { 4576 mLock.unlock(); 4577 AudioSystem::stopInput(mId); 4578 mLock.lock(); 4579 ALOGV("Record stopped OK"); 4580 } 4581 } 4582 } 4583} 4584 4585status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args) 4586{ 4587 const size_t SIZE = 256; 4588 char buffer[SIZE]; 4589 String8 result; 4590 4591 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this); 4592 result.append(buffer); 4593 4594 if (mActiveTrack != 0) { 4595 result.append("Active Track:\n"); 4596 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n"); 4597 mActiveTrack->dump(buffer, SIZE); 4598 result.append(buffer); 4599 4600 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex); 4601 result.append(buffer); 4602 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes); 4603 result.append(buffer); 4604 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL)); 4605 result.append(buffer); 4606 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount); 4607 result.append(buffer); 4608 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate); 4609 result.append(buffer); 4610 4611 4612 } else { 4613 result.append("No record client\n"); 4614 } 4615 write(fd, result.string(), result.size()); 4616 4617 dumpBase(fd, args); 4618 dumpEffectChains(fd, args); 4619 4620 return NO_ERROR; 4621} 4622 4623status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer) 4624{ 4625 size_t framesReq = buffer->frameCount; 4626 size_t framesReady = mFrameCount - mRsmpInIndex; 4627 int channelCount; 4628 4629 if (framesReady == 0) { 4630 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes); 4631 if (mBytesRead < 0) { 4632 ALOGE("RecordThread::getNextBuffer() Error reading audio input"); 4633 if (mActiveTrack->mState == TrackBase::ACTIVE) { 4634 // Force input into standby so that it tries to 4635 // recover at next read attempt 4636 mInput->stream->common.standby(&mInput->stream->common); 4637 usleep(kRecordThreadSleepUs); 4638 } 4639 buffer->raw = NULL; 4640 buffer->frameCount = 0; 4641 return NOT_ENOUGH_DATA; 4642 } 4643 mRsmpInIndex = 0; 4644 framesReady = mFrameCount; 4645 } 4646 4647 if (framesReq > framesReady) { 4648 framesReq = framesReady; 4649 } 4650 4651 if (mChannelCount == 1 && mReqChannelCount == 2) { 4652 channelCount = 1; 4653 } else { 4654 channelCount = 2; 4655 } 4656 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount; 4657 buffer->frameCount = framesReq; 4658 return NO_ERROR; 4659} 4660 4661void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer) 4662{ 4663 mRsmpInIndex += buffer->frameCount; 4664 buffer->frameCount = 0; 4665} 4666 4667bool AudioFlinger::RecordThread::checkForNewParameters_l() 4668{ 4669 bool reconfig = false; 4670 4671 while (!mNewParameters.isEmpty()) { 4672 status_t status = NO_ERROR; 4673 String8 keyValuePair = mNewParameters[0]; 4674 AudioParameter param = AudioParameter(keyValuePair); 4675 int value; 4676 audio_format_t reqFormat = mFormat; 4677 int reqSamplingRate = mReqSampleRate; 4678 int reqChannelCount = mReqChannelCount; 4679 4680 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { 4681 reqSamplingRate = value; 4682 reconfig = true; 4683 } 4684 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { 4685 reqFormat = (audio_format_t) value; 4686 reconfig = true; 4687 } 4688 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { 4689 reqChannelCount = popcount(value); 4690 reconfig = true; 4691 } 4692 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 4693 // do not accept frame count changes if tracks are open as the track buffer 4694 // size depends on frame count and correct behavior would not be garantied 4695 // if frame count is changed after track creation 4696 if (mActiveTrack != 0) { 4697 status = INVALID_OPERATION; 4698 } else { 4699 reconfig = true; 4700 } 4701 } 4702 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 4703 // forward device change to effects that have requested to be 4704 // aware of attached audio device. 4705 for (size_t i = 0; i < mEffectChains.size(); i++) { 4706 mEffectChains[i]->setDevice_l(value); 4707 } 4708 // store input device and output device but do not forward output device to audio HAL. 4709 // Note that status is ignored by the caller for output device 4710 // (see AudioFlinger::setParameters() 4711 if (value & AUDIO_DEVICE_OUT_ALL) { 4712 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL); 4713 status = BAD_VALUE; 4714 } else { 4715 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL); 4716 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 4717 if (mTrack != NULL) { 4718 bool suspend = audio_is_bluetooth_sco_device( 4719 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff(); 4720 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId()); 4721 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId()); 4722 } 4723 } 4724 mDevice |= (uint32_t)value; 4725 } 4726 if (status == NO_ERROR) { 4727 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string()); 4728 if (status == INVALID_OPERATION) { 4729 mInput->stream->common.standby(&mInput->stream->common); 4730 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string()); 4731 } 4732 if (reconfig) { 4733 if (status == BAD_VALUE && 4734 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) && 4735 reqFormat == AUDIO_FORMAT_PCM_16_BIT && 4736 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) && 4737 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) && 4738 (reqChannelCount < 3)) { 4739 status = NO_ERROR; 4740 } 4741 if (status == NO_ERROR) { 4742 readInputParameters(); 4743 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED); 4744 } 4745 } 4746 } 4747 4748 mNewParameters.removeAt(0); 4749 4750 mParamStatus = status; 4751 mParamCond.signal(); 4752 // wait for condition with time out in case the thread calling ThreadBase::setParameters() 4753 // already timed out waiting for the status and will never signal the condition. 4754 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); 4755 } 4756 return reconfig; 4757} 4758 4759String8 AudioFlinger::RecordThread::getParameters(const String8& keys) 4760{ 4761 char *s; 4762 String8 out_s8 = String8(); 4763 4764 Mutex::Autolock _l(mLock); 4765 if (initCheck() != NO_ERROR) { 4766 return out_s8; 4767 } 4768 4769 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string()); 4770 out_s8 = String8(s); 4771 free(s); 4772 return out_s8; 4773} 4774 4775void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) { 4776 AudioSystem::OutputDescriptor desc; 4777 void *param2 = NULL; 4778 4779 switch (event) { 4780 case AudioSystem::INPUT_OPENED: 4781 case AudioSystem::INPUT_CONFIG_CHANGED: 4782 desc.channels = mChannelMask; 4783 desc.samplingRate = mSampleRate; 4784 desc.format = mFormat; 4785 desc.frameCount = mFrameCount; 4786 desc.latency = 0; 4787 param2 = &desc; 4788 break; 4789 4790 case AudioSystem::INPUT_CLOSED: 4791 default: 4792 break; 4793 } 4794 mAudioFlinger->audioConfigChanged_l(event, mId, param2); 4795} 4796 4797void AudioFlinger::RecordThread::readInputParameters() 4798{ 4799 delete mRsmpInBuffer; 4800 // mRsmpInBuffer is always assigned a new[] below 4801 delete mRsmpOutBuffer; 4802 mRsmpOutBuffer = NULL; 4803 delete mResampler; 4804 mResampler = NULL; 4805 4806 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common); 4807 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common); 4808 mChannelCount = (uint16_t)popcount(mChannelMask); 4809 mFormat = mInput->stream->common.get_format(&mInput->stream->common); 4810 mFrameSize = audio_stream_frame_size(&mInput->stream->common); 4811 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common); 4812 mFrameCount = mInputBytes / mFrameSize; 4813 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount]; 4814 4815 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3) 4816 { 4817 int channelCount; 4818 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid 4819 // stereo to mono post process as the resampler always outputs stereo. 4820 if (mChannelCount == 1 && mReqChannelCount == 2) { 4821 channelCount = 1; 4822 } else { 4823 channelCount = 2; 4824 } 4825 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate); 4826 mResampler->setSampleRate(mSampleRate); 4827 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN); 4828 mRsmpOutBuffer = new int32_t[mFrameCount * 2]; 4829 4830 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples 4831 if (mChannelCount == 1 && mReqChannelCount == 1) { 4832 mFrameCount >>= 1; 4833 } 4834 4835 } 4836 mRsmpInIndex = mFrameCount; 4837} 4838 4839unsigned int AudioFlinger::RecordThread::getInputFramesLost() 4840{ 4841 Mutex::Autolock _l(mLock); 4842 if (initCheck() != NO_ERROR) { 4843 return 0; 4844 } 4845 4846 return mInput->stream->get_input_frames_lost(mInput->stream); 4847} 4848 4849uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) 4850{ 4851 Mutex::Autolock _l(mLock); 4852 uint32_t result = 0; 4853 if (getEffectChain_l(sessionId) != 0) { 4854 result = EFFECT_SESSION; 4855 } 4856 4857 if (mTrack != NULL && sessionId == mTrack->sessionId()) { 4858 result |= TRACK_SESSION; 4859 } 4860 4861 return result; 4862} 4863 4864AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track() 4865{ 4866 Mutex::Autolock _l(mLock); 4867 return mTrack; 4868} 4869 4870AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const 4871{ 4872 Mutex::Autolock _l(mLock); 4873 return mInput; 4874} 4875 4876AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput() 4877{ 4878 Mutex::Autolock _l(mLock); 4879 AudioStreamIn *input = mInput; 4880 mInput = NULL; 4881 return input; 4882} 4883 4884// this method must always be called either with ThreadBase mLock held or inside the thread loop 4885audio_stream_t* AudioFlinger::RecordThread::stream() 4886{ 4887 if (mInput == NULL) { 4888 return NULL; 4889 } 4890 return &mInput->stream->common; 4891} 4892 4893 4894// ---------------------------------------------------------------------------- 4895 4896audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices, 4897 uint32_t *pSamplingRate, 4898 audio_format_t *pFormat, 4899 uint32_t *pChannels, 4900 uint32_t *pLatencyMs, 4901 uint32_t flags) 4902{ 4903 status_t status; 4904 PlaybackThread *thread = NULL; 4905 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN; 4906 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0; 4907 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT; 4908 uint32_t channels = pChannels ? *pChannels : 0; 4909 uint32_t latency = pLatencyMs ? *pLatencyMs : 0; 4910 audio_stream_out_t *outStream; 4911 audio_hw_device_t *outHwDev; 4912 4913 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x", 4914 pDevices ? *pDevices : 0, 4915 samplingRate, 4916 format, 4917 channels, 4918 flags); 4919 4920 if (pDevices == NULL || *pDevices == 0) { 4921 return 0; 4922 } 4923 4924 Mutex::Autolock _l(mLock); 4925 4926 outHwDev = findSuitableHwDev_l(*pDevices); 4927 if (outHwDev == NULL) 4928 return 0; 4929 4930 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format, 4931 &channels, &samplingRate, &outStream); 4932 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d", 4933 outStream, 4934 samplingRate, 4935 format, 4936 channels, 4937 status); 4938 4939 mHardwareStatus = AUDIO_HW_IDLE; 4940 if (outStream != NULL) { 4941 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream); 4942 audio_io_handle_t id = nextUniqueId(); 4943 4944 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) || 4945 (format != AUDIO_FORMAT_PCM_16_BIT) || 4946 (channels != AUDIO_CHANNEL_OUT_STEREO)) { 4947 thread = new DirectOutputThread(this, output, id, *pDevices); 4948 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread); 4949 } else { 4950 thread = new MixerThread(this, output, id, *pDevices); 4951 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread); 4952 } 4953 mPlaybackThreads.add(id, thread); 4954 4955 if (pSamplingRate != NULL) *pSamplingRate = samplingRate; 4956 if (pFormat != NULL) *pFormat = format; 4957 if (pChannels != NULL) *pChannels = channels; 4958 if (pLatencyMs != NULL) *pLatencyMs = thread->latency(); 4959 4960 // notify client processes of the new output creation 4961 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED); 4962 return id; 4963 } 4964 4965 return 0; 4966} 4967 4968audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1, 4969 audio_io_handle_t output2) 4970{ 4971 Mutex::Autolock _l(mLock); 4972 MixerThread *thread1 = checkMixerThread_l(output1); 4973 MixerThread *thread2 = checkMixerThread_l(output2); 4974 4975 if (thread1 == NULL || thread2 == NULL) { 4976 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2); 4977 return 0; 4978 } 4979 4980 audio_io_handle_t id = nextUniqueId(); 4981 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id); 4982 thread->addOutputTrack(thread2); 4983 mPlaybackThreads.add(id, thread); 4984 // notify client processes of the new output creation 4985 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED); 4986 return id; 4987} 4988 4989status_t AudioFlinger::closeOutput(audio_io_handle_t output) 4990{ 4991 // keep strong reference on the playback thread so that 4992 // it is not destroyed while exit() is executed 4993 sp <PlaybackThread> thread; 4994 { 4995 Mutex::Autolock _l(mLock); 4996 thread = checkPlaybackThread_l(output); 4997 if (thread == NULL) { 4998 return BAD_VALUE; 4999 } 5000 5001 ALOGV("closeOutput() %d", output); 5002 5003 if (thread->type() == ThreadBase::MIXER) { 5004 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 5005 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) { 5006 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get(); 5007 dupThread->removeOutputTrack((MixerThread *)thread.get()); 5008 } 5009 } 5010 } 5011 void *param2 = NULL; 5012 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2); 5013 mPlaybackThreads.removeItem(output); 5014 } 5015 thread->exit(); 5016 5017 if (thread->type() != ThreadBase::DUPLICATING) { 5018 AudioStreamOut *out = thread->clearOutput(); 5019 assert(out != NULL); 5020 // from now on thread->mOutput is NULL 5021 out->hwDev->close_output_stream(out->hwDev, out->stream); 5022 delete out; 5023 } 5024 return NO_ERROR; 5025} 5026 5027status_t AudioFlinger::suspendOutput(audio_io_handle_t output) 5028{ 5029 Mutex::Autolock _l(mLock); 5030 PlaybackThread *thread = checkPlaybackThread_l(output); 5031 5032 if (thread == NULL) { 5033 return BAD_VALUE; 5034 } 5035 5036 ALOGV("suspendOutput() %d", output); 5037 thread->suspend(); 5038 5039 return NO_ERROR; 5040} 5041 5042status_t AudioFlinger::restoreOutput(audio_io_handle_t output) 5043{ 5044 Mutex::Autolock _l(mLock); 5045 PlaybackThread *thread = checkPlaybackThread_l(output); 5046 5047 if (thread == NULL) { 5048 return BAD_VALUE; 5049 } 5050 5051 ALOGV("restoreOutput() %d", output); 5052 5053 thread->restore(); 5054 5055 return NO_ERROR; 5056} 5057 5058audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices, 5059 uint32_t *pSamplingRate, 5060 audio_format_t *pFormat, 5061 uint32_t *pChannels, 5062 audio_in_acoustics_t acoustics) 5063{ 5064 status_t status; 5065 RecordThread *thread = NULL; 5066 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0; 5067 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT; 5068 uint32_t channels = pChannels ? *pChannels : 0; 5069 uint32_t reqSamplingRate = samplingRate; 5070 audio_format_t reqFormat = format; 5071 uint32_t reqChannels = channels; 5072 audio_stream_in_t *inStream; 5073 audio_hw_device_t *inHwDev; 5074 5075 if (pDevices == NULL || *pDevices == 0) { 5076 return 0; 5077 } 5078 5079 Mutex::Autolock _l(mLock); 5080 5081 inHwDev = findSuitableHwDev_l(*pDevices); 5082 if (inHwDev == NULL) 5083 return 0; 5084 5085 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format, 5086 &channels, &samplingRate, 5087 acoustics, 5088 &inStream); 5089 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d", 5090 inStream, 5091 samplingRate, 5092 format, 5093 channels, 5094 acoustics, 5095 status); 5096 5097 // If the input could not be opened with the requested parameters and we can handle the conversion internally, 5098 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo 5099 // or stereo to mono conversions on 16 bit PCM inputs. 5100 if (inStream == NULL && status == BAD_VALUE && 5101 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT && 5102 (samplingRate <= 2 * reqSamplingRate) && 5103 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) { 5104 ALOGV("openInput() reopening with proposed sampling rate and channels"); 5105 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format, 5106 &channels, &samplingRate, 5107 acoustics, 5108 &inStream); 5109 } 5110 5111 if (inStream != NULL) { 5112 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream); 5113 5114 audio_io_handle_t id = nextUniqueId(); 5115 // Start record thread 5116 // RecorThread require both input and output device indication to forward to audio 5117 // pre processing modules 5118 uint32_t device = (*pDevices) | primaryOutputDevice_l(); 5119 thread = new RecordThread(this, 5120 input, 5121 reqSamplingRate, 5122 reqChannels, 5123 id, 5124 device); 5125 mRecordThreads.add(id, thread); 5126 ALOGV("openInput() created record thread: ID %d thread %p", id, thread); 5127 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate; 5128 if (pFormat != NULL) *pFormat = format; 5129 if (pChannels != NULL) *pChannels = reqChannels; 5130 5131 input->stream->common.standby(&input->stream->common); 5132 5133 // notify client processes of the new input creation 5134 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED); 5135 return id; 5136 } 5137 5138 return 0; 5139} 5140 5141status_t AudioFlinger::closeInput(audio_io_handle_t input) 5142{ 5143 // keep strong reference on the record thread so that 5144 // it is not destroyed while exit() is executed 5145 sp <RecordThread> thread; 5146 { 5147 Mutex::Autolock _l(mLock); 5148 thread = checkRecordThread_l(input); 5149 if (thread == NULL) { 5150 return BAD_VALUE; 5151 } 5152 5153 ALOGV("closeInput() %d", input); 5154 void *param2 = NULL; 5155 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2); 5156 mRecordThreads.removeItem(input); 5157 } 5158 thread->exit(); 5159 5160 AudioStreamIn *in = thread->clearInput(); 5161 assert(in != NULL); 5162 // from now on thread->mInput is NULL 5163 in->hwDev->close_input_stream(in->hwDev, in->stream); 5164 delete in; 5165 5166 return NO_ERROR; 5167} 5168 5169status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output) 5170{ 5171 Mutex::Autolock _l(mLock); 5172 MixerThread *dstThread = checkMixerThread_l(output); 5173 if (dstThread == NULL) { 5174 ALOGW("setStreamOutput() bad output id %d", output); 5175 return BAD_VALUE; 5176 } 5177 5178 ALOGV("setStreamOutput() stream %d to output %d", stream, output); 5179 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream); 5180 5181 dstThread->setStreamValid(stream, true); 5182 5183 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 5184 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get(); 5185 if (thread != dstThread && 5186 thread->type() != ThreadBase::DIRECT) { 5187 MixerThread *srcThread = (MixerThread *)thread; 5188 srcThread->setStreamValid(stream, false); 5189 srcThread->invalidateTracks(stream); 5190 } 5191 } 5192 5193 return NO_ERROR; 5194} 5195 5196 5197int AudioFlinger::newAudioSessionId() 5198{ 5199 return nextUniqueId(); 5200} 5201 5202void AudioFlinger::acquireAudioSessionId(int audioSession) 5203{ 5204 Mutex::Autolock _l(mLock); 5205 pid_t caller = IPCThreadState::self()->getCallingPid(); 5206 ALOGV("acquiring %d from %d", audioSession, caller); 5207 int num = mAudioSessionRefs.size(); 5208 for (int i = 0; i< num; i++) { 5209 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i); 5210 if (ref->sessionid == audioSession && ref->pid == caller) { 5211 ref->cnt++; 5212 ALOGV(" incremented refcount to %d", ref->cnt); 5213 return; 5214 } 5215 } 5216 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller)); 5217 ALOGV(" added new entry for %d", audioSession); 5218} 5219 5220void AudioFlinger::releaseAudioSessionId(int audioSession) 5221{ 5222 Mutex::Autolock _l(mLock); 5223 pid_t caller = IPCThreadState::self()->getCallingPid(); 5224 ALOGV("releasing %d from %d", audioSession, caller); 5225 int num = mAudioSessionRefs.size(); 5226 for (int i = 0; i< num; i++) { 5227 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i); 5228 if (ref->sessionid == audioSession && ref->pid == caller) { 5229 ref->cnt--; 5230 ALOGV(" decremented refcount to %d", ref->cnt); 5231 if (ref->cnt == 0) { 5232 mAudioSessionRefs.removeAt(i); 5233 delete ref; 5234 purgeStaleEffects_l(); 5235 } 5236 return; 5237 } 5238 } 5239 ALOGW("session id %d not found for pid %d", audioSession, caller); 5240} 5241 5242void AudioFlinger::purgeStaleEffects_l() { 5243 5244 ALOGV("purging stale effects"); 5245 5246 Vector< sp<EffectChain> > chains; 5247 5248 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 5249 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i); 5250 for (size_t j = 0; j < t->mEffectChains.size(); j++) { 5251 sp<EffectChain> ec = t->mEffectChains[j]; 5252 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) { 5253 chains.push(ec); 5254 } 5255 } 5256 } 5257 for (size_t i = 0; i < mRecordThreads.size(); i++) { 5258 sp<RecordThread> t = mRecordThreads.valueAt(i); 5259 for (size_t j = 0; j < t->mEffectChains.size(); j++) { 5260 sp<EffectChain> ec = t->mEffectChains[j]; 5261 chains.push(ec); 5262 } 5263 } 5264 5265 for (size_t i = 0; i < chains.size(); i++) { 5266 sp<EffectChain> ec = chains[i]; 5267 int sessionid = ec->sessionId(); 5268 sp<ThreadBase> t = ec->mThread.promote(); 5269 if (t == 0) { 5270 continue; 5271 } 5272 size_t numsessionrefs = mAudioSessionRefs.size(); 5273 bool found = false; 5274 for (size_t k = 0; k < numsessionrefs; k++) { 5275 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k); 5276 if (ref->sessionid == sessionid) { 5277 ALOGV(" session %d still exists for %d with %d refs", 5278 sessionid, ref->pid, ref->cnt); 5279 found = true; 5280 break; 5281 } 5282 } 5283 if (!found) { 5284 // remove all effects from the chain 5285 while (ec->mEffects.size()) { 5286 sp<EffectModule> effect = ec->mEffects[0]; 5287 effect->unPin(); 5288 Mutex::Autolock _l (t->mLock); 5289 t->removeEffect_l(effect); 5290 for (size_t j = 0; j < effect->mHandles.size(); j++) { 5291 sp<EffectHandle> handle = effect->mHandles[j].promote(); 5292 if (handle != 0) { 5293 handle->mEffect.clear(); 5294 if (handle->mHasControl && handle->mEnabled) { 5295 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId()); 5296 } 5297 } 5298 } 5299 AudioSystem::unregisterEffect(effect->id()); 5300 } 5301 } 5302 } 5303 return; 5304} 5305 5306// checkPlaybackThread_l() must be called with AudioFlinger::mLock held 5307AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const 5308{ 5309 PlaybackThread *thread = NULL; 5310 if (mPlaybackThreads.indexOfKey(output) >= 0) { 5311 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get(); 5312 } 5313 return thread; 5314} 5315 5316// checkMixerThread_l() must be called with AudioFlinger::mLock held 5317AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const 5318{ 5319 PlaybackThread *thread = checkPlaybackThread_l(output); 5320 if (thread != NULL) { 5321 if (thread->type() == ThreadBase::DIRECT) { 5322 thread = NULL; 5323 } 5324 } 5325 return (MixerThread *)thread; 5326} 5327 5328// checkRecordThread_l() must be called with AudioFlinger::mLock held 5329AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const 5330{ 5331 RecordThread *thread = NULL; 5332 if (mRecordThreads.indexOfKey(input) >= 0) { 5333 thread = (RecordThread *)mRecordThreads.valueFor(input).get(); 5334 } 5335 return thread; 5336} 5337 5338uint32_t AudioFlinger::nextUniqueId() 5339{ 5340 return android_atomic_inc(&mNextUniqueId); 5341} 5342 5343AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() 5344{ 5345 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 5346 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get(); 5347 AudioStreamOut *output = thread->getOutput(); 5348 if (output != NULL && output->hwDev == mPrimaryHardwareDev) { 5349 return thread; 5350 } 5351 } 5352 return NULL; 5353} 5354 5355uint32_t AudioFlinger::primaryOutputDevice_l() 5356{ 5357 PlaybackThread *thread = primaryPlaybackThread_l(); 5358 5359 if (thread == NULL) { 5360 return 0; 5361 } 5362 5363 return thread->device(); 5364} 5365 5366 5367// ---------------------------------------------------------------------------- 5368// Effect management 5369// ---------------------------------------------------------------------------- 5370 5371 5372status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const 5373{ 5374 Mutex::Autolock _l(mLock); 5375 return EffectQueryNumberEffects(numEffects); 5376} 5377 5378status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const 5379{ 5380 Mutex::Autolock _l(mLock); 5381 return EffectQueryEffect(index, descriptor); 5382} 5383 5384status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid, 5385 effect_descriptor_t *descriptor) const 5386{ 5387 Mutex::Autolock _l(mLock); 5388 return EffectGetDescriptor(pUuid, descriptor); 5389} 5390 5391 5392sp<IEffect> AudioFlinger::createEffect(pid_t pid, 5393 effect_descriptor_t *pDesc, 5394 const sp<IEffectClient>& effectClient, 5395 int32_t priority, 5396 audio_io_handle_t io, 5397 int sessionId, 5398 status_t *status, 5399 int *id, 5400 int *enabled) 5401{ 5402 status_t lStatus = NO_ERROR; 5403 sp<EffectHandle> handle; 5404 effect_descriptor_t desc; 5405 5406 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d", 5407 pid, effectClient.get(), priority, sessionId, io); 5408 5409 if (pDesc == NULL) { 5410 lStatus = BAD_VALUE; 5411 goto Exit; 5412 } 5413 5414 // check audio settings permission for global effects 5415 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) { 5416 lStatus = PERMISSION_DENIED; 5417 goto Exit; 5418 } 5419 5420 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects 5421 // that can only be created by audio policy manager (running in same process) 5422 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) { 5423 lStatus = PERMISSION_DENIED; 5424 goto Exit; 5425 } 5426 5427 if (io == 0) { 5428 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) { 5429 // output must be specified by AudioPolicyManager when using session 5430 // AUDIO_SESSION_OUTPUT_STAGE 5431 lStatus = BAD_VALUE; 5432 goto Exit; 5433 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) { 5434 // if the output returned by getOutputForEffect() is removed before we lock the 5435 // mutex below, the call to checkPlaybackThread_l(io) below will detect it 5436 // and we will exit safely 5437 io = AudioSystem::getOutputForEffect(&desc); 5438 } 5439 } 5440 5441 { 5442 Mutex::Autolock _l(mLock); 5443 5444 5445 if (!EffectIsNullUuid(&pDesc->uuid)) { 5446 // if uuid is specified, request effect descriptor 5447 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc); 5448 if (lStatus < 0) { 5449 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus); 5450 goto Exit; 5451 } 5452 } else { 5453 // if uuid is not specified, look for an available implementation 5454 // of the required type in effect factory 5455 if (EffectIsNullUuid(&pDesc->type)) { 5456 ALOGW("createEffect() no effect type"); 5457 lStatus = BAD_VALUE; 5458 goto Exit; 5459 } 5460 uint32_t numEffects = 0; 5461 effect_descriptor_t d; 5462 d.flags = 0; // prevent compiler warning 5463 bool found = false; 5464 5465 lStatus = EffectQueryNumberEffects(&numEffects); 5466 if (lStatus < 0) { 5467 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus); 5468 goto Exit; 5469 } 5470 for (uint32_t i = 0; i < numEffects; i++) { 5471 lStatus = EffectQueryEffect(i, &desc); 5472 if (lStatus < 0) { 5473 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus); 5474 continue; 5475 } 5476 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) { 5477 // If matching type found save effect descriptor. If the session is 5478 // 0 and the effect is not auxiliary, continue enumeration in case 5479 // an auxiliary version of this effect type is available 5480 found = true; 5481 memcpy(&d, &desc, sizeof(effect_descriptor_t)); 5482 if (sessionId != AUDIO_SESSION_OUTPUT_MIX || 5483 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 5484 break; 5485 } 5486 } 5487 } 5488 if (!found) { 5489 lStatus = BAD_VALUE; 5490 ALOGW("createEffect() effect not found"); 5491 goto Exit; 5492 } 5493 // For same effect type, chose auxiliary version over insert version if 5494 // connect to output mix (Compliance to OpenSL ES) 5495 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && 5496 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) { 5497 memcpy(&desc, &d, sizeof(effect_descriptor_t)); 5498 } 5499 } 5500 5501 // Do not allow auxiliary effects on a session different from 0 (output mix) 5502 if (sessionId != AUDIO_SESSION_OUTPUT_MIX && 5503 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 5504 lStatus = INVALID_OPERATION; 5505 goto Exit; 5506 } 5507 5508 // check recording permission for visualizer 5509 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) && 5510 !recordingAllowed()) { 5511 lStatus = PERMISSION_DENIED; 5512 goto Exit; 5513 } 5514 5515 // return effect descriptor 5516 memcpy(pDesc, &desc, sizeof(effect_descriptor_t)); 5517 5518 // If output is not specified try to find a matching audio session ID in one of the 5519 // output threads. 5520 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX 5521 // because of code checking output when entering the function. 5522 // Note: io is never 0 when creating an effect on an input 5523 if (io == 0) { 5524 // look for the thread where the specified audio session is present 5525 for (size_t i = 0; i < mPlaybackThreads.size(); i++) { 5526 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) { 5527 io = mPlaybackThreads.keyAt(i); 5528 break; 5529 } 5530 } 5531 if (io == 0) { 5532 for (size_t i = 0; i < mRecordThreads.size(); i++) { 5533 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) { 5534 io = mRecordThreads.keyAt(i); 5535 break; 5536 } 5537 } 5538 } 5539 // If no output thread contains the requested session ID, default to 5540 // first output. The effect chain will be moved to the correct output 5541 // thread when a track with the same session ID is created 5542 if (io == 0 && mPlaybackThreads.size()) { 5543 io = mPlaybackThreads.keyAt(0); 5544 } 5545 ALOGV("createEffect() got io %d for effect %s", io, desc.name); 5546 } 5547 ThreadBase *thread = checkRecordThread_l(io); 5548 if (thread == NULL) { 5549 thread = checkPlaybackThread_l(io); 5550 if (thread == NULL) { 5551 ALOGE("createEffect() unknown output thread"); 5552 lStatus = BAD_VALUE; 5553 goto Exit; 5554 } 5555 } 5556 5557 sp<Client> client = registerPid_l(pid); 5558 5559 // create effect on selected output thread 5560 handle = thread->createEffect_l(client, effectClient, priority, sessionId, 5561 &desc, enabled, &lStatus); 5562 if (handle != 0 && id != NULL) { 5563 *id = handle->id(); 5564 } 5565 } 5566 5567Exit: 5568 if(status) { 5569 *status = lStatus; 5570 } 5571 return handle; 5572} 5573 5574status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput, 5575 audio_io_handle_t dstOutput) 5576{ 5577 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d", 5578 sessionId, srcOutput, dstOutput); 5579 Mutex::Autolock _l(mLock); 5580 if (srcOutput == dstOutput) { 5581 ALOGW("moveEffects() same dst and src outputs %d", dstOutput); 5582 return NO_ERROR; 5583 } 5584 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput); 5585 if (srcThread == NULL) { 5586 ALOGW("moveEffects() bad srcOutput %d", srcOutput); 5587 return BAD_VALUE; 5588 } 5589 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput); 5590 if (dstThread == NULL) { 5591 ALOGW("moveEffects() bad dstOutput %d", dstOutput); 5592 return BAD_VALUE; 5593 } 5594 5595 Mutex::Autolock _dl(dstThread->mLock); 5596 Mutex::Autolock _sl(srcThread->mLock); 5597 moveEffectChain_l(sessionId, srcThread, dstThread, false); 5598 5599 return NO_ERROR; 5600} 5601 5602// moveEffectChain_l must be called with both srcThread and dstThread mLocks held 5603status_t AudioFlinger::moveEffectChain_l(int sessionId, 5604 AudioFlinger::PlaybackThread *srcThread, 5605 AudioFlinger::PlaybackThread *dstThread, 5606 bool reRegister) 5607{ 5608 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p", 5609 sessionId, srcThread, dstThread); 5610 5611 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId); 5612 if (chain == 0) { 5613 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p", 5614 sessionId, srcThread); 5615 return INVALID_OPERATION; 5616 } 5617 5618 // remove chain first. This is useful only if reconfiguring effect chain on same output thread, 5619 // so that a new chain is created with correct parameters when first effect is added. This is 5620 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is 5621 // removed. 5622 srcThread->removeEffectChain_l(chain); 5623 5624 // transfer all effects one by one so that new effect chain is created on new thread with 5625 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly 5626 audio_io_handle_t dstOutput = dstThread->id(); 5627 sp<EffectChain> dstChain; 5628 uint32_t strategy = 0; // prevent compiler warning 5629 sp<EffectModule> effect = chain->getEffectFromId_l(0); 5630 while (effect != 0) { 5631 srcThread->removeEffect_l(effect); 5632 dstThread->addEffect_l(effect); 5633 // removeEffect_l() has stopped the effect if it was active so it must be restarted 5634 if (effect->state() == EffectModule::ACTIVE || 5635 effect->state() == EffectModule::STOPPING) { 5636 effect->start(); 5637 } 5638 // if the move request is not received from audio policy manager, the effect must be 5639 // re-registered with the new strategy and output 5640 if (dstChain == 0) { 5641 dstChain = effect->chain().promote(); 5642 if (dstChain == 0) { 5643 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get()); 5644 srcThread->addEffect_l(effect); 5645 return NO_INIT; 5646 } 5647 strategy = dstChain->strategy(); 5648 } 5649 if (reRegister) { 5650 AudioSystem::unregisterEffect(effect->id()); 5651 AudioSystem::registerEffect(&effect->desc(), 5652 dstOutput, 5653 strategy, 5654 sessionId, 5655 effect->id()); 5656 } 5657 effect = chain->getEffectFromId_l(0); 5658 } 5659 5660 return NO_ERROR; 5661} 5662 5663 5664// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held 5665sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l( 5666 const sp<AudioFlinger::Client>& client, 5667 const sp<IEffectClient>& effectClient, 5668 int32_t priority, 5669 int sessionId, 5670 effect_descriptor_t *desc, 5671 int *enabled, 5672 status_t *status 5673 ) 5674{ 5675 sp<EffectModule> effect; 5676 sp<EffectHandle> handle; 5677 status_t lStatus; 5678 sp<EffectChain> chain; 5679 bool chainCreated = false; 5680 bool effectCreated = false; 5681 bool effectRegistered = false; 5682 5683 lStatus = initCheck(); 5684 if (lStatus != NO_ERROR) { 5685 ALOGW("createEffect_l() Audio driver not initialized."); 5686 goto Exit; 5687 } 5688 5689 // Do not allow effects with session ID 0 on direct output or duplicating threads 5690 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format 5691 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) { 5692 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d", 5693 desc->name, sessionId); 5694 lStatus = BAD_VALUE; 5695 goto Exit; 5696 } 5697 // Only Pre processor effects are allowed on input threads and only on input threads 5698 if ((mType == RECORD && 5699 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) || 5700 (mType != RECORD && 5701 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) { 5702 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d", 5703 desc->name, desc->flags, mType); 5704 lStatus = BAD_VALUE; 5705 goto Exit; 5706 } 5707 5708 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId); 5709 5710 { // scope for mLock 5711 Mutex::Autolock _l(mLock); 5712 5713 // check for existing effect chain with the requested audio session 5714 chain = getEffectChain_l(sessionId); 5715 if (chain == 0) { 5716 // create a new chain for this session 5717 ALOGV("createEffect_l() new effect chain for session %d", sessionId); 5718 chain = new EffectChain(this, sessionId); 5719 addEffectChain_l(chain); 5720 chain->setStrategy(getStrategyForSession_l(sessionId)); 5721 chainCreated = true; 5722 } else { 5723 effect = chain->getEffectFromDesc_l(desc); 5724 } 5725 5726 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get()); 5727 5728 if (effect == 0) { 5729 int id = mAudioFlinger->nextUniqueId(); 5730 // Check CPU and memory usage 5731 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id); 5732 if (lStatus != NO_ERROR) { 5733 goto Exit; 5734 } 5735 effectRegistered = true; 5736 // create a new effect module if none present in the chain 5737 effect = new EffectModule(this, chain, desc, id, sessionId); 5738 lStatus = effect->status(); 5739 if (lStatus != NO_ERROR) { 5740 goto Exit; 5741 } 5742 lStatus = chain->addEffect_l(effect); 5743 if (lStatus != NO_ERROR) { 5744 goto Exit; 5745 } 5746 effectCreated = true; 5747 5748 effect->setDevice(mDevice); 5749 effect->setMode(mAudioFlinger->getMode()); 5750 } 5751 // create effect handle and connect it to effect module 5752 handle = new EffectHandle(effect, client, effectClient, priority); 5753 lStatus = effect->addHandle(handle); 5754 if (enabled != NULL) { 5755 *enabled = (int)effect->isEnabled(); 5756 } 5757 } 5758 5759Exit: 5760 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) { 5761 Mutex::Autolock _l(mLock); 5762 if (effectCreated) { 5763 chain->removeEffect_l(effect); 5764 } 5765 if (effectRegistered) { 5766 AudioSystem::unregisterEffect(effect->id()); 5767 } 5768 if (chainCreated) { 5769 removeEffectChain_l(chain); 5770 } 5771 handle.clear(); 5772 } 5773 5774 if(status) { 5775 *status = lStatus; 5776 } 5777 return handle; 5778} 5779 5780sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId) 5781{ 5782 sp<EffectChain> chain = getEffectChain_l(sessionId); 5783 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0; 5784} 5785 5786// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and 5787// PlaybackThread::mLock held 5788status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect) 5789{ 5790 // check for existing effect chain with the requested audio session 5791 int sessionId = effect->sessionId(); 5792 sp<EffectChain> chain = getEffectChain_l(sessionId); 5793 bool chainCreated = false; 5794 5795 if (chain == 0) { 5796 // create a new chain for this session 5797 ALOGV("addEffect_l() new effect chain for session %d", sessionId); 5798 chain = new EffectChain(this, sessionId); 5799 addEffectChain_l(chain); 5800 chain->setStrategy(getStrategyForSession_l(sessionId)); 5801 chainCreated = true; 5802 } 5803 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get()); 5804 5805 if (chain->getEffectFromId_l(effect->id()) != 0) { 5806 ALOGW("addEffect_l() %p effect %s already present in chain %p", 5807 this, effect->desc().name, chain.get()); 5808 return BAD_VALUE; 5809 } 5810 5811 status_t status = chain->addEffect_l(effect); 5812 if (status != NO_ERROR) { 5813 if (chainCreated) { 5814 removeEffectChain_l(chain); 5815 } 5816 return status; 5817 } 5818 5819 effect->setDevice(mDevice); 5820 effect->setMode(mAudioFlinger->getMode()); 5821 return NO_ERROR; 5822} 5823 5824void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) { 5825 5826 ALOGV("removeEffect_l() %p effect %p", this, effect.get()); 5827 effect_descriptor_t desc = effect->desc(); 5828 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 5829 detachAuxEffect_l(effect->id()); 5830 } 5831 5832 sp<EffectChain> chain = effect->chain().promote(); 5833 if (chain != 0) { 5834 // remove effect chain if removing last effect 5835 if (chain->removeEffect_l(effect) == 0) { 5836 removeEffectChain_l(chain); 5837 } 5838 } else { 5839 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get()); 5840 } 5841} 5842 5843void AudioFlinger::ThreadBase::lockEffectChains_l( 5844 Vector<sp <AudioFlinger::EffectChain> >& effectChains) 5845{ 5846 effectChains = mEffectChains; 5847 for (size_t i = 0; i < mEffectChains.size(); i++) { 5848 mEffectChains[i]->lock(); 5849 } 5850} 5851 5852void AudioFlinger::ThreadBase::unlockEffectChains( 5853 Vector<sp <AudioFlinger::EffectChain> >& effectChains) 5854{ 5855 for (size_t i = 0; i < effectChains.size(); i++) { 5856 effectChains[i]->unlock(); 5857 } 5858} 5859 5860sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId) 5861{ 5862 Mutex::Autolock _l(mLock); 5863 return getEffectChain_l(sessionId); 5864} 5865 5866sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) 5867{ 5868 size_t size = mEffectChains.size(); 5869 for (size_t i = 0; i < size; i++) { 5870 if (mEffectChains[i]->sessionId() == sessionId) { 5871 return mEffectChains[i]; 5872 } 5873 } 5874 return 0; 5875} 5876 5877void AudioFlinger::ThreadBase::setMode(audio_mode_t mode) 5878{ 5879 Mutex::Autolock _l(mLock); 5880 size_t size = mEffectChains.size(); 5881 for (size_t i = 0; i < size; i++) { 5882 mEffectChains[i]->setMode_l(mode); 5883 } 5884} 5885 5886void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect, 5887 const wp<EffectHandle>& handle, 5888 bool unpinIfLast) { 5889 5890 Mutex::Autolock _l(mLock); 5891 ALOGV("disconnectEffect() %p effect %p", this, effect.get()); 5892 // delete the effect module if removing last handle on it 5893 if (effect->removeHandle(handle) == 0) { 5894 if (!effect->isPinned() || unpinIfLast) { 5895 removeEffect_l(effect); 5896 AudioSystem::unregisterEffect(effect->id()); 5897 } 5898 } 5899} 5900 5901status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain) 5902{ 5903 int session = chain->sessionId(); 5904 int16_t *buffer = mMixBuffer; 5905 bool ownsBuffer = false; 5906 5907 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session); 5908 if (session > 0) { 5909 // Only one effect chain can be present in direct output thread and it uses 5910 // the mix buffer as input 5911 if (mType != DIRECT) { 5912 size_t numSamples = mFrameCount * mChannelCount; 5913 buffer = new int16_t[numSamples]; 5914 memset(buffer, 0, numSamples * sizeof(int16_t)); 5915 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session); 5916 ownsBuffer = true; 5917 } 5918 5919 // Attach all tracks with same session ID to this chain. 5920 for (size_t i = 0; i < mTracks.size(); ++i) { 5921 sp<Track> track = mTracks[i]; 5922 if (session == track->sessionId()) { 5923 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer); 5924 track->setMainBuffer(buffer); 5925 chain->incTrackCnt(); 5926 } 5927 } 5928 5929 // indicate all active tracks in the chain 5930 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) { 5931 sp<Track> track = mActiveTracks[i].promote(); 5932 if (track == 0) continue; 5933 if (session == track->sessionId()) { 5934 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session); 5935 chain->incActiveTrackCnt(); 5936 } 5937 } 5938 } 5939 5940 chain->setInBuffer(buffer, ownsBuffer); 5941 chain->setOutBuffer(mMixBuffer); 5942 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect 5943 // chains list in order to be processed last as it contains output stage effects 5944 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before 5945 // session AUDIO_SESSION_OUTPUT_STAGE to be processed 5946 // after track specific effects and before output stage 5947 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and 5948 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX 5949 // Effect chain for other sessions are inserted at beginning of effect 5950 // chains list to be processed before output mix effects. Relative order between other 5951 // sessions is not important 5952 size_t size = mEffectChains.size(); 5953 size_t i = 0; 5954 for (i = 0; i < size; i++) { 5955 if (mEffectChains[i]->sessionId() < session) break; 5956 } 5957 mEffectChains.insertAt(chain, i); 5958 checkSuspendOnAddEffectChain_l(chain); 5959 5960 return NO_ERROR; 5961} 5962 5963size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain) 5964{ 5965 int session = chain->sessionId(); 5966 5967 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session); 5968 5969 for (size_t i = 0; i < mEffectChains.size(); i++) { 5970 if (chain == mEffectChains[i]) { 5971 mEffectChains.removeAt(i); 5972 // detach all active tracks from the chain 5973 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) { 5974 sp<Track> track = mActiveTracks[i].promote(); 5975 if (track == 0) continue; 5976 if (session == track->sessionId()) { 5977 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d", 5978 chain.get(), session); 5979 chain->decActiveTrackCnt(); 5980 } 5981 } 5982 5983 // detach all tracks with same session ID from this chain 5984 for (size_t i = 0; i < mTracks.size(); ++i) { 5985 sp<Track> track = mTracks[i]; 5986 if (session == track->sessionId()) { 5987 track->setMainBuffer(mMixBuffer); 5988 chain->decTrackCnt(); 5989 } 5990 } 5991 break; 5992 } 5993 } 5994 return mEffectChains.size(); 5995} 5996 5997status_t AudioFlinger::PlaybackThread::attachAuxEffect( 5998 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId) 5999{ 6000 Mutex::Autolock _l(mLock); 6001 return attachAuxEffect_l(track, EffectId); 6002} 6003 6004status_t AudioFlinger::PlaybackThread::attachAuxEffect_l( 6005 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId) 6006{ 6007 status_t status = NO_ERROR; 6008 6009 if (EffectId == 0) { 6010 track->setAuxBuffer(0, NULL); 6011 } else { 6012 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX 6013 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId); 6014 if (effect != 0) { 6015 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 6016 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer()); 6017 } else { 6018 status = INVALID_OPERATION; 6019 } 6020 } else { 6021 status = BAD_VALUE; 6022 } 6023 } 6024 return status; 6025} 6026 6027void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId) 6028{ 6029 for (size_t i = 0; i < mTracks.size(); ++i) { 6030 sp<Track> track = mTracks[i]; 6031 if (track->auxEffectId() == effectId) { 6032 attachAuxEffect_l(track, 0); 6033 } 6034 } 6035} 6036 6037status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain) 6038{ 6039 // only one chain per input thread 6040 if (mEffectChains.size() != 0) { 6041 return INVALID_OPERATION; 6042 } 6043 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this); 6044 6045 chain->setInBuffer(NULL); 6046 chain->setOutBuffer(NULL); 6047 6048 checkSuspendOnAddEffectChain_l(chain); 6049 6050 mEffectChains.add(chain); 6051 6052 return NO_ERROR; 6053} 6054 6055size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain) 6056{ 6057 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this); 6058 ALOGW_IF(mEffectChains.size() != 1, 6059 "removeEffectChain_l() %p invalid chain size %d on thread %p", 6060 chain.get(), mEffectChains.size(), this); 6061 if (mEffectChains.size() == 1) { 6062 mEffectChains.removeAt(0); 6063 } 6064 return 0; 6065} 6066 6067// ---------------------------------------------------------------------------- 6068// EffectModule implementation 6069// ---------------------------------------------------------------------------- 6070 6071#undef LOG_TAG 6072#define LOG_TAG "AudioFlinger::EffectModule" 6073 6074AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread, 6075 const wp<AudioFlinger::EffectChain>& chain, 6076 effect_descriptor_t *desc, 6077 int id, 6078 int sessionId) 6079 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL), 6080 mStatus(NO_INIT), mState(IDLE), mSuspended(false) 6081{ 6082 ALOGV("Constructor %p", this); 6083 int lStatus; 6084 sp<ThreadBase> thread = mThread.promote(); 6085 if (thread == 0) { 6086 return; 6087 } 6088 6089 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t)); 6090 6091 // create effect engine from effect factory 6092 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface); 6093 6094 if (mStatus != NO_ERROR) { 6095 return; 6096 } 6097 lStatus = init(); 6098 if (lStatus < 0) { 6099 mStatus = lStatus; 6100 goto Error; 6101 } 6102 6103 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) { 6104 mPinned = true; 6105 } 6106 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface); 6107 return; 6108Error: 6109 EffectRelease(mEffectInterface); 6110 mEffectInterface = NULL; 6111 ALOGV("Constructor Error %d", mStatus); 6112} 6113 6114AudioFlinger::EffectModule::~EffectModule() 6115{ 6116 ALOGV("Destructor %p", this); 6117 if (mEffectInterface != NULL) { 6118 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC || 6119 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) { 6120 sp<ThreadBase> thread = mThread.promote(); 6121 if (thread != 0) { 6122 audio_stream_t *stream = thread->stream(); 6123 if (stream != NULL) { 6124 stream->remove_audio_effect(stream, mEffectInterface); 6125 } 6126 } 6127 } 6128 // release effect engine 6129 EffectRelease(mEffectInterface); 6130 } 6131} 6132 6133status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle) 6134{ 6135 status_t status; 6136 6137 Mutex::Autolock _l(mLock); 6138 // First handle in mHandles has highest priority and controls the effect module 6139 int priority = handle->priority(); 6140 size_t size = mHandles.size(); 6141 sp<EffectHandle> h; 6142 size_t i; 6143 for (i = 0; i < size; i++) { 6144 h = mHandles[i].promote(); 6145 if (h == 0) continue; 6146 if (h->priority() <= priority) break; 6147 } 6148 // if inserted in first place, move effect control from previous owner to this handle 6149 if (i == 0) { 6150 bool enabled = false; 6151 if (h != 0) { 6152 enabled = h->enabled(); 6153 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/); 6154 } 6155 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/); 6156 status = NO_ERROR; 6157 } else { 6158 status = ALREADY_EXISTS; 6159 } 6160 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i); 6161 mHandles.insertAt(handle, i); 6162 return status; 6163} 6164 6165size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle) 6166{ 6167 Mutex::Autolock _l(mLock); 6168 size_t size = mHandles.size(); 6169 size_t i; 6170 for (i = 0; i < size; i++) { 6171 if (mHandles[i] == handle) break; 6172 } 6173 if (i == size) { 6174 return size; 6175 } 6176 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i); 6177 6178 bool enabled = false; 6179 EffectHandle *hdl = handle.unsafe_get(); 6180 if (hdl != NULL) { 6181 ALOGV("removeHandle() unsafe_get OK"); 6182 enabled = hdl->enabled(); 6183 } 6184 mHandles.removeAt(i); 6185 size = mHandles.size(); 6186 // if removed from first place, move effect control from this handle to next in line 6187 if (i == 0 && size != 0) { 6188 sp<EffectHandle> h = mHandles[0].promote(); 6189 if (h != 0) { 6190 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/); 6191 } 6192 } 6193 6194 // Prevent calls to process() and other functions on effect interface from now on. 6195 // The effect engine will be released by the destructor when the last strong reference on 6196 // this object is released which can happen after next process is called. 6197 if (size == 0 && !mPinned) { 6198 mState = DESTROYED; 6199 } 6200 6201 return size; 6202} 6203 6204sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle() 6205{ 6206 Mutex::Autolock _l(mLock); 6207 return mHandles.size() != 0 ? mHandles[0].promote() : 0; 6208} 6209 6210void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast) 6211{ 6212 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get()); 6213 // keep a strong reference on this EffectModule to avoid calling the 6214 // destructor before we exit 6215 sp<EffectModule> keep(this); 6216 { 6217 sp<ThreadBase> thread = mThread.promote(); 6218 if (thread != 0) { 6219 thread->disconnectEffect(keep, handle, unpinIfLast); 6220 } 6221 } 6222} 6223 6224void AudioFlinger::EffectModule::updateState() { 6225 Mutex::Autolock _l(mLock); 6226 6227 switch (mState) { 6228 case RESTART: 6229 reset_l(); 6230 // FALL THROUGH 6231 6232 case STARTING: 6233 // clear auxiliary effect input buffer for next accumulation 6234 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 6235 memset(mConfig.inputCfg.buffer.raw, 6236 0, 6237 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t)); 6238 } 6239 start_l(); 6240 mState = ACTIVE; 6241 break; 6242 case STOPPING: 6243 stop_l(); 6244 mDisableWaitCnt = mMaxDisableWaitCnt; 6245 mState = STOPPED; 6246 break; 6247 case STOPPED: 6248 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the 6249 // turn off sequence. 6250 if (--mDisableWaitCnt == 0) { 6251 reset_l(); 6252 mState = IDLE; 6253 } 6254 break; 6255 default: //IDLE , ACTIVE, DESTROYED 6256 break; 6257 } 6258} 6259 6260void AudioFlinger::EffectModule::process() 6261{ 6262 Mutex::Autolock _l(mLock); 6263 6264 if (mState == DESTROYED || mEffectInterface == NULL || 6265 mConfig.inputCfg.buffer.raw == NULL || 6266 mConfig.outputCfg.buffer.raw == NULL) { 6267 return; 6268 } 6269 6270 if (isProcessEnabled()) { 6271 // do 32 bit to 16 bit conversion for auxiliary effect input buffer 6272 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 6273 ditherAndClamp(mConfig.inputCfg.buffer.s32, 6274 mConfig.inputCfg.buffer.s32, 6275 mConfig.inputCfg.buffer.frameCount/2); 6276 } 6277 6278 // do the actual processing in the effect engine 6279 int ret = (*mEffectInterface)->process(mEffectInterface, 6280 &mConfig.inputCfg.buffer, 6281 &mConfig.outputCfg.buffer); 6282 6283 // force transition to IDLE state when engine is ready 6284 if (mState == STOPPED && ret == -ENODATA) { 6285 mDisableWaitCnt = 1; 6286 } 6287 6288 // clear auxiliary effect input buffer for next accumulation 6289 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 6290 memset(mConfig.inputCfg.buffer.raw, 0, 6291 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t)); 6292 } 6293 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT && 6294 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) { 6295 // If an insert effect is idle and input buffer is different from output buffer, 6296 // accumulate input onto output 6297 sp<EffectChain> chain = mChain.promote(); 6298 if (chain != 0 && chain->activeTrackCnt() != 0) { 6299 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here 6300 int16_t *in = mConfig.inputCfg.buffer.s16; 6301 int16_t *out = mConfig.outputCfg.buffer.s16; 6302 for (size_t i = 0; i < frameCnt; i++) { 6303 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]); 6304 } 6305 } 6306 } 6307} 6308 6309void AudioFlinger::EffectModule::reset_l() 6310{ 6311 if (mEffectInterface == NULL) { 6312 return; 6313 } 6314 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL); 6315} 6316 6317status_t AudioFlinger::EffectModule::configure() 6318{ 6319 uint32_t channels; 6320 if (mEffectInterface == NULL) { 6321 return NO_INIT; 6322 } 6323 6324 sp<ThreadBase> thread = mThread.promote(); 6325 if (thread == 0) { 6326 return DEAD_OBJECT; 6327 } 6328 6329 // TODO: handle configuration of effects replacing track process 6330 if (thread->channelCount() == 1) { 6331 channels = AUDIO_CHANNEL_OUT_MONO; 6332 } else { 6333 channels = AUDIO_CHANNEL_OUT_STEREO; 6334 } 6335 6336 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 6337 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO; 6338 } else { 6339 mConfig.inputCfg.channels = channels; 6340 } 6341 mConfig.outputCfg.channels = channels; 6342 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT; 6343 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT; 6344 mConfig.inputCfg.samplingRate = thread->sampleRate(); 6345 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate; 6346 mConfig.inputCfg.bufferProvider.cookie = NULL; 6347 mConfig.inputCfg.bufferProvider.getBuffer = NULL; 6348 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL; 6349 mConfig.outputCfg.bufferProvider.cookie = NULL; 6350 mConfig.outputCfg.bufferProvider.getBuffer = NULL; 6351 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL; 6352 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ; 6353 // Insert effect: 6354 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE, 6355 // always overwrites output buffer: input buffer == output buffer 6356 // - in other sessions: 6357 // last effect in the chain accumulates in output buffer: input buffer != output buffer 6358 // other effect: overwrites output buffer: input buffer == output buffer 6359 // Auxiliary effect: 6360 // accumulates in output buffer: input buffer != output buffer 6361 // Therefore: accumulate <=> input buffer != output buffer 6362 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) { 6363 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE; 6364 } else { 6365 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE; 6366 } 6367 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL; 6368 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL; 6369 mConfig.inputCfg.buffer.frameCount = thread->frameCount(); 6370 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount; 6371 6372 ALOGV("configure() %p thread %p buffer %p framecount %d", 6373 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount); 6374 6375 status_t cmdStatus; 6376 uint32_t size = sizeof(int); 6377 status_t status = (*mEffectInterface)->command(mEffectInterface, 6378 EFFECT_CMD_SET_CONFIG, 6379 sizeof(effect_config_t), 6380 &mConfig, 6381 &size, 6382 &cmdStatus); 6383 if (status == 0) { 6384 status = cmdStatus; 6385 } 6386 6387 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) / 6388 (1000 * mConfig.outputCfg.buffer.frameCount); 6389 6390 return status; 6391} 6392 6393status_t AudioFlinger::EffectModule::init() 6394{ 6395 Mutex::Autolock _l(mLock); 6396 if (mEffectInterface == NULL) { 6397 return NO_INIT; 6398 } 6399 status_t cmdStatus; 6400 uint32_t size = sizeof(status_t); 6401 status_t status = (*mEffectInterface)->command(mEffectInterface, 6402 EFFECT_CMD_INIT, 6403 0, 6404 NULL, 6405 &size, 6406 &cmdStatus); 6407 if (status == 0) { 6408 status = cmdStatus; 6409 } 6410 return status; 6411} 6412 6413status_t AudioFlinger::EffectModule::start() 6414{ 6415 Mutex::Autolock _l(mLock); 6416 return start_l(); 6417} 6418 6419status_t AudioFlinger::EffectModule::start_l() 6420{ 6421 if (mEffectInterface == NULL) { 6422 return NO_INIT; 6423 } 6424 status_t cmdStatus; 6425 uint32_t size = sizeof(status_t); 6426 status_t status = (*mEffectInterface)->command(mEffectInterface, 6427 EFFECT_CMD_ENABLE, 6428 0, 6429 NULL, 6430 &size, 6431 &cmdStatus); 6432 if (status == 0) { 6433 status = cmdStatus; 6434 } 6435 if (status == 0 && 6436 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC || 6437 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) { 6438 sp<ThreadBase> thread = mThread.promote(); 6439 if (thread != 0) { 6440 audio_stream_t *stream = thread->stream(); 6441 if (stream != NULL) { 6442 stream->add_audio_effect(stream, mEffectInterface); 6443 } 6444 } 6445 } 6446 return status; 6447} 6448 6449status_t AudioFlinger::EffectModule::stop() 6450{ 6451 Mutex::Autolock _l(mLock); 6452 return stop_l(); 6453} 6454 6455status_t AudioFlinger::EffectModule::stop_l() 6456{ 6457 if (mEffectInterface == NULL) { 6458 return NO_INIT; 6459 } 6460 status_t cmdStatus; 6461 uint32_t size = sizeof(status_t); 6462 status_t status = (*mEffectInterface)->command(mEffectInterface, 6463 EFFECT_CMD_DISABLE, 6464 0, 6465 NULL, 6466 &size, 6467 &cmdStatus); 6468 if (status == 0) { 6469 status = cmdStatus; 6470 } 6471 if (status == 0 && 6472 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC || 6473 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) { 6474 sp<ThreadBase> thread = mThread.promote(); 6475 if (thread != 0) { 6476 audio_stream_t *stream = thread->stream(); 6477 if (stream != NULL) { 6478 stream->remove_audio_effect(stream, mEffectInterface); 6479 } 6480 } 6481 } 6482 return status; 6483} 6484 6485status_t AudioFlinger::EffectModule::command(uint32_t cmdCode, 6486 uint32_t cmdSize, 6487 void *pCmdData, 6488 uint32_t *replySize, 6489 void *pReplyData) 6490{ 6491 Mutex::Autolock _l(mLock); 6492// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface); 6493 6494 if (mState == DESTROYED || mEffectInterface == NULL) { 6495 return NO_INIT; 6496 } 6497 status_t status = (*mEffectInterface)->command(mEffectInterface, 6498 cmdCode, 6499 cmdSize, 6500 pCmdData, 6501 replySize, 6502 pReplyData); 6503 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) { 6504 uint32_t size = (replySize == NULL) ? 0 : *replySize; 6505 for (size_t i = 1; i < mHandles.size(); i++) { 6506 sp<EffectHandle> h = mHandles[i].promote(); 6507 if (h != 0) { 6508 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData); 6509 } 6510 } 6511 } 6512 return status; 6513} 6514 6515status_t AudioFlinger::EffectModule::setEnabled(bool enabled) 6516{ 6517 6518 Mutex::Autolock _l(mLock); 6519 ALOGV("setEnabled %p enabled %d", this, enabled); 6520 6521 if (enabled != isEnabled()) { 6522 status_t status = AudioSystem::setEffectEnabled(mId, enabled); 6523 if (enabled && status != NO_ERROR) { 6524 return status; 6525 } 6526 6527 switch (mState) { 6528 // going from disabled to enabled 6529 case IDLE: 6530 mState = STARTING; 6531 break; 6532 case STOPPED: 6533 mState = RESTART; 6534 break; 6535 case STOPPING: 6536 mState = ACTIVE; 6537 break; 6538 6539 // going from enabled to disabled 6540 case RESTART: 6541 mState = STOPPED; 6542 break; 6543 case STARTING: 6544 mState = IDLE; 6545 break; 6546 case ACTIVE: 6547 mState = STOPPING; 6548 break; 6549 case DESTROYED: 6550 return NO_ERROR; // simply ignore as we are being destroyed 6551 } 6552 for (size_t i = 1; i < mHandles.size(); i++) { 6553 sp<EffectHandle> h = mHandles[i].promote(); 6554 if (h != 0) { 6555 h->setEnabled(enabled); 6556 } 6557 } 6558 } 6559 return NO_ERROR; 6560} 6561 6562bool AudioFlinger::EffectModule::isEnabled() const 6563{ 6564 switch (mState) { 6565 case RESTART: 6566 case STARTING: 6567 case ACTIVE: 6568 return true; 6569 case IDLE: 6570 case STOPPING: 6571 case STOPPED: 6572 case DESTROYED: 6573 default: 6574 return false; 6575 } 6576} 6577 6578bool AudioFlinger::EffectModule::isProcessEnabled() const 6579{ 6580 switch (mState) { 6581 case RESTART: 6582 case ACTIVE: 6583 case STOPPING: 6584 case STOPPED: 6585 return true; 6586 case IDLE: 6587 case STARTING: 6588 case DESTROYED: 6589 default: 6590 return false; 6591 } 6592} 6593 6594status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller) 6595{ 6596 Mutex::Autolock _l(mLock); 6597 status_t status = NO_ERROR; 6598 6599 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume 6600 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set) 6601 if (isProcessEnabled() && 6602 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL || 6603 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) { 6604 status_t cmdStatus; 6605 uint32_t volume[2]; 6606 uint32_t *pVolume = NULL; 6607 uint32_t size = sizeof(volume); 6608 volume[0] = *left; 6609 volume[1] = *right; 6610 if (controller) { 6611 pVolume = volume; 6612 } 6613 status = (*mEffectInterface)->command(mEffectInterface, 6614 EFFECT_CMD_SET_VOLUME, 6615 size, 6616 volume, 6617 &size, 6618 pVolume); 6619 if (controller && status == NO_ERROR && size == sizeof(volume)) { 6620 *left = volume[0]; 6621 *right = volume[1]; 6622 } 6623 } 6624 return status; 6625} 6626 6627status_t AudioFlinger::EffectModule::setDevice(uint32_t device) 6628{ 6629 Mutex::Autolock _l(mLock); 6630 status_t status = NO_ERROR; 6631 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) { 6632 // audio pre processing modules on RecordThread can receive both output and 6633 // input device indication in the same call 6634 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL; 6635 if (dev) { 6636 status_t cmdStatus; 6637 uint32_t size = sizeof(status_t); 6638 6639 status = (*mEffectInterface)->command(mEffectInterface, 6640 EFFECT_CMD_SET_DEVICE, 6641 sizeof(uint32_t), 6642 &dev, 6643 &size, 6644 &cmdStatus); 6645 if (status == NO_ERROR) { 6646 status = cmdStatus; 6647 } 6648 } 6649 dev = device & AUDIO_DEVICE_IN_ALL; 6650 if (dev) { 6651 status_t cmdStatus; 6652 uint32_t size = sizeof(status_t); 6653 6654 status_t status2 = (*mEffectInterface)->command(mEffectInterface, 6655 EFFECT_CMD_SET_INPUT_DEVICE, 6656 sizeof(uint32_t), 6657 &dev, 6658 &size, 6659 &cmdStatus); 6660 if (status2 == NO_ERROR) { 6661 status2 = cmdStatus; 6662 } 6663 if (status == NO_ERROR) { 6664 status = status2; 6665 } 6666 } 6667 } 6668 return status; 6669} 6670 6671status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode) 6672{ 6673 Mutex::Autolock _l(mLock); 6674 status_t status = NO_ERROR; 6675 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) { 6676 status_t cmdStatus; 6677 uint32_t size = sizeof(status_t); 6678 status = (*mEffectInterface)->command(mEffectInterface, 6679 EFFECT_CMD_SET_AUDIO_MODE, 6680 sizeof(audio_mode_t), 6681 &mode, 6682 &size, 6683 &cmdStatus); 6684 if (status == NO_ERROR) { 6685 status = cmdStatus; 6686 } 6687 } 6688 return status; 6689} 6690 6691void AudioFlinger::EffectModule::setSuspended(bool suspended) 6692{ 6693 Mutex::Autolock _l(mLock); 6694 mSuspended = suspended; 6695} 6696 6697bool AudioFlinger::EffectModule::suspended() const 6698{ 6699 Mutex::Autolock _l(mLock); 6700 return mSuspended; 6701} 6702 6703status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args) 6704{ 6705 const size_t SIZE = 256; 6706 char buffer[SIZE]; 6707 String8 result; 6708 6709 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId); 6710 result.append(buffer); 6711 6712 bool locked = tryLock(mLock); 6713 // failed to lock - AudioFlinger is probably deadlocked 6714 if (!locked) { 6715 result.append("\t\tCould not lock Fx mutex:\n"); 6716 } 6717 6718 result.append("\t\tSession Status State Engine:\n"); 6719 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n", 6720 mSessionId, mStatus, mState, (uint32_t)mEffectInterface); 6721 result.append(buffer); 6722 6723 result.append("\t\tDescriptor:\n"); 6724 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n", 6725 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion, 6726 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2], 6727 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]); 6728 result.append(buffer); 6729 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n", 6730 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion, 6731 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2], 6732 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]); 6733 result.append(buffer); 6734 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n", 6735 mDescriptor.apiVersion, 6736 mDescriptor.flags); 6737 result.append(buffer); 6738 snprintf(buffer, SIZE, "\t\t- name: %s\n", 6739 mDescriptor.name); 6740 result.append(buffer); 6741 snprintf(buffer, SIZE, "\t\t- implementor: %s\n", 6742 mDescriptor.implementor); 6743 result.append(buffer); 6744 6745 result.append("\t\t- Input configuration:\n"); 6746 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n"); 6747 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n", 6748 (uint32_t)mConfig.inputCfg.buffer.raw, 6749 mConfig.inputCfg.buffer.frameCount, 6750 mConfig.inputCfg.samplingRate, 6751 mConfig.inputCfg.channels, 6752 mConfig.inputCfg.format); 6753 result.append(buffer); 6754 6755 result.append("\t\t- Output configuration:\n"); 6756 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n"); 6757 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n", 6758 (uint32_t)mConfig.outputCfg.buffer.raw, 6759 mConfig.outputCfg.buffer.frameCount, 6760 mConfig.outputCfg.samplingRate, 6761 mConfig.outputCfg.channels, 6762 mConfig.outputCfg.format); 6763 result.append(buffer); 6764 6765 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size()); 6766 result.append(buffer); 6767 result.append("\t\t\tPid Priority Ctrl Locked client server\n"); 6768 for (size_t i = 0; i < mHandles.size(); ++i) { 6769 sp<EffectHandle> handle = mHandles[i].promote(); 6770 if (handle != 0) { 6771 handle->dump(buffer, SIZE); 6772 result.append(buffer); 6773 } 6774 } 6775 6776 result.append("\n"); 6777 6778 write(fd, result.string(), result.length()); 6779 6780 if (locked) { 6781 mLock.unlock(); 6782 } 6783 6784 return NO_ERROR; 6785} 6786 6787// ---------------------------------------------------------------------------- 6788// EffectHandle implementation 6789// ---------------------------------------------------------------------------- 6790 6791#undef LOG_TAG 6792#define LOG_TAG "AudioFlinger::EffectHandle" 6793 6794AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect, 6795 const sp<AudioFlinger::Client>& client, 6796 const sp<IEffectClient>& effectClient, 6797 int32_t priority) 6798 : BnEffect(), 6799 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL), 6800 mPriority(priority), mHasControl(false), mEnabled(false) 6801{ 6802 ALOGV("constructor %p", this); 6803 6804 if (client == 0) { 6805 return; 6806 } 6807 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int); 6808 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset); 6809 if (mCblkMemory != 0) { 6810 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer()); 6811 6812 if (mCblk != NULL) { 6813 new(mCblk) effect_param_cblk_t(); 6814 mBuffer = (uint8_t *)mCblk + bufOffset; 6815 } 6816 } else { 6817 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t)); 6818 return; 6819 } 6820} 6821 6822AudioFlinger::EffectHandle::~EffectHandle() 6823{ 6824 ALOGV("Destructor %p", this); 6825 disconnect(false); 6826 ALOGV("Destructor DONE %p", this); 6827} 6828 6829status_t AudioFlinger::EffectHandle::enable() 6830{ 6831 ALOGV("enable %p", this); 6832 if (!mHasControl) return INVALID_OPERATION; 6833 if (mEffect == 0) return DEAD_OBJECT; 6834 6835 if (mEnabled) { 6836 return NO_ERROR; 6837 } 6838 6839 mEnabled = true; 6840 6841 sp<ThreadBase> thread = mEffect->thread().promote(); 6842 if (thread != 0) { 6843 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId()); 6844 } 6845 6846 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled 6847 if (mEffect->suspended()) { 6848 return NO_ERROR; 6849 } 6850 6851 status_t status = mEffect->setEnabled(true); 6852 if (status != NO_ERROR) { 6853 if (thread != 0) { 6854 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId()); 6855 } 6856 mEnabled = false; 6857 } 6858 return status; 6859} 6860 6861status_t AudioFlinger::EffectHandle::disable() 6862{ 6863 ALOGV("disable %p", this); 6864 if (!mHasControl) return INVALID_OPERATION; 6865 if (mEffect == 0) return DEAD_OBJECT; 6866 6867 if (!mEnabled) { 6868 return NO_ERROR; 6869 } 6870 mEnabled = false; 6871 6872 if (mEffect->suspended()) { 6873 return NO_ERROR; 6874 } 6875 6876 status_t status = mEffect->setEnabled(false); 6877 6878 sp<ThreadBase> thread = mEffect->thread().promote(); 6879 if (thread != 0) { 6880 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId()); 6881 } 6882 6883 return status; 6884} 6885 6886void AudioFlinger::EffectHandle::disconnect() 6887{ 6888 disconnect(true); 6889} 6890 6891void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast) 6892{ 6893 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false"); 6894 if (mEffect == 0) { 6895 return; 6896 } 6897 mEffect->disconnect(this, unpinIfLast); 6898 6899 if (mHasControl && mEnabled) { 6900 sp<ThreadBase> thread = mEffect->thread().promote(); 6901 if (thread != 0) { 6902 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId()); 6903 } 6904 } 6905 6906 // release sp on module => module destructor can be called now 6907 mEffect.clear(); 6908 if (mClient != 0) { 6909 if (mCblk != NULL) { 6910 // unlike ~TrackBase(), mCblk is never a local new, so don't delete 6911 mCblk->~effect_param_cblk_t(); // destroy our shared-structure. 6912 } 6913 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to 6914 // Client destructor must run with AudioFlinger mutex locked 6915 Mutex::Autolock _l(mClient->audioFlinger()->mLock); 6916 mClient.clear(); 6917 } 6918} 6919 6920status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode, 6921 uint32_t cmdSize, 6922 void *pCmdData, 6923 uint32_t *replySize, 6924 void *pReplyData) 6925{ 6926// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p", 6927// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get()); 6928 6929 // only get parameter command is permitted for applications not controlling the effect 6930 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) { 6931 return INVALID_OPERATION; 6932 } 6933 if (mEffect == 0) return DEAD_OBJECT; 6934 if (mClient == 0) return INVALID_OPERATION; 6935 6936 // handle commands that are not forwarded transparently to effect engine 6937 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) { 6938 // No need to trylock() here as this function is executed in the binder thread serving a particular client process: 6939 // no risk to block the whole media server process or mixer threads is we are stuck here 6940 Mutex::Autolock _l(mCblk->lock); 6941 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE || 6942 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) { 6943 mCblk->serverIndex = 0; 6944 mCblk->clientIndex = 0; 6945 return BAD_VALUE; 6946 } 6947 status_t status = NO_ERROR; 6948 while (mCblk->serverIndex < mCblk->clientIndex) { 6949 int reply; 6950 uint32_t rsize = sizeof(int); 6951 int *p = (int *)(mBuffer + mCblk->serverIndex); 6952 int size = *p++; 6953 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) { 6954 ALOGW("command(): invalid parameter block size"); 6955 break; 6956 } 6957 effect_param_t *param = (effect_param_t *)p; 6958 if (param->psize == 0 || param->vsize == 0) { 6959 ALOGW("command(): null parameter or value size"); 6960 mCblk->serverIndex += size; 6961 continue; 6962 } 6963 uint32_t psize = sizeof(effect_param_t) + 6964 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) + 6965 param->vsize; 6966 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM, 6967 psize, 6968 p, 6969 &rsize, 6970 &reply); 6971 // stop at first error encountered 6972 if (ret != NO_ERROR) { 6973 status = ret; 6974 *(int *)pReplyData = reply; 6975 break; 6976 } else if (reply != NO_ERROR) { 6977 *(int *)pReplyData = reply; 6978 break; 6979 } 6980 mCblk->serverIndex += size; 6981 } 6982 mCblk->serverIndex = 0; 6983 mCblk->clientIndex = 0; 6984 return status; 6985 } else if (cmdCode == EFFECT_CMD_ENABLE) { 6986 *(int *)pReplyData = NO_ERROR; 6987 return enable(); 6988 } else if (cmdCode == EFFECT_CMD_DISABLE) { 6989 *(int *)pReplyData = NO_ERROR; 6990 return disable(); 6991 } 6992 6993 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData); 6994} 6995 6996void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled) 6997{ 6998 ALOGV("setControl %p control %d", this, hasControl); 6999 7000 mHasControl = hasControl; 7001 mEnabled = enabled; 7002 7003 if (signal && mEffectClient != 0) { 7004 mEffectClient->controlStatusChanged(hasControl); 7005 } 7006} 7007 7008void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode, 7009 uint32_t cmdSize, 7010 void *pCmdData, 7011 uint32_t replySize, 7012 void *pReplyData) 7013{ 7014 if (mEffectClient != 0) { 7015 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData); 7016 } 7017} 7018 7019 7020 7021void AudioFlinger::EffectHandle::setEnabled(bool enabled) 7022{ 7023 if (mEffectClient != 0) { 7024 mEffectClient->enableStatusChanged(enabled); 7025 } 7026} 7027 7028status_t AudioFlinger::EffectHandle::onTransact( 7029 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 7030{ 7031 return BnEffect::onTransact(code, data, reply, flags); 7032} 7033 7034 7035void AudioFlinger::EffectHandle::dump(char* buffer, size_t size) 7036{ 7037 bool locked = mCblk != NULL && tryLock(mCblk->lock); 7038 7039 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n", 7040 (mClient == 0) ? getpid() : mClient->pid(), 7041 mPriority, 7042 mHasControl, 7043 !locked, 7044 mCblk ? mCblk->clientIndex : 0, 7045 mCblk ? mCblk->serverIndex : 0 7046 ); 7047 7048 if (locked) { 7049 mCblk->lock.unlock(); 7050 } 7051} 7052 7053#undef LOG_TAG 7054#define LOG_TAG "AudioFlinger::EffectChain" 7055 7056AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread, 7057 int sessionId) 7058 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0), 7059 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX), 7060 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX) 7061{ 7062 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); 7063 sp<ThreadBase> thread = mThread.promote(); 7064 if (thread == 0) { 7065 return; 7066 } 7067 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) / 7068 thread->frameCount(); 7069} 7070 7071AudioFlinger::EffectChain::~EffectChain() 7072{ 7073 if (mOwnInBuffer) { 7074 delete mInBuffer; 7075 } 7076 7077} 7078 7079// getEffectFromDesc_l() must be called with ThreadBase::mLock held 7080sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor) 7081{ 7082 size_t size = mEffects.size(); 7083 7084 for (size_t i = 0; i < size; i++) { 7085 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) { 7086 return mEffects[i]; 7087 } 7088 } 7089 return 0; 7090} 7091 7092// getEffectFromId_l() must be called with ThreadBase::mLock held 7093sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id) 7094{ 7095 size_t size = mEffects.size(); 7096 7097 for (size_t i = 0; i < size; i++) { 7098 // by convention, return first effect if id provided is 0 (0 is never a valid id) 7099 if (id == 0 || mEffects[i]->id() == id) { 7100 return mEffects[i]; 7101 } 7102 } 7103 return 0; 7104} 7105 7106// getEffectFromType_l() must be called with ThreadBase::mLock held 7107sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l( 7108 const effect_uuid_t *type) 7109{ 7110 size_t size = mEffects.size(); 7111 7112 for (size_t i = 0; i < size; i++) { 7113 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) { 7114 return mEffects[i]; 7115 } 7116 } 7117 return 0; 7118} 7119 7120// Must be called with EffectChain::mLock locked 7121void AudioFlinger::EffectChain::process_l() 7122{ 7123 sp<ThreadBase> thread = mThread.promote(); 7124 if (thread == 0) { 7125 ALOGW("process_l(): cannot promote mixer thread"); 7126 return; 7127 } 7128 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) || 7129 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE); 7130 // always process effects unless no more tracks are on the session and the effect tail 7131 // has been rendered 7132 bool doProcess = true; 7133 if (!isGlobalSession) { 7134 bool tracksOnSession = (trackCnt() != 0); 7135 7136 if (!tracksOnSession && mTailBufferCount == 0) { 7137 doProcess = false; 7138 } 7139 7140 if (activeTrackCnt() == 0) { 7141 // if no track is active and the effect tail has not been rendered, 7142 // the input buffer must be cleared here as the mixer process will not do it 7143 if (tracksOnSession || mTailBufferCount > 0) { 7144 size_t numSamples = thread->frameCount() * thread->channelCount(); 7145 memset(mInBuffer, 0, numSamples * sizeof(int16_t)); 7146 if (mTailBufferCount > 0) { 7147 mTailBufferCount--; 7148 } 7149 } 7150 } 7151 } 7152 7153 size_t size = mEffects.size(); 7154 if (doProcess) { 7155 for (size_t i = 0; i < size; i++) { 7156 mEffects[i]->process(); 7157 } 7158 } 7159 for (size_t i = 0; i < size; i++) { 7160 mEffects[i]->updateState(); 7161 } 7162} 7163 7164// addEffect_l() must be called with PlaybackThread::mLock held 7165status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect) 7166{ 7167 effect_descriptor_t desc = effect->desc(); 7168 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK; 7169 7170 Mutex::Autolock _l(mLock); 7171 effect->setChain(this); 7172 sp<ThreadBase> thread = mThread.promote(); 7173 if (thread == 0) { 7174 return NO_INIT; 7175 } 7176 effect->setThread(thread); 7177 7178 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 7179 // Auxiliary effects are inserted at the beginning of mEffects vector as 7180 // they are processed first and accumulated in chain input buffer 7181 mEffects.insertAt(effect, 0); 7182 7183 // the input buffer for auxiliary effect contains mono samples in 7184 // 32 bit format. This is to avoid saturation in AudoMixer 7185 // accumulation stage. Saturation is done in EffectModule::process() before 7186 // calling the process in effect engine 7187 size_t numSamples = thread->frameCount(); 7188 int32_t *buffer = new int32_t[numSamples]; 7189 memset(buffer, 0, numSamples * sizeof(int32_t)); 7190 effect->setInBuffer((int16_t *)buffer); 7191 // auxiliary effects output samples to chain input buffer for further processing 7192 // by insert effects 7193 effect->setOutBuffer(mInBuffer); 7194 } else { 7195 // Insert effects are inserted at the end of mEffects vector as they are processed 7196 // after track and auxiliary effects. 7197 // Insert effect order as a function of indicated preference: 7198 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if 7199 // another effect is present 7200 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the 7201 // last effect claiming first position 7202 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the 7203 // first effect claiming last position 7204 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last 7205 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is 7206 // already present 7207 7208 int size = (int)mEffects.size(); 7209 int idx_insert = size; 7210 int idx_insert_first = -1; 7211 int idx_insert_last = -1; 7212 7213 for (int i = 0; i < size; i++) { 7214 effect_descriptor_t d = mEffects[i]->desc(); 7215 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK; 7216 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK; 7217 if (iMode == EFFECT_FLAG_TYPE_INSERT) { 7218 // check invalid effect chaining combinations 7219 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE || 7220 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) { 7221 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name); 7222 return INVALID_OPERATION; 7223 } 7224 // remember position of first insert effect and by default 7225 // select this as insert position for new effect 7226 if (idx_insert == size) { 7227 idx_insert = i; 7228 } 7229 // remember position of last insert effect claiming 7230 // first position 7231 if (iPref == EFFECT_FLAG_INSERT_FIRST) { 7232 idx_insert_first = i; 7233 } 7234 // remember position of first insert effect claiming 7235 // last position 7236 if (iPref == EFFECT_FLAG_INSERT_LAST && 7237 idx_insert_last == -1) { 7238 idx_insert_last = i; 7239 } 7240 } 7241 } 7242 7243 // modify idx_insert from first position if needed 7244 if (insertPref == EFFECT_FLAG_INSERT_LAST) { 7245 if (idx_insert_last != -1) { 7246 idx_insert = idx_insert_last; 7247 } else { 7248 idx_insert = size; 7249 } 7250 } else { 7251 if (idx_insert_first != -1) { 7252 idx_insert = idx_insert_first + 1; 7253 } 7254 } 7255 7256 // always read samples from chain input buffer 7257 effect->setInBuffer(mInBuffer); 7258 7259 // if last effect in the chain, output samples to chain 7260 // output buffer, otherwise to chain input buffer 7261 if (idx_insert == size) { 7262 if (idx_insert != 0) { 7263 mEffects[idx_insert-1]->setOutBuffer(mInBuffer); 7264 mEffects[idx_insert-1]->configure(); 7265 } 7266 effect->setOutBuffer(mOutBuffer); 7267 } else { 7268 effect->setOutBuffer(mInBuffer); 7269 } 7270 mEffects.insertAt(effect, idx_insert); 7271 7272 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert); 7273 } 7274 effect->configure(); 7275 return NO_ERROR; 7276} 7277 7278// removeEffect_l() must be called with PlaybackThread::mLock held 7279size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect) 7280{ 7281 Mutex::Autolock _l(mLock); 7282 int size = (int)mEffects.size(); 7283 int i; 7284 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK; 7285 7286 for (i = 0; i < size; i++) { 7287 if (effect == mEffects[i]) { 7288 // calling stop here will remove pre-processing effect from the audio HAL. 7289 // This is safe as we hold the EffectChain mutex which guarantees that we are not in 7290 // the middle of a read from audio HAL 7291 if (mEffects[i]->state() == EffectModule::ACTIVE || 7292 mEffects[i]->state() == EffectModule::STOPPING) { 7293 mEffects[i]->stop(); 7294 } 7295 if (type == EFFECT_FLAG_TYPE_AUXILIARY) { 7296 delete[] effect->inBuffer(); 7297 } else { 7298 if (i == size - 1 && i != 0) { 7299 mEffects[i - 1]->setOutBuffer(mOutBuffer); 7300 mEffects[i - 1]->configure(); 7301 } 7302 } 7303 mEffects.removeAt(i); 7304 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i); 7305 break; 7306 } 7307 } 7308 7309 return mEffects.size(); 7310} 7311 7312// setDevice_l() must be called with PlaybackThread::mLock held 7313void AudioFlinger::EffectChain::setDevice_l(uint32_t device) 7314{ 7315 size_t size = mEffects.size(); 7316 for (size_t i = 0; i < size; i++) { 7317 mEffects[i]->setDevice(device); 7318 } 7319} 7320 7321// setMode_l() must be called with PlaybackThread::mLock held 7322void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode) 7323{ 7324 size_t size = mEffects.size(); 7325 for (size_t i = 0; i < size; i++) { 7326 mEffects[i]->setMode(mode); 7327 } 7328} 7329 7330// setVolume_l() must be called with PlaybackThread::mLock held 7331bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right) 7332{ 7333 uint32_t newLeft = *left; 7334 uint32_t newRight = *right; 7335 bool hasControl = false; 7336 int ctrlIdx = -1; 7337 size_t size = mEffects.size(); 7338 7339 // first update volume controller 7340 for (size_t i = size; i > 0; i--) { 7341 if (mEffects[i - 1]->isProcessEnabled() && 7342 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) { 7343 ctrlIdx = i - 1; 7344 hasControl = true; 7345 break; 7346 } 7347 } 7348 7349 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) { 7350 if (hasControl) { 7351 *left = mNewLeftVolume; 7352 *right = mNewRightVolume; 7353 } 7354 return hasControl; 7355 } 7356 7357 mVolumeCtrlIdx = ctrlIdx; 7358 mLeftVolume = newLeft; 7359 mRightVolume = newRight; 7360 7361 // second get volume update from volume controller 7362 if (ctrlIdx >= 0) { 7363 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true); 7364 mNewLeftVolume = newLeft; 7365 mNewRightVolume = newRight; 7366 } 7367 // then indicate volume to all other effects in chain. 7368 // Pass altered volume to effects before volume controller 7369 // and requested volume to effects after controller 7370 uint32_t lVol = newLeft; 7371 uint32_t rVol = newRight; 7372 7373 for (size_t i = 0; i < size; i++) { 7374 if ((int)i == ctrlIdx) continue; 7375 // this also works for ctrlIdx == -1 when there is no volume controller 7376 if ((int)i > ctrlIdx) { 7377 lVol = *left; 7378 rVol = *right; 7379 } 7380 mEffects[i]->setVolume(&lVol, &rVol, false); 7381 } 7382 *left = newLeft; 7383 *right = newRight; 7384 7385 return hasControl; 7386} 7387 7388status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args) 7389{ 7390 const size_t SIZE = 256; 7391 char buffer[SIZE]; 7392 String8 result; 7393 7394 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId); 7395 result.append(buffer); 7396 7397 bool locked = tryLock(mLock); 7398 // failed to lock - AudioFlinger is probably deadlocked 7399 if (!locked) { 7400 result.append("\tCould not lock mutex:\n"); 7401 } 7402 7403 result.append("\tNum fx In buffer Out buffer Active tracks:\n"); 7404 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n", 7405 mEffects.size(), 7406 (uint32_t)mInBuffer, 7407 (uint32_t)mOutBuffer, 7408 mActiveTrackCnt); 7409 result.append(buffer); 7410 write(fd, result.string(), result.size()); 7411 7412 for (size_t i = 0; i < mEffects.size(); ++i) { 7413 sp<EffectModule> effect = mEffects[i]; 7414 if (effect != 0) { 7415 effect->dump(fd, args); 7416 } 7417 } 7418 7419 if (locked) { 7420 mLock.unlock(); 7421 } 7422 7423 return NO_ERROR; 7424} 7425 7426// must be called with ThreadBase::mLock held 7427void AudioFlinger::EffectChain::setEffectSuspended_l( 7428 const effect_uuid_t *type, bool suspend) 7429{ 7430 sp<SuspendedEffectDesc> desc; 7431 // use effect type UUID timelow as key as there is no real risk of identical 7432 // timeLow fields among effect type UUIDs. 7433 int index = mSuspendedEffects.indexOfKey(type->timeLow); 7434 if (suspend) { 7435 if (index >= 0) { 7436 desc = mSuspendedEffects.valueAt(index); 7437 } else { 7438 desc = new SuspendedEffectDesc(); 7439 memcpy(&desc->mType, type, sizeof(effect_uuid_t)); 7440 mSuspendedEffects.add(type->timeLow, desc); 7441 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow); 7442 } 7443 if (desc->mRefCount++ == 0) { 7444 sp<EffectModule> effect = getEffectIfEnabled(type); 7445 if (effect != 0) { 7446 desc->mEffect = effect; 7447 effect->setSuspended(true); 7448 effect->setEnabled(false); 7449 } 7450 } 7451 } else { 7452 if (index < 0) { 7453 return; 7454 } 7455 desc = mSuspendedEffects.valueAt(index); 7456 if (desc->mRefCount <= 0) { 7457 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount); 7458 desc->mRefCount = 1; 7459 } 7460 if (--desc->mRefCount == 0) { 7461 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index)); 7462 if (desc->mEffect != 0) { 7463 sp<EffectModule> effect = desc->mEffect.promote(); 7464 if (effect != 0) { 7465 effect->setSuspended(false); 7466 sp<EffectHandle> handle = effect->controlHandle(); 7467 if (handle != 0) { 7468 effect->setEnabled(handle->enabled()); 7469 } 7470 } 7471 desc->mEffect.clear(); 7472 } 7473 mSuspendedEffects.removeItemsAt(index); 7474 } 7475 } 7476} 7477 7478// must be called with ThreadBase::mLock held 7479void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend) 7480{ 7481 sp<SuspendedEffectDesc> desc; 7482 7483 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll); 7484 if (suspend) { 7485 if (index >= 0) { 7486 desc = mSuspendedEffects.valueAt(index); 7487 } else { 7488 desc = new SuspendedEffectDesc(); 7489 mSuspendedEffects.add((int)kKeyForSuspendAll, desc); 7490 ALOGV("setEffectSuspendedAll_l() add entry for 0"); 7491 } 7492 if (desc->mRefCount++ == 0) { 7493 Vector< sp<EffectModule> > effects; 7494 getSuspendEligibleEffects(effects); 7495 for (size_t i = 0; i < effects.size(); i++) { 7496 setEffectSuspended_l(&effects[i]->desc().type, true); 7497 } 7498 } 7499 } else { 7500 if (index < 0) { 7501 return; 7502 } 7503 desc = mSuspendedEffects.valueAt(index); 7504 if (desc->mRefCount <= 0) { 7505 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount); 7506 desc->mRefCount = 1; 7507 } 7508 if (--desc->mRefCount == 0) { 7509 Vector<const effect_uuid_t *> types; 7510 for (size_t i = 0; i < mSuspendedEffects.size(); i++) { 7511 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) { 7512 continue; 7513 } 7514 types.add(&mSuspendedEffects.valueAt(i)->mType); 7515 } 7516 for (size_t i = 0; i < types.size(); i++) { 7517 setEffectSuspended_l(types[i], false); 7518 } 7519 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index)); 7520 mSuspendedEffects.removeItem((int)kKeyForSuspendAll); 7521 } 7522 } 7523} 7524 7525 7526// The volume effect is used for automated tests only 7527#ifndef OPENSL_ES_H_ 7528static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6, 7529 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } }; 7530const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_; 7531#endif //OPENSL_ES_H_ 7532 7533bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc) 7534{ 7535 // auxiliary effects and visualizer are never suspended on output mix 7536 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) && 7537 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) || 7538 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) || 7539 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) { 7540 return false; 7541 } 7542 return true; 7543} 7544 7545void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects) 7546{ 7547 effects.clear(); 7548 for (size_t i = 0; i < mEffects.size(); i++) { 7549 if (isEffectEligibleForSuspend(mEffects[i]->desc())) { 7550 effects.add(mEffects[i]); 7551 } 7552 } 7553} 7554 7555sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled( 7556 const effect_uuid_t *type) 7557{ 7558 sp<EffectModule> effect = getEffectFromType_l(type); 7559 return effect != 0 && effect->isEnabled() ? effect : 0; 7560} 7561 7562void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect, 7563 bool enabled) 7564{ 7565 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow); 7566 if (enabled) { 7567 if (index < 0) { 7568 // if the effect is not suspend check if all effects are suspended 7569 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll); 7570 if (index < 0) { 7571 return; 7572 } 7573 if (!isEffectEligibleForSuspend(effect->desc())) { 7574 return; 7575 } 7576 setEffectSuspended_l(&effect->desc().type, enabled); 7577 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow); 7578 if (index < 0) { 7579 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!"); 7580 return; 7581 } 7582 } 7583 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x", 7584 effect->desc().type.timeLow); 7585 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index); 7586 // if effect is requested to suspended but was not yet enabled, supend it now. 7587 if (desc->mEffect == 0) { 7588 desc->mEffect = effect; 7589 effect->setEnabled(false); 7590 effect->setSuspended(true); 7591 } 7592 } else { 7593 if (index < 0) { 7594 return; 7595 } 7596 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x", 7597 effect->desc().type.timeLow); 7598 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index); 7599 desc->mEffect.clear(); 7600 effect->setSuspended(false); 7601 } 7602} 7603 7604#undef LOG_TAG 7605#define LOG_TAG "AudioFlinger" 7606 7607// ---------------------------------------------------------------------------- 7608 7609status_t AudioFlinger::onTransact( 7610 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 7611{ 7612 return BnAudioFlinger::onTransact(code, data, reply, flags); 7613} 7614 7615}; // namespace android 7616