Threads.cpp revision 24a325d6f8c4bbf9330e6ce0c769d46e04266ffc
1/* 2** 3** Copyright 2012, 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#define ATRACE_TAG ATRACE_TAG_AUDIO 22 23#include "Configuration.h" 24#include <math.h> 25#include <fcntl.h> 26#include <sys/stat.h> 27#include <cutils/properties.h> 28#include <media/AudioParameter.h> 29#include <utils/Log.h> 30#include <utils/Trace.h> 31 32#include <private/media/AudioTrackShared.h> 33#include <hardware/audio.h> 34#include <audio_effects/effect_ns.h> 35#include <audio_effects/effect_aec.h> 36#include <audio_utils/primitives.h> 37 38// NBAIO implementations 39#include <media/nbaio/AudioStreamOutSink.h> 40#include <media/nbaio/MonoPipe.h> 41#include <media/nbaio/MonoPipeReader.h> 42#include <media/nbaio/Pipe.h> 43#include <media/nbaio/PipeReader.h> 44#include <media/nbaio/SourceAudioBufferProvider.h> 45 46#include <powermanager/PowerManager.h> 47 48#include <common_time/cc_helper.h> 49#include <common_time/local_clock.h> 50 51#include "AudioFlinger.h" 52#include "AudioMixer.h" 53#include "FastMixer.h" 54#include "ServiceUtilities.h" 55#include "SchedulingPolicyService.h" 56 57#ifdef ADD_BATTERY_DATA 58#include <media/IMediaPlayerService.h> 59#include <media/IMediaDeathNotifier.h> 60#endif 61 62#ifdef DEBUG_CPU_USAGE 63#include <cpustats/CentralTendencyStatistics.h> 64#include <cpustats/ThreadCpuUsage.h> 65#endif 66 67// ---------------------------------------------------------------------------- 68 69// Note: the following macro is used for extremely verbose logging message. In 70// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to 71// 0; but one side effect of this is to turn all LOGV's as well. Some messages 72// are so verbose that we want to suppress them even when we have ALOG_ASSERT 73// turned on. Do not uncomment the #def below unless you really know what you 74// are doing and want to see all of the extremely verbose messages. 75//#define VERY_VERY_VERBOSE_LOGGING 76#ifdef VERY_VERY_VERBOSE_LOGGING 77#define ALOGVV ALOGV 78#else 79#define ALOGVV(a...) do { } while(0) 80#endif 81 82namespace android { 83 84// retry counts for buffer fill timeout 85// 50 * ~20msecs = 1 second 86static const int8_t kMaxTrackRetries = 50; 87static const int8_t kMaxTrackStartupRetries = 50; 88// allow less retry attempts on direct output thread. 89// direct outputs can be a scarce resource in audio hardware and should 90// be released as quickly as possible. 91static const int8_t kMaxTrackRetriesDirect = 2; 92 93// don't warn about blocked writes or record buffer overflows more often than this 94static const nsecs_t kWarningThrottleNs = seconds(5); 95 96// RecordThread loop sleep time upon application overrun or audio HAL read error 97static const int kRecordThreadSleepUs = 5000; 98 99// maximum time to wait for setParameters to complete 100static const nsecs_t kSetParametersTimeoutNs = seconds(2); 101 102// minimum sleep time for the mixer thread loop when tracks are active but in underrun 103static const uint32_t kMinThreadSleepTimeUs = 5000; 104// maximum divider applied to the active sleep time in the mixer thread loop 105static const uint32_t kMaxThreadSleepTimeShift = 2; 106 107// minimum normal mix buffer size, expressed in milliseconds rather than frames 108static const uint32_t kMinNormalMixBufferSizeMs = 20; 109// maximum normal mix buffer size 110static const uint32_t kMaxNormalMixBufferSizeMs = 24; 111 112// Offloaded output thread standby delay: allows track transition without going to standby 113static const nsecs_t kOffloadStandbyDelayNs = seconds(1); 114 115// Whether to use fast mixer 116static const enum { 117 FastMixer_Never, // never initialize or use: for debugging only 118 FastMixer_Always, // always initialize and use, even if not needed: for debugging only 119 // normal mixer multiplier is 1 120 FastMixer_Static, // initialize if needed, then use all the time if initialized, 121 // multiplier is calculated based on min & max normal mixer buffer size 122 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load, 123 // multiplier is calculated based on min & max normal mixer buffer size 124 // FIXME for FastMixer_Dynamic: 125 // Supporting this option will require fixing HALs that can't handle large writes. 126 // For example, one HAL implementation returns an error from a large write, 127 // and another HAL implementation corrupts memory, possibly in the sample rate converter. 128 // We could either fix the HAL implementations, or provide a wrapper that breaks 129 // up large writes into smaller ones, and the wrapper would need to deal with scheduler. 130} kUseFastMixer = FastMixer_Static; 131 132// Priorities for requestPriority 133static const int kPriorityAudioApp = 2; 134static const int kPriorityFastMixer = 3; 135 136// IAudioFlinger::createTrack() reports back to client the total size of shared memory area 137// for the track. The client then sub-divides this into smaller buffers for its use. 138// Currently the client uses double-buffering by default, but doesn't tell us about that. 139// So for now we just assume that client is double-buffered. 140// FIXME It would be better for client to tell AudioFlinger whether it wants double-buffering or 141// N-buffering, so AudioFlinger could allocate the right amount of memory. 142// See the client's minBufCount and mNotificationFramesAct calculations for details. 143static const int kFastTrackMultiplier = 1; 144 145// ---------------------------------------------------------------------------- 146 147#ifdef ADD_BATTERY_DATA 148// To collect the amplifier usage 149static void addBatteryData(uint32_t params) { 150 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService(); 151 if (service == NULL) { 152 // it already logged 153 return; 154 } 155 156 service->addBatteryData(params); 157} 158#endif 159 160 161// ---------------------------------------------------------------------------- 162// CPU Stats 163// ---------------------------------------------------------------------------- 164 165class CpuStats { 166public: 167 CpuStats(); 168 void sample(const String8 &title); 169#ifdef DEBUG_CPU_USAGE 170private: 171 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns 172 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns 173 174 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles 175 176 int mCpuNum; // thread's current CPU number 177 int mCpukHz; // frequency of thread's current CPU in kHz 178#endif 179}; 180 181CpuStats::CpuStats() 182#ifdef DEBUG_CPU_USAGE 183 : mCpuNum(-1), mCpukHz(-1) 184#endif 185{ 186} 187 188void CpuStats::sample(const String8 &title) { 189#ifdef DEBUG_CPU_USAGE 190 // get current thread's delta CPU time in wall clock ns 191 double wcNs; 192 bool valid = mCpuUsage.sampleAndEnable(wcNs); 193 194 // record sample for wall clock statistics 195 if (valid) { 196 mWcStats.sample(wcNs); 197 } 198 199 // get the current CPU number 200 int cpuNum = sched_getcpu(); 201 202 // get the current CPU frequency in kHz 203 int cpukHz = mCpuUsage.getCpukHz(cpuNum); 204 205 // check if either CPU number or frequency changed 206 if (cpuNum != mCpuNum || cpukHz != mCpukHz) { 207 mCpuNum = cpuNum; 208 mCpukHz = cpukHz; 209 // ignore sample for purposes of cycles 210 valid = false; 211 } 212 213 // if no change in CPU number or frequency, then record sample for cycle statistics 214 if (valid && mCpukHz > 0) { 215 double cycles = wcNs * cpukHz * 0.000001; 216 mHzStats.sample(cycles); 217 } 218 219 unsigned n = mWcStats.n(); 220 // mCpuUsage.elapsed() is expensive, so don't call it every loop 221 if ((n & 127) == 1) { 222 long long elapsed = mCpuUsage.elapsed(); 223 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) { 224 double perLoop = elapsed / (double) n; 225 double perLoop100 = perLoop * 0.01; 226 double perLoop1k = perLoop * 0.001; 227 double mean = mWcStats.mean(); 228 double stddev = mWcStats.stddev(); 229 double minimum = mWcStats.minimum(); 230 double maximum = mWcStats.maximum(); 231 double meanCycles = mHzStats.mean(); 232 double stddevCycles = mHzStats.stddev(); 233 double minCycles = mHzStats.minimum(); 234 double maxCycles = mHzStats.maximum(); 235 mCpuUsage.resetElapsed(); 236 mWcStats.reset(); 237 mHzStats.reset(); 238 ALOGD("CPU usage for %s over past %.1f secs\n" 239 " (%u mixer loops at %.1f mean ms per loop):\n" 240 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n" 241 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n" 242 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f", 243 title.string(), 244 elapsed * .000000001, n, perLoop * .000001, 245 mean * .001, 246 stddev * .001, 247 minimum * .001, 248 maximum * .001, 249 mean / perLoop100, 250 stddev / perLoop100, 251 minimum / perLoop100, 252 maximum / perLoop100, 253 meanCycles / perLoop1k, 254 stddevCycles / perLoop1k, 255 minCycles / perLoop1k, 256 maxCycles / perLoop1k); 257 258 } 259 } 260#endif 261}; 262 263// ---------------------------------------------------------------------------- 264// ThreadBase 265// ---------------------------------------------------------------------------- 266 267AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id, 268 audio_devices_t outDevice, audio_devices_t inDevice, type_t type) 269 : Thread(false /*canCallJava*/), 270 mType(type), 271 mAudioFlinger(audioFlinger), 272 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize 273 // are set by PlaybackThread::readOutputParameters() or RecordThread::readInputParameters() 274 mParamStatus(NO_ERROR), 275 //FIXME: mStandby should be true here. Is this some kind of hack? 276 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice), 277 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id), 278 // mName will be set by concrete (non-virtual) subclass 279 mDeathRecipient(new PMDeathRecipient(this)) 280{ 281} 282 283AudioFlinger::ThreadBase::~ThreadBase() 284{ 285 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns 286 for (size_t i = 0; i < mConfigEvents.size(); i++) { 287 delete mConfigEvents[i]; 288 } 289 mConfigEvents.clear(); 290 291 mParamCond.broadcast(); 292 // do not lock the mutex in destructor 293 releaseWakeLock_l(); 294 if (mPowerManager != 0) { 295 sp<IBinder> binder = mPowerManager->asBinder(); 296 binder->unlinkToDeath(mDeathRecipient); 297 } 298} 299 300status_t AudioFlinger::ThreadBase::readyToRun() 301{ 302 status_t status = initCheck(); 303 if (status == NO_ERROR) { 304 ALOGI("AudioFlinger's thread %p ready to run", this); 305 } else { 306 ALOGE("No working audio driver found."); 307 } 308 return status; 309} 310 311void AudioFlinger::ThreadBase::exit() 312{ 313 ALOGV("ThreadBase::exit"); 314 // do any cleanup required for exit to succeed 315 preExit(); 316 { 317 // This lock prevents the following race in thread (uniprocessor for illustration): 318 // if (!exitPending()) { 319 // // context switch from here to exit() 320 // // exit() calls requestExit(), what exitPending() observes 321 // // exit() calls signal(), which is dropped since no waiters 322 // // context switch back from exit() to here 323 // mWaitWorkCV.wait(...); 324 // // now thread is hung 325 // } 326 AutoMutex lock(mLock); 327 requestExit(); 328 mWaitWorkCV.broadcast(); 329 } 330 // When Thread::requestExitAndWait is made virtual and this method is renamed to 331 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();" 332 requestExitAndWait(); 333} 334 335status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs) 336{ 337 status_t status; 338 339 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string()); 340 Mutex::Autolock _l(mLock); 341 342 mNewParameters.add(keyValuePairs); 343 mWaitWorkCV.signal(); 344 // wait condition with timeout in case the thread loop has exited 345 // before the request could be processed 346 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) { 347 status = mParamStatus; 348 mWaitWorkCV.signal(); 349 } else { 350 status = TIMED_OUT; 351 } 352 return status; 353} 354 355void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param) 356{ 357 Mutex::Autolock _l(mLock); 358 sendIoConfigEvent_l(event, param); 359} 360 361// sendIoConfigEvent_l() must be called with ThreadBase::mLock held 362void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param) 363{ 364 IoConfigEvent *ioEvent = new IoConfigEvent(event, param); 365 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent)); 366 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, 367 param); 368 mWaitWorkCV.signal(); 369} 370 371// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held 372void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio) 373{ 374 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio); 375 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent)); 376 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d", 377 mConfigEvents.size(), pid, tid, prio); 378 mWaitWorkCV.signal(); 379} 380 381void AudioFlinger::ThreadBase::processConfigEvents() 382{ 383 Mutex::Autolock _l(mLock); 384 processConfigEvents_l(); 385} 386 387// post condition: mConfigEvents.isEmpty() 388void AudioFlinger::ThreadBase::processConfigEvents_l() 389{ 390 while (!mConfigEvents.isEmpty()) { 391 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size()); 392 ConfigEvent *event = mConfigEvents[0]; 393 mConfigEvents.removeAt(0); 394 // release mLock before locking AudioFlinger mLock: lock order is always 395 // AudioFlinger then ThreadBase to avoid cross deadlock 396 mLock.unlock(); 397 switch (event->type()) { 398 case CFG_EVENT_PRIO: { 399 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event); 400 // FIXME Need to understand why this has be done asynchronously 401 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio(), 402 true /*asynchronous*/); 403 if (err != 0) { 404 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d", 405 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err); 406 } 407 } break; 408 case CFG_EVENT_IO: { 409 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event); 410 { 411 Mutex::Autolock _l(mAudioFlinger->mLock); 412 audioConfigChanged_l(ioEvent->event(), ioEvent->param()); 413 } 414 } break; 415 default: 416 ALOGE("processConfigEvents() unknown event type %d", event->type()); 417 break; 418 } 419 delete event; 420 mLock.lock(); 421 } 422} 423 424void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args) 425{ 426 const size_t SIZE = 256; 427 char buffer[SIZE]; 428 String8 result; 429 430 bool locked = AudioFlinger::dumpTryLock(mLock); 431 if (!locked) { 432 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this); 433 write(fd, buffer, strlen(buffer)); 434 } 435 436 snprintf(buffer, SIZE, "io handle: %d\n", mId); 437 result.append(buffer); 438 snprintf(buffer, SIZE, "TID: %d\n", getTid()); 439 result.append(buffer); 440 snprintf(buffer, SIZE, "standby: %d\n", mStandby); 441 result.append(buffer); 442 snprintf(buffer, SIZE, "Sample rate: %u\n", mSampleRate); 443 result.append(buffer); 444 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount); 445 result.append(buffer); 446 snprintf(buffer, SIZE, "HAL buffer size: %u bytes\n", mBufferSize); 447 result.append(buffer); 448 snprintf(buffer, SIZE, "Channel Count: %u\n", mChannelCount); 449 result.append(buffer); 450 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask); 451 result.append(buffer); 452 snprintf(buffer, SIZE, "Format: %d\n", mFormat); 453 result.append(buffer); 454 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize); 455 result.append(buffer); 456 457 snprintf(buffer, SIZE, "\nPending setParameters commands: \n"); 458 result.append(buffer); 459 result.append(" Index Command"); 460 for (size_t i = 0; i < mNewParameters.size(); ++i) { 461 snprintf(buffer, SIZE, "\n %02d ", i); 462 result.append(buffer); 463 result.append(mNewParameters[i]); 464 } 465 466 snprintf(buffer, SIZE, "\n\nPending config events: \n"); 467 result.append(buffer); 468 for (size_t i = 0; i < mConfigEvents.size(); i++) { 469 mConfigEvents[i]->dump(buffer, SIZE); 470 result.append(buffer); 471 } 472 result.append("\n"); 473 474 write(fd, result.string(), result.size()); 475 476 if (locked) { 477 mLock.unlock(); 478 } 479} 480 481void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args) 482{ 483 const size_t SIZE = 256; 484 char buffer[SIZE]; 485 String8 result; 486 487 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size()); 488 write(fd, buffer, strlen(buffer)); 489 490 for (size_t i = 0; i < mEffectChains.size(); ++i) { 491 sp<EffectChain> chain = mEffectChains[i]; 492 if (chain != 0) { 493 chain->dump(fd, args); 494 } 495 } 496} 497 498void AudioFlinger::ThreadBase::acquireWakeLock(int uid) 499{ 500 Mutex::Autolock _l(mLock); 501 acquireWakeLock_l(uid); 502} 503 504String16 AudioFlinger::ThreadBase::getWakeLockTag() 505{ 506 switch (mType) { 507 case MIXER: 508 return String16("AudioMix"); 509 case DIRECT: 510 return String16("AudioDirectOut"); 511 case DUPLICATING: 512 return String16("AudioDup"); 513 case RECORD: 514 return String16("AudioIn"); 515 case OFFLOAD: 516 return String16("AudioOffload"); 517 default: 518 ALOG_ASSERT(false); 519 return String16("AudioUnknown"); 520 } 521} 522 523void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid) 524{ 525 getPowerManager_l(); 526 if (mPowerManager != 0) { 527 sp<IBinder> binder = new BBinder(); 528 status_t status; 529 if (uid >= 0) { 530 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK, 531 binder, 532 getWakeLockTag(), 533 String16("media"), 534 uid); 535 } else { 536 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK, 537 binder, 538 getWakeLockTag(), 539 String16("media")); 540 } 541 if (status == NO_ERROR) { 542 mWakeLockToken = binder; 543 } 544 ALOGV("acquireWakeLock_l() %s status %d", mName, status); 545 } 546} 547 548void AudioFlinger::ThreadBase::releaseWakeLock() 549{ 550 Mutex::Autolock _l(mLock); 551 releaseWakeLock_l(); 552} 553 554void AudioFlinger::ThreadBase::releaseWakeLock_l() 555{ 556 if (mWakeLockToken != 0) { 557 ALOGV("releaseWakeLock_l() %s", mName); 558 if (mPowerManager != 0) { 559 mPowerManager->releaseWakeLock(mWakeLockToken, 0); 560 } 561 mWakeLockToken.clear(); 562 } 563} 564 565void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) { 566 Mutex::Autolock _l(mLock); 567 updateWakeLockUids_l(uids); 568} 569 570void AudioFlinger::ThreadBase::getPowerManager_l() { 571 572 if (mPowerManager == 0) { 573 // use checkService() to avoid blocking if power service is not up yet 574 sp<IBinder> binder = 575 defaultServiceManager()->checkService(String16("power")); 576 if (binder == 0) { 577 ALOGW("Thread %s cannot connect to the power manager service", mName); 578 } else { 579 mPowerManager = interface_cast<IPowerManager>(binder); 580 binder->linkToDeath(mDeathRecipient); 581 } 582 } 583} 584 585void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) { 586 587 getPowerManager_l(); 588 if (mWakeLockToken == NULL) { 589 ALOGE("no wake lock to update!"); 590 return; 591 } 592 if (mPowerManager != 0) { 593 sp<IBinder> binder = new BBinder(); 594 status_t status; 595 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array()); 596 ALOGV("acquireWakeLock_l() %s status %d", mName, status); 597 } 598} 599 600void AudioFlinger::ThreadBase::clearPowerManager() 601{ 602 Mutex::Autolock _l(mLock); 603 releaseWakeLock_l(); 604 mPowerManager.clear(); 605} 606 607void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who) 608{ 609 sp<ThreadBase> thread = mThread.promote(); 610 if (thread != 0) { 611 thread->clearPowerManager(); 612 } 613 ALOGW("power manager service died !!!"); 614} 615 616void AudioFlinger::ThreadBase::setEffectSuspended( 617 const effect_uuid_t *type, bool suspend, int sessionId) 618{ 619 Mutex::Autolock _l(mLock); 620 setEffectSuspended_l(type, suspend, sessionId); 621} 622 623void AudioFlinger::ThreadBase::setEffectSuspended_l( 624 const effect_uuid_t *type, bool suspend, int sessionId) 625{ 626 sp<EffectChain> chain = getEffectChain_l(sessionId); 627 if (chain != 0) { 628 if (type != NULL) { 629 chain->setEffectSuspended_l(type, suspend); 630 } else { 631 chain->setEffectSuspendedAll_l(suspend); 632 } 633 } 634 635 updateSuspendedSessions_l(type, suspend, sessionId); 636} 637 638void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain) 639{ 640 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId()); 641 if (index < 0) { 642 return; 643 } 644 645 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects = 646 mSuspendedSessions.valueAt(index); 647 648 for (size_t i = 0; i < sessionEffects.size(); i++) { 649 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i); 650 for (int j = 0; j < desc->mRefCount; j++) { 651 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) { 652 chain->setEffectSuspendedAll_l(true); 653 } else { 654 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x", 655 desc->mType.timeLow); 656 chain->setEffectSuspended_l(&desc->mType, true); 657 } 658 } 659 } 660} 661 662void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type, 663 bool suspend, 664 int sessionId) 665{ 666 ssize_t index = mSuspendedSessions.indexOfKey(sessionId); 667 668 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects; 669 670 if (suspend) { 671 if (index >= 0) { 672 sessionEffects = mSuspendedSessions.valueAt(index); 673 } else { 674 mSuspendedSessions.add(sessionId, sessionEffects); 675 } 676 } else { 677 if (index < 0) { 678 return; 679 } 680 sessionEffects = mSuspendedSessions.valueAt(index); 681 } 682 683 684 int key = EffectChain::kKeyForSuspendAll; 685 if (type != NULL) { 686 key = type->timeLow; 687 } 688 index = sessionEffects.indexOfKey(key); 689 690 sp<SuspendedSessionDesc> desc; 691 if (suspend) { 692 if (index >= 0) { 693 desc = sessionEffects.valueAt(index); 694 } else { 695 desc = new SuspendedSessionDesc(); 696 if (type != NULL) { 697 desc->mType = *type; 698 } 699 sessionEffects.add(key, desc); 700 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key); 701 } 702 desc->mRefCount++; 703 } else { 704 if (index < 0) { 705 return; 706 } 707 desc = sessionEffects.valueAt(index); 708 if (--desc->mRefCount == 0) { 709 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key); 710 sessionEffects.removeItemsAt(index); 711 if (sessionEffects.isEmpty()) { 712 ALOGV("updateSuspendedSessions_l() restore removing session %d", 713 sessionId); 714 mSuspendedSessions.removeItem(sessionId); 715 } 716 } 717 } 718 if (!sessionEffects.isEmpty()) { 719 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects); 720 } 721} 722 723void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect, 724 bool enabled, 725 int sessionId) 726{ 727 Mutex::Autolock _l(mLock); 728 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId); 729} 730 731void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect, 732 bool enabled, 733 int sessionId) 734{ 735 if (mType != RECORD) { 736 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on 737 // another session. This gives the priority to well behaved effect control panels 738 // and applications not using global effects. 739 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect 740 // global effects 741 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) { 742 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX); 743 } 744 } 745 746 sp<EffectChain> chain = getEffectChain_l(sessionId); 747 if (chain != 0) { 748 chain->checkSuspendOnEffectEnabled(effect, enabled); 749 } 750} 751 752// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held 753sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l( 754 const sp<AudioFlinger::Client>& client, 755 const sp<IEffectClient>& effectClient, 756 int32_t priority, 757 int sessionId, 758 effect_descriptor_t *desc, 759 int *enabled, 760 status_t *status) 761{ 762 sp<EffectModule> effect; 763 sp<EffectHandle> handle; 764 status_t lStatus; 765 sp<EffectChain> chain; 766 bool chainCreated = false; 767 bool effectCreated = false; 768 bool effectRegistered = false; 769 770 lStatus = initCheck(); 771 if (lStatus != NO_ERROR) { 772 ALOGW("createEffect_l() Audio driver not initialized."); 773 goto Exit; 774 } 775 776 // Allow global effects only on offloaded and mixer threads 777 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) { 778 switch (mType) { 779 case MIXER: 780 case OFFLOAD: 781 break; 782 case DIRECT: 783 case DUPLICATING: 784 case RECORD: 785 default: 786 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName); 787 lStatus = BAD_VALUE; 788 goto Exit; 789 } 790 } 791 792 // Only Pre processor effects are allowed on input threads and only on input threads 793 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) { 794 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d", 795 desc->name, desc->flags, mType); 796 lStatus = BAD_VALUE; 797 goto Exit; 798 } 799 800 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId); 801 802 { // scope for mLock 803 Mutex::Autolock _l(mLock); 804 805 // check for existing effect chain with the requested audio session 806 chain = getEffectChain_l(sessionId); 807 if (chain == 0) { 808 // create a new chain for this session 809 ALOGV("createEffect_l() new effect chain for session %d", sessionId); 810 chain = new EffectChain(this, sessionId); 811 addEffectChain_l(chain); 812 chain->setStrategy(getStrategyForSession_l(sessionId)); 813 chainCreated = true; 814 } else { 815 effect = chain->getEffectFromDesc_l(desc); 816 } 817 818 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get()); 819 820 if (effect == 0) { 821 int id = mAudioFlinger->nextUniqueId(); 822 // Check CPU and memory usage 823 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id); 824 if (lStatus != NO_ERROR) { 825 goto Exit; 826 } 827 effectRegistered = true; 828 // create a new effect module if none present in the chain 829 effect = new EffectModule(this, chain, desc, id, sessionId); 830 lStatus = effect->status(); 831 if (lStatus != NO_ERROR) { 832 goto Exit; 833 } 834 effect->setOffloaded(mType == OFFLOAD, mId); 835 836 lStatus = chain->addEffect_l(effect); 837 if (lStatus != NO_ERROR) { 838 goto Exit; 839 } 840 effectCreated = true; 841 842 effect->setDevice(mOutDevice); 843 effect->setDevice(mInDevice); 844 effect->setMode(mAudioFlinger->getMode()); 845 effect->setAudioSource(mAudioSource); 846 } 847 // create effect handle and connect it to effect module 848 handle = new EffectHandle(effect, client, effectClient, priority); 849 lStatus = handle->initCheck(); 850 if (lStatus == OK) { 851 lStatus = effect->addHandle(handle.get()); 852 } 853 if (enabled != NULL) { 854 *enabled = (int)effect->isEnabled(); 855 } 856 } 857 858Exit: 859 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) { 860 Mutex::Autolock _l(mLock); 861 if (effectCreated) { 862 chain->removeEffect_l(effect); 863 } 864 if (effectRegistered) { 865 AudioSystem::unregisterEffect(effect->id()); 866 } 867 if (chainCreated) { 868 removeEffectChain_l(chain); 869 } 870 handle.clear(); 871 } 872 873 *status = lStatus; 874 return handle; 875} 876 877sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId) 878{ 879 Mutex::Autolock _l(mLock); 880 return getEffect_l(sessionId, effectId); 881} 882 883sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId) 884{ 885 sp<EffectChain> chain = getEffectChain_l(sessionId); 886 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0; 887} 888 889// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and 890// PlaybackThread::mLock held 891status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect) 892{ 893 // check for existing effect chain with the requested audio session 894 int sessionId = effect->sessionId(); 895 sp<EffectChain> chain = getEffectChain_l(sessionId); 896 bool chainCreated = false; 897 898 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(), 899 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x", 900 this, effect->desc().name, effect->desc().flags); 901 902 if (chain == 0) { 903 // create a new chain for this session 904 ALOGV("addEffect_l() new effect chain for session %d", sessionId); 905 chain = new EffectChain(this, sessionId); 906 addEffectChain_l(chain); 907 chain->setStrategy(getStrategyForSession_l(sessionId)); 908 chainCreated = true; 909 } 910 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get()); 911 912 if (chain->getEffectFromId_l(effect->id()) != 0) { 913 ALOGW("addEffect_l() %p effect %s already present in chain %p", 914 this, effect->desc().name, chain.get()); 915 return BAD_VALUE; 916 } 917 918 effect->setOffloaded(mType == OFFLOAD, mId); 919 920 status_t status = chain->addEffect_l(effect); 921 if (status != NO_ERROR) { 922 if (chainCreated) { 923 removeEffectChain_l(chain); 924 } 925 return status; 926 } 927 928 effect->setDevice(mOutDevice); 929 effect->setDevice(mInDevice); 930 effect->setMode(mAudioFlinger->getMode()); 931 effect->setAudioSource(mAudioSource); 932 return NO_ERROR; 933} 934 935void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) { 936 937 ALOGV("removeEffect_l() %p effect %p", this, effect.get()); 938 effect_descriptor_t desc = effect->desc(); 939 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 940 detachAuxEffect_l(effect->id()); 941 } 942 943 sp<EffectChain> chain = effect->chain().promote(); 944 if (chain != 0) { 945 // remove effect chain if removing last effect 946 if (chain->removeEffect_l(effect) == 0) { 947 removeEffectChain_l(chain); 948 } 949 } else { 950 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get()); 951 } 952} 953 954void AudioFlinger::ThreadBase::lockEffectChains_l( 955 Vector< sp<AudioFlinger::EffectChain> >& effectChains) 956{ 957 effectChains = mEffectChains; 958 for (size_t i = 0; i < mEffectChains.size(); i++) { 959 mEffectChains[i]->lock(); 960 } 961} 962 963void AudioFlinger::ThreadBase::unlockEffectChains( 964 const Vector< sp<AudioFlinger::EffectChain> >& effectChains) 965{ 966 for (size_t i = 0; i < effectChains.size(); i++) { 967 effectChains[i]->unlock(); 968 } 969} 970 971sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId) 972{ 973 Mutex::Autolock _l(mLock); 974 return getEffectChain_l(sessionId); 975} 976 977sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const 978{ 979 size_t size = mEffectChains.size(); 980 for (size_t i = 0; i < size; i++) { 981 if (mEffectChains[i]->sessionId() == sessionId) { 982 return mEffectChains[i]; 983 } 984 } 985 return 0; 986} 987 988void AudioFlinger::ThreadBase::setMode(audio_mode_t mode) 989{ 990 Mutex::Autolock _l(mLock); 991 size_t size = mEffectChains.size(); 992 for (size_t i = 0; i < size; i++) { 993 mEffectChains[i]->setMode_l(mode); 994 } 995} 996 997void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect, 998 EffectHandle *handle, 999 bool unpinIfLast) { 1000 1001 Mutex::Autolock _l(mLock); 1002 ALOGV("disconnectEffect() %p effect %p", this, effect.get()); 1003 // delete the effect module if removing last handle on it 1004 if (effect->removeHandle(handle) == 0) { 1005 if (!effect->isPinned() || unpinIfLast) { 1006 removeEffect_l(effect); 1007 AudioSystem::unregisterEffect(effect->id()); 1008 } 1009 } 1010} 1011 1012// ---------------------------------------------------------------------------- 1013// Playback 1014// ---------------------------------------------------------------------------- 1015 1016AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, 1017 AudioStreamOut* output, 1018 audio_io_handle_t id, 1019 audio_devices_t device, 1020 type_t type) 1021 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type), 1022 mNormalFrameCount(0), mMixBuffer(NULL), 1023 mSuspended(0), mBytesWritten(0), 1024 mActiveTracksGeneration(0), 1025 // mStreamTypes[] initialized in constructor body 1026 mOutput(output), 1027 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false), 1028 mMixerStatus(MIXER_IDLE), 1029 mMixerStatusIgnoringFastTracks(MIXER_IDLE), 1030 standbyDelay(AudioFlinger::mStandbyTimeInNsecs), 1031 mBytesRemaining(0), 1032 mCurrentWriteLength(0), 1033 mUseAsyncWrite(false), 1034 mWriteAckSequence(0), 1035 mDrainSequence(0), 1036 mSignalPending(false), 1037 mScreenState(AudioFlinger::mScreenState), 1038 // index 0 is reserved for normal mixer's submix 1039 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1), 1040 // mLatchD, mLatchQ, 1041 mLatchDValid(false), mLatchQValid(false) 1042{ 1043 snprintf(mName, kNameLength, "AudioOut_%X", id); 1044 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName); 1045 1046 // Assumes constructor is called by AudioFlinger with it's mLock held, but 1047 // it would be safer to explicitly pass initial masterVolume/masterMute as 1048 // parameter. 1049 // 1050 // If the HAL we are using has support for master volume or master mute, 1051 // then do not attenuate or mute during mixing (just leave the volume at 1.0 1052 // and the mute set to false). 1053 mMasterVolume = audioFlinger->masterVolume_l(); 1054 mMasterMute = audioFlinger->masterMute_l(); 1055 if (mOutput && mOutput->audioHwDev) { 1056 if (mOutput->audioHwDev->canSetMasterVolume()) { 1057 mMasterVolume = 1.0; 1058 } 1059 1060 if (mOutput->audioHwDev->canSetMasterMute()) { 1061 mMasterMute = false; 1062 } 1063 } 1064 1065 readOutputParameters(); 1066 1067 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor 1068 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile 1069 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT; 1070 stream = (audio_stream_type_t) (stream + 1)) { 1071 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream); 1072 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream); 1073 } 1074 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here, 1075 // because mAudioFlinger doesn't have one to copy from 1076} 1077 1078AudioFlinger::PlaybackThread::~PlaybackThread() 1079{ 1080 mAudioFlinger->unregisterWriter(mNBLogWriter); 1081 delete[] mMixBuffer; 1082} 1083 1084void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args) 1085{ 1086 dumpInternals(fd, args); 1087 dumpTracks(fd, args); 1088 dumpEffectChains(fd, args); 1089} 1090 1091void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args) 1092{ 1093 const size_t SIZE = 256; 1094 char buffer[SIZE]; 1095 String8 result; 1096 1097 result.appendFormat("Output thread %p stream volumes in dB:\n ", this); 1098 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) { 1099 const stream_type_t *st = &mStreamTypes[i]; 1100 if (i > 0) { 1101 result.appendFormat(", "); 1102 } 1103 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume)); 1104 if (st->mute) { 1105 result.append("M"); 1106 } 1107 } 1108 result.append("\n"); 1109 write(fd, result.string(), result.length()); 1110 result.clear(); 1111 1112 snprintf(buffer, SIZE, "Output thread %p tracks\n", this); 1113 result.append(buffer); 1114 Track::appendDumpHeader(result); 1115 for (size_t i = 0; i < mTracks.size(); ++i) { 1116 sp<Track> track = mTracks[i]; 1117 if (track != 0) { 1118 track->dump(buffer, SIZE); 1119 result.append(buffer); 1120 } 1121 } 1122 1123 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this); 1124 result.append(buffer); 1125 Track::appendDumpHeader(result); 1126 for (size_t i = 0; i < mActiveTracks.size(); ++i) { 1127 sp<Track> track = mActiveTracks[i].promote(); 1128 if (track != 0) { 1129 track->dump(buffer, SIZE); 1130 result.append(buffer); 1131 } 1132 } 1133 write(fd, result.string(), result.size()); 1134 1135 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way. 1136 FastTrackUnderruns underruns = getFastTrackUnderruns(0); 1137 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n", 1138 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty); 1139} 1140 1141void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args) 1142{ 1143 const size_t SIZE = 256; 1144 char buffer[SIZE]; 1145 String8 result; 1146 1147 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this); 1148 result.append(buffer); 1149 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount); 1150 result.append(buffer); 1151 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", 1152 ns2ms(systemTime() - mLastWriteTime)); 1153 result.append(buffer); 1154 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites); 1155 result.append(buffer); 1156 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites); 1157 result.append(buffer); 1158 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite); 1159 result.append(buffer); 1160 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended); 1161 result.append(buffer); 1162 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer); 1163 result.append(buffer); 1164 write(fd, result.string(), result.size()); 1165 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask); 1166 1167 dumpBase(fd, args); 1168} 1169 1170// Thread virtuals 1171 1172void AudioFlinger::PlaybackThread::onFirstRef() 1173{ 1174 run(mName, ANDROID_PRIORITY_URGENT_AUDIO); 1175} 1176 1177// ThreadBase virtuals 1178void AudioFlinger::PlaybackThread::preExit() 1179{ 1180 ALOGV(" preExit()"); 1181 // FIXME this is using hard-coded strings but in the future, this functionality will be 1182 // converted to use audio HAL extensions required to support tunneling 1183 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1"); 1184} 1185 1186// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held 1187sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l( 1188 const sp<AudioFlinger::Client>& client, 1189 audio_stream_type_t streamType, 1190 uint32_t sampleRate, 1191 audio_format_t format, 1192 audio_channel_mask_t channelMask, 1193 size_t frameCount, 1194 const sp<IMemory>& sharedBuffer, 1195 int sessionId, 1196 IAudioFlinger::track_flags_t *flags, 1197 pid_t tid, 1198 int uid, 1199 status_t *status) 1200{ 1201 sp<Track> track; 1202 status_t lStatus; 1203 1204 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0; 1205 1206 // client expresses a preference for FAST, but we get the final say 1207 if (*flags & IAudioFlinger::TRACK_FAST) { 1208 if ( 1209 // not timed 1210 (!isTimed) && 1211 // either of these use cases: 1212 ( 1213 // use case 1: shared buffer with any frame count 1214 ( 1215 (sharedBuffer != 0) 1216 ) || 1217 // use case 2: callback handler and frame count is default or at least as large as HAL 1218 ( 1219 (tid != -1) && 1220 ((frameCount == 0) || 1221 (frameCount >= (mFrameCount * kFastTrackMultiplier))) 1222 ) 1223 ) && 1224 // PCM data 1225 audio_is_linear_pcm(format) && 1226 // mono or stereo 1227 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) || 1228 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) && 1229#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE 1230 // hardware sample rate 1231 (sampleRate == mSampleRate) && 1232#endif 1233 // normal mixer has an associated fast mixer 1234 hasFastMixer() && 1235 // there are sufficient fast track slots available 1236 (mFastTrackAvailMask != 0) 1237 // FIXME test that MixerThread for this fast track has a capable output HAL 1238 // FIXME add a permission test also? 1239 ) { 1240 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count 1241 if (frameCount == 0) { 1242 frameCount = mFrameCount * kFastTrackMultiplier; 1243 } 1244 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d", 1245 frameCount, mFrameCount); 1246 } else { 1247 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d " 1248 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u " 1249 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x", 1250 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, 1251 audio_is_linear_pcm(format), 1252 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask); 1253 *flags &= ~IAudioFlinger::TRACK_FAST; 1254 // For compatibility with AudioTrack calculation, buffer depth is forced 1255 // to be at least 2 x the normal mixer frame count and cover audio hardware latency. 1256 // This is probably too conservative, but legacy application code may depend on it. 1257 // If you change this calculation, also review the start threshold which is related. 1258 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream); 1259 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate); 1260 if (minBufCount < 2) { 1261 minBufCount = 2; 1262 } 1263 size_t minFrameCount = mNormalFrameCount * minBufCount; 1264 if (frameCount < minFrameCount) { 1265 frameCount = minFrameCount; 1266 } 1267 } 1268 } 1269 1270 if (mType == DIRECT) { 1271 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) { 1272 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) { 1273 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x " 1274 "for output %p with format %d", 1275 sampleRate, format, channelMask, mOutput, mFormat); 1276 lStatus = BAD_VALUE; 1277 goto Exit; 1278 } 1279 } 1280 } else if (mType == OFFLOAD) { 1281 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) { 1282 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \"" 1283 "for output %p with format %d", 1284 sampleRate, format, channelMask, mOutput, mFormat); 1285 lStatus = BAD_VALUE; 1286 goto Exit; 1287 } 1288 } else { 1289 if ((format & AUDIO_FORMAT_MAIN_MASK) != AUDIO_FORMAT_PCM) { 1290 ALOGE("createTrack_l() Bad parameter: format %d \"" 1291 "for output %p with format %d", 1292 format, mOutput, mFormat); 1293 lStatus = BAD_VALUE; 1294 goto Exit; 1295 } 1296 // Resampler implementation limits input sampling rate to 2 x output sampling rate. 1297 if (sampleRate > mSampleRate*2) { 1298 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate); 1299 lStatus = BAD_VALUE; 1300 goto Exit; 1301 } 1302 } 1303 1304 lStatus = initCheck(); 1305 if (lStatus != NO_ERROR) { 1306 ALOGE("Audio driver not initialized."); 1307 goto Exit; 1308 } 1309 1310 { // scope for mLock 1311 Mutex::Autolock _l(mLock); 1312 1313 // all tracks in same audio session must share the same routing strategy otherwise 1314 // conflicts will happen when tracks are moved from one output to another by audio policy 1315 // manager 1316 uint32_t strategy = AudioSystem::getStrategyForStream(streamType); 1317 for (size_t i = 0; i < mTracks.size(); ++i) { 1318 sp<Track> t = mTracks[i]; 1319 if (t != 0 && !t->isOutputTrack()) { 1320 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType()); 1321 if (sessionId == t->sessionId() && strategy != actual) { 1322 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u", 1323 strategy, actual); 1324 lStatus = BAD_VALUE; 1325 goto Exit; 1326 } 1327 } 1328 } 1329 1330 if (!isTimed) { 1331 track = new Track(this, client, streamType, sampleRate, format, 1332 channelMask, frameCount, sharedBuffer, sessionId, uid, *flags); 1333 } else { 1334 track = TimedTrack::create(this, client, streamType, sampleRate, format, 1335 channelMask, frameCount, sharedBuffer, sessionId, uid); 1336 } 1337 1338 // new Track always returns non-NULL, 1339 // but TimedTrack::create() is a factory that could fail by returning NULL 1340 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY; 1341 if (lStatus != NO_ERROR) { 1342 track.clear(); 1343 goto Exit; 1344 } 1345 1346 mTracks.add(track); 1347 1348 sp<EffectChain> chain = getEffectChain_l(sessionId); 1349 if (chain != 0) { 1350 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer()); 1351 track->setMainBuffer(chain->inBuffer()); 1352 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType())); 1353 chain->incTrackCnt(); 1354 } 1355 1356 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) { 1357 pid_t callingPid = IPCThreadState::self()->getCallingPid(); 1358 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful, 1359 // so ask activity manager to do this on our behalf 1360 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp); 1361 } 1362 } 1363 1364 lStatus = NO_ERROR; 1365 1366Exit: 1367 *status = lStatus; 1368 return track; 1369} 1370 1371uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const 1372{ 1373 return latency; 1374} 1375 1376uint32_t AudioFlinger::PlaybackThread::latency() const 1377{ 1378 Mutex::Autolock _l(mLock); 1379 return latency_l(); 1380} 1381uint32_t AudioFlinger::PlaybackThread::latency_l() const 1382{ 1383 if (initCheck() == NO_ERROR) { 1384 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream)); 1385 } else { 1386 return 0; 1387 } 1388} 1389 1390void AudioFlinger::PlaybackThread::setMasterVolume(float value) 1391{ 1392 Mutex::Autolock _l(mLock); 1393 // Don't apply master volume in SW if our HAL can do it for us. 1394 if (mOutput && mOutput->audioHwDev && 1395 mOutput->audioHwDev->canSetMasterVolume()) { 1396 mMasterVolume = 1.0; 1397 } else { 1398 mMasterVolume = value; 1399 } 1400} 1401 1402void AudioFlinger::PlaybackThread::setMasterMute(bool muted) 1403{ 1404 Mutex::Autolock _l(mLock); 1405 // Don't apply master mute in SW if our HAL can do it for us. 1406 if (mOutput && mOutput->audioHwDev && 1407 mOutput->audioHwDev->canSetMasterMute()) { 1408 mMasterMute = false; 1409 } else { 1410 mMasterMute = muted; 1411 } 1412} 1413 1414void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value) 1415{ 1416 Mutex::Autolock _l(mLock); 1417 mStreamTypes[stream].volume = value; 1418 broadcast_l(); 1419} 1420 1421void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted) 1422{ 1423 Mutex::Autolock _l(mLock); 1424 mStreamTypes[stream].mute = muted; 1425 broadcast_l(); 1426} 1427 1428float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const 1429{ 1430 Mutex::Autolock _l(mLock); 1431 return mStreamTypes[stream].volume; 1432} 1433 1434// addTrack_l() must be called with ThreadBase::mLock held 1435status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track) 1436{ 1437 status_t status = ALREADY_EXISTS; 1438 1439 // set retry count for buffer fill 1440 track->mRetryCount = kMaxTrackStartupRetries; 1441 if (mActiveTracks.indexOf(track) < 0) { 1442 // the track is newly added, make sure it fills up all its 1443 // buffers before playing. This is to ensure the client will 1444 // effectively get the latency it requested. 1445 if (!track->isOutputTrack()) { 1446 TrackBase::track_state state = track->mState; 1447 mLock.unlock(); 1448 status = AudioSystem::startOutput(mId, track->streamType(), track->sessionId()); 1449 mLock.lock(); 1450 // abort track was stopped/paused while we released the lock 1451 if (state != track->mState) { 1452 if (status == NO_ERROR) { 1453 mLock.unlock(); 1454 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId()); 1455 mLock.lock(); 1456 } 1457 return INVALID_OPERATION; 1458 } 1459 // abort if start is rejected by audio policy manager 1460 if (status != NO_ERROR) { 1461 return PERMISSION_DENIED; 1462 } 1463#ifdef ADD_BATTERY_DATA 1464 // to track the speaker usage 1465 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart); 1466#endif 1467 } 1468 1469 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING; 1470 track->mResetDone = false; 1471 track->mPresentationCompleteFrames = 0; 1472 mActiveTracks.add(track); 1473 mWakeLockUids.add(track->uid()); 1474 mActiveTracksGeneration++; 1475 mLatestActiveTrack = track; 1476 sp<EffectChain> chain = getEffectChain_l(track->sessionId()); 1477 if (chain != 0) { 1478 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), 1479 track->sessionId()); 1480 chain->incActiveTrackCnt(); 1481 } 1482 1483 status = NO_ERROR; 1484 } 1485 1486 ALOGV("signal playback thread"); 1487 broadcast_l(); 1488 1489 return status; 1490} 1491 1492bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track) 1493{ 1494 track->terminate(); 1495 // active tracks are removed by threadLoop() 1496 bool trackActive = (mActiveTracks.indexOf(track) >= 0); 1497 track->mState = TrackBase::STOPPED; 1498 if (!trackActive) { 1499 removeTrack_l(track); 1500 } else if (track->isFastTrack() || track->isOffloaded()) { 1501 track->mState = TrackBase::STOPPING_1; 1502 } 1503 1504 return trackActive; 1505} 1506 1507void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track) 1508{ 1509 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE); 1510 mTracks.remove(track); 1511 deleteTrackName_l(track->name()); 1512 // redundant as track is about to be destroyed, for dumpsys only 1513 track->mName = -1; 1514 if (track->isFastTrack()) { 1515 int index = track->mFastIndex; 1516 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks); 1517 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index))); 1518 mFastTrackAvailMask |= 1 << index; 1519 // redundant as track is about to be destroyed, for dumpsys only 1520 track->mFastIndex = -1; 1521 } 1522 sp<EffectChain> chain = getEffectChain_l(track->sessionId()); 1523 if (chain != 0) { 1524 chain->decTrackCnt(); 1525 } 1526} 1527 1528void AudioFlinger::PlaybackThread::broadcast_l() 1529{ 1530 // Thread could be blocked waiting for async 1531 // so signal it to handle state changes immediately 1532 // If threadLoop is currently unlocked a signal of mWaitWorkCV will 1533 // be lost so we also flag to prevent it blocking on mWaitWorkCV 1534 mSignalPending = true; 1535 mWaitWorkCV.broadcast(); 1536} 1537 1538String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys) 1539{ 1540 Mutex::Autolock _l(mLock); 1541 if (initCheck() != NO_ERROR) { 1542 return String8(); 1543 } 1544 1545 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string()); 1546 const String8 out_s8(s); 1547 free(s); 1548 return out_s8; 1549} 1550 1551// audioConfigChanged_l() must be called with AudioFlinger::mLock held 1552void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) { 1553 AudioSystem::OutputDescriptor desc; 1554 void *param2 = NULL; 1555 1556 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, 1557 param); 1558 1559 switch (event) { 1560 case AudioSystem::OUTPUT_OPENED: 1561 case AudioSystem::OUTPUT_CONFIG_CHANGED: 1562 desc.channelMask = mChannelMask; 1563 desc.samplingRate = mSampleRate; 1564 desc.format = mFormat; 1565 desc.frameCount = mNormalFrameCount; // FIXME see 1566 // AudioFlinger::frameCount(audio_io_handle_t) 1567 desc.latency = latency(); 1568 param2 = &desc; 1569 break; 1570 1571 case AudioSystem::STREAM_CONFIG_CHANGED: 1572 param2 = ¶m; 1573 case AudioSystem::OUTPUT_CLOSED: 1574 default: 1575 break; 1576 } 1577 mAudioFlinger->audioConfigChanged_l(event, mId, param2); 1578} 1579 1580void AudioFlinger::PlaybackThread::writeCallback() 1581{ 1582 ALOG_ASSERT(mCallbackThread != 0); 1583 mCallbackThread->resetWriteBlocked(); 1584} 1585 1586void AudioFlinger::PlaybackThread::drainCallback() 1587{ 1588 ALOG_ASSERT(mCallbackThread != 0); 1589 mCallbackThread->resetDraining(); 1590} 1591 1592void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence) 1593{ 1594 Mutex::Autolock _l(mLock); 1595 // reject out of sequence requests 1596 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) { 1597 mWriteAckSequence &= ~1; 1598 mWaitWorkCV.signal(); 1599 } 1600} 1601 1602void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence) 1603{ 1604 Mutex::Autolock _l(mLock); 1605 // reject out of sequence requests 1606 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) { 1607 mDrainSequence &= ~1; 1608 mWaitWorkCV.signal(); 1609 } 1610} 1611 1612// static 1613int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event, 1614 void *param, 1615 void *cookie) 1616{ 1617 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie; 1618 ALOGV("asyncCallback() event %d", event); 1619 switch (event) { 1620 case STREAM_CBK_EVENT_WRITE_READY: 1621 me->writeCallback(); 1622 break; 1623 case STREAM_CBK_EVENT_DRAIN_READY: 1624 me->drainCallback(); 1625 break; 1626 default: 1627 ALOGW("asyncCallback() unknown event %d", event); 1628 break; 1629 } 1630 return 0; 1631} 1632 1633void AudioFlinger::PlaybackThread::readOutputParameters() 1634{ 1635 // unfortunately we have no way of recovering from errors here, hence the LOG_FATAL 1636 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common); 1637 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common); 1638 if (!audio_is_output_channel(mChannelMask)) { 1639 LOG_FATAL("HAL channel mask %#x not valid for output", mChannelMask); 1640 } 1641 if ((mType == MIXER || mType == DUPLICATING) && mChannelMask != AUDIO_CHANNEL_OUT_STEREO) { 1642 LOG_FATAL("HAL channel mask %#x not supported for mixed output; " 1643 "must be AUDIO_CHANNEL_OUT_STEREO", mChannelMask); 1644 } 1645 mChannelCount = popcount(mChannelMask); 1646 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common); 1647 if (!audio_is_valid_format(mFormat)) { 1648 LOG_FATAL("HAL format %d not valid for output", mFormat); 1649 } 1650 if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) { 1651 LOG_FATAL("HAL format %d not supported for mixed output; must be AUDIO_FORMAT_PCM_16_BIT", 1652 mFormat); 1653 } 1654 mFrameSize = audio_stream_frame_size(&mOutput->stream->common); 1655 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common); 1656 mFrameCount = mBufferSize / mFrameSize; 1657 if (mFrameCount & 15) { 1658 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames", 1659 mFrameCount); 1660 } 1661 1662 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) && 1663 (mOutput->stream->set_callback != NULL)) { 1664 if (mOutput->stream->set_callback(mOutput->stream, 1665 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) { 1666 mUseAsyncWrite = true; 1667 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this); 1668 } 1669 } 1670 1671 // Calculate size of normal mix buffer relative to the HAL output buffer size 1672 double multiplier = 1.0; 1673 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || 1674 kUseFastMixer == FastMixer_Dynamic)) { 1675 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000; 1676 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000; 1677 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer 1678 minNormalFrameCount = (minNormalFrameCount + 15) & ~15; 1679 maxNormalFrameCount = maxNormalFrameCount & ~15; 1680 if (maxNormalFrameCount < minNormalFrameCount) { 1681 maxNormalFrameCount = minNormalFrameCount; 1682 } 1683 multiplier = (double) minNormalFrameCount / (double) mFrameCount; 1684 if (multiplier <= 1.0) { 1685 multiplier = 1.0; 1686 } else if (multiplier <= 2.0) { 1687 if (2 * mFrameCount <= maxNormalFrameCount) { 1688 multiplier = 2.0; 1689 } else { 1690 multiplier = (double) maxNormalFrameCount / (double) mFrameCount; 1691 } 1692 } else { 1693 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL 1694 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast 1695 // track, but we sometimes have to do this to satisfy the maximum frame count 1696 // constraint) 1697 // FIXME this rounding up should not be done if no HAL SRC 1698 uint32_t truncMult = (uint32_t) multiplier; 1699 if ((truncMult & 1)) { 1700 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) { 1701 ++truncMult; 1702 } 1703 } 1704 multiplier = (double) truncMult; 1705 } 1706 } 1707 mNormalFrameCount = multiplier * mFrameCount; 1708 // round up to nearest 16 frames to satisfy AudioMixer 1709 mNormalFrameCount = (mNormalFrameCount + 15) & ~15; 1710 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, 1711 mNormalFrameCount); 1712 1713 delete[] mMixBuffer; 1714 size_t normalBufferSize = mNormalFrameCount * mFrameSize; 1715 // For historical reasons mMixBuffer is int16_t[], but mFrameSize can be odd (such as 1) 1716 mMixBuffer = new int16_t[(normalBufferSize + 1) >> 1]; 1717 memset(mMixBuffer, 0, normalBufferSize); 1718 1719 // force reconfiguration of effect chains and engines to take new buffer size and audio 1720 // parameters into account 1721 // Note that mLock is not held when readOutputParameters() is called from the constructor 1722 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't 1723 // matter. 1724 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains 1725 Vector< sp<EffectChain> > effectChains = mEffectChains; 1726 for (size_t i = 0; i < effectChains.size(); i ++) { 1727 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false); 1728 } 1729} 1730 1731 1732status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames) 1733{ 1734 if (halFrames == NULL || dspFrames == NULL) { 1735 return BAD_VALUE; 1736 } 1737 Mutex::Autolock _l(mLock); 1738 if (initCheck() != NO_ERROR) { 1739 return INVALID_OPERATION; 1740 } 1741 size_t framesWritten = mBytesWritten / mFrameSize; 1742 *halFrames = framesWritten; 1743 1744 if (isSuspended()) { 1745 // return an estimation of rendered frames when the output is suspended 1746 size_t latencyFrames = (latency_l() * mSampleRate) / 1000; 1747 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0; 1748 return NO_ERROR; 1749 } else { 1750 return mOutput->stream->get_render_position(mOutput->stream, dspFrames); 1751 } 1752} 1753 1754uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const 1755{ 1756 Mutex::Autolock _l(mLock); 1757 uint32_t result = 0; 1758 if (getEffectChain_l(sessionId) != 0) { 1759 result = EFFECT_SESSION; 1760 } 1761 1762 for (size_t i = 0; i < mTracks.size(); ++i) { 1763 sp<Track> track = mTracks[i]; 1764 if (sessionId == track->sessionId() && !track->isInvalid()) { 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() && !track->isInvalid()) { 1783 return AudioSystem::getStrategyForStream(track->streamType()); 1784 } 1785 } 1786 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); 1787} 1788 1789 1790AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const 1791{ 1792 Mutex::Autolock _l(mLock); 1793 return mOutput; 1794} 1795 1796AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput() 1797{ 1798 Mutex::Autolock _l(mLock); 1799 AudioStreamOut *output = mOutput; 1800 mOutput = NULL; 1801 // FIXME FastMixer might also have a raw ptr to mOutputSink; 1802 // must push a NULL and wait for ack 1803 mOutputSink.clear(); 1804 mPipeSink.clear(); 1805 mNormalSink.clear(); 1806 return output; 1807} 1808 1809// this method must always be called either with ThreadBase mLock held or inside the thread loop 1810audio_stream_t* AudioFlinger::PlaybackThread::stream() const 1811{ 1812 if (mOutput == NULL) { 1813 return NULL; 1814 } 1815 return &mOutput->stream->common; 1816} 1817 1818uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const 1819{ 1820 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000); 1821} 1822 1823status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event) 1824{ 1825 if (!isValidSyncEvent(event)) { 1826 return BAD_VALUE; 1827 } 1828 1829 Mutex::Autolock _l(mLock); 1830 1831 for (size_t i = 0; i < mTracks.size(); ++i) { 1832 sp<Track> track = mTracks[i]; 1833 if (event->triggerSession() == track->sessionId()) { 1834 (void) track->setSyncEvent(event); 1835 return NO_ERROR; 1836 } 1837 } 1838 1839 return NAME_NOT_FOUND; 1840} 1841 1842bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const 1843{ 1844 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE; 1845} 1846 1847void AudioFlinger::PlaybackThread::threadLoop_removeTracks( 1848 const Vector< sp<Track> >& tracksToRemove) 1849{ 1850 size_t count = tracksToRemove.size(); 1851 if (count > 0) { 1852 for (size_t i = 0 ; i < count ; i++) { 1853 const sp<Track>& track = tracksToRemove.itemAt(i); 1854 if (!track->isOutputTrack()) { 1855 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId()); 1856#ifdef ADD_BATTERY_DATA 1857 // to track the speaker usage 1858 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop); 1859#endif 1860 if (track->isTerminated()) { 1861 AudioSystem::releaseOutput(mId); 1862 } 1863 } 1864 } 1865 } 1866} 1867 1868void AudioFlinger::PlaybackThread::checkSilentMode_l() 1869{ 1870 if (!mMasterMute) { 1871 char value[PROPERTY_VALUE_MAX]; 1872 if (property_get("ro.audio.silent", value, "0") > 0) { 1873 char *endptr; 1874 unsigned long ul = strtoul(value, &endptr, 0); 1875 if (*endptr == '\0' && ul != 0) { 1876 ALOGD("Silence is golden"); 1877 // The setprop command will not allow a property to be changed after 1878 // the first time it is set, so we don't have to worry about un-muting. 1879 setMasterMute_l(true); 1880 } 1881 } 1882 } 1883} 1884 1885// shared by MIXER and DIRECT, overridden by DUPLICATING 1886ssize_t AudioFlinger::PlaybackThread::threadLoop_write() 1887{ 1888 // FIXME rewrite to reduce number of system calls 1889 mLastWriteTime = systemTime(); 1890 mInWrite = true; 1891 ssize_t bytesWritten; 1892 1893 // If an NBAIO sink is present, use it to write the normal mixer's submix 1894 if (mNormalSink != 0) { 1895#define mBitShift 2 // FIXME 1896 size_t count = mBytesRemaining >> mBitShift; 1897 size_t offset = (mCurrentWriteLength - mBytesRemaining) >> 1; 1898 ATRACE_BEGIN("write"); 1899 // update the setpoint when AudioFlinger::mScreenState changes 1900 uint32_t screenState = AudioFlinger::mScreenState; 1901 if (screenState != mScreenState) { 1902 mScreenState = screenState; 1903 MonoPipe *pipe = (MonoPipe *)mPipeSink.get(); 1904 if (pipe != NULL) { 1905 pipe->setAvgFrames((mScreenState & 1) ? 1906 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2); 1907 } 1908 } 1909 ssize_t framesWritten = mNormalSink->write(mMixBuffer + offset, count); 1910 ATRACE_END(); 1911 if (framesWritten > 0) { 1912 bytesWritten = framesWritten << mBitShift; 1913 } else { 1914 bytesWritten = framesWritten; 1915 } 1916 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp); 1917 if (status == NO_ERROR) { 1918 size_t totalFramesWritten = mNormalSink->framesWritten(); 1919 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) { 1920 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition; 1921 mLatchDValid = true; 1922 } 1923 } 1924 // otherwise use the HAL / AudioStreamOut directly 1925 } else { 1926 // Direct output and offload threads 1927 size_t offset = (mCurrentWriteLength - mBytesRemaining); 1928 if (mUseAsyncWrite) { 1929 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request"); 1930 mWriteAckSequence += 2; 1931 mWriteAckSequence |= 1; 1932 ALOG_ASSERT(mCallbackThread != 0); 1933 mCallbackThread->setWriteBlocked(mWriteAckSequence); 1934 } 1935 // FIXME We should have an implementation of timestamps for direct output threads. 1936 // They are used e.g for multichannel PCM playback over HDMI. 1937 bytesWritten = mOutput->stream->write(mOutput->stream, 1938 (char *)mMixBuffer + offset, mBytesRemaining); 1939 if (mUseAsyncWrite && 1940 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) { 1941 // do not wait for async callback in case of error of full write 1942 mWriteAckSequence &= ~1; 1943 ALOG_ASSERT(mCallbackThread != 0); 1944 mCallbackThread->setWriteBlocked(mWriteAckSequence); 1945 } 1946 } 1947 1948 mNumWrites++; 1949 mInWrite = false; 1950 mStandby = false; 1951 return bytesWritten; 1952} 1953 1954void AudioFlinger::PlaybackThread::threadLoop_drain() 1955{ 1956 if (mOutput->stream->drain) { 1957 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full"); 1958 if (mUseAsyncWrite) { 1959 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request"); 1960 mDrainSequence |= 1; 1961 ALOG_ASSERT(mCallbackThread != 0); 1962 mCallbackThread->setDraining(mDrainSequence); 1963 } 1964 mOutput->stream->drain(mOutput->stream, 1965 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY 1966 : AUDIO_DRAIN_ALL); 1967 } 1968} 1969 1970void AudioFlinger::PlaybackThread::threadLoop_exit() 1971{ 1972 // Default implementation has nothing to do 1973} 1974 1975/* 1976The derived values that are cached: 1977 - mixBufferSize from frame count * frame size 1978 - activeSleepTime from activeSleepTimeUs() 1979 - idleSleepTime from idleSleepTimeUs() 1980 - standbyDelay from mActiveSleepTimeUs (DIRECT only) 1981 - maxPeriod from frame count and sample rate (MIXER only) 1982 1983The parameters that affect these derived values are: 1984 - frame count 1985 - frame size 1986 - sample rate 1987 - device type: A2DP or not 1988 - device latency 1989 - format: PCM or not 1990 - active sleep time 1991 - idle sleep time 1992*/ 1993 1994void AudioFlinger::PlaybackThread::cacheParameters_l() 1995{ 1996 mixBufferSize = mNormalFrameCount * mFrameSize; 1997 activeSleepTime = activeSleepTimeUs(); 1998 idleSleepTime = idleSleepTimeUs(); 1999} 2000 2001void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType) 2002{ 2003 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d", 2004 this, streamType, mTracks.size()); 2005 Mutex::Autolock _l(mLock); 2006 2007 size_t size = mTracks.size(); 2008 for (size_t i = 0; i < size; i++) { 2009 sp<Track> t = mTracks[i]; 2010 if (t->streamType() == streamType) { 2011 t->invalidate(); 2012 } 2013 } 2014} 2015 2016status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain) 2017{ 2018 int session = chain->sessionId(); 2019 int16_t *buffer = mMixBuffer; 2020 bool ownsBuffer = false; 2021 2022 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session); 2023 if (session > 0) { 2024 // Only one effect chain can be present in direct output thread and it uses 2025 // the mix buffer as input 2026 if (mType != DIRECT) { 2027 size_t numSamples = mNormalFrameCount * mChannelCount; 2028 buffer = new int16_t[numSamples]; 2029 memset(buffer, 0, numSamples * sizeof(int16_t)); 2030 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session); 2031 ownsBuffer = true; 2032 } 2033 2034 // Attach all tracks with same session ID to this chain. 2035 for (size_t i = 0; i < mTracks.size(); ++i) { 2036 sp<Track> track = mTracks[i]; 2037 if (session == track->sessionId()) { 2038 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), 2039 buffer); 2040 track->setMainBuffer(buffer); 2041 chain->incTrackCnt(); 2042 } 2043 } 2044 2045 // indicate all active tracks in the chain 2046 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) { 2047 sp<Track> track = mActiveTracks[i].promote(); 2048 if (track == 0) { 2049 continue; 2050 } 2051 if (session == track->sessionId()) { 2052 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session); 2053 chain->incActiveTrackCnt(); 2054 } 2055 } 2056 } 2057 2058 chain->setInBuffer(buffer, ownsBuffer); 2059 chain->setOutBuffer(mMixBuffer); 2060 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect 2061 // chains list in order to be processed last as it contains output stage effects 2062 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before 2063 // session AUDIO_SESSION_OUTPUT_STAGE to be processed 2064 // after track specific effects and before output stage 2065 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and 2066 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX 2067 // Effect chain for other sessions are inserted at beginning of effect 2068 // chains list to be processed before output mix effects. Relative order between other 2069 // sessions is not important 2070 size_t size = mEffectChains.size(); 2071 size_t i = 0; 2072 for (i = 0; i < size; i++) { 2073 if (mEffectChains[i]->sessionId() < session) { 2074 break; 2075 } 2076 } 2077 mEffectChains.insertAt(chain, i); 2078 checkSuspendOnAddEffectChain_l(chain); 2079 2080 return NO_ERROR; 2081} 2082 2083size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain) 2084{ 2085 int session = chain->sessionId(); 2086 2087 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session); 2088 2089 for (size_t i = 0; i < mEffectChains.size(); i++) { 2090 if (chain == mEffectChains[i]) { 2091 mEffectChains.removeAt(i); 2092 // detach all active tracks from the chain 2093 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) { 2094 sp<Track> track = mActiveTracks[i].promote(); 2095 if (track == 0) { 2096 continue; 2097 } 2098 if (session == track->sessionId()) { 2099 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d", 2100 chain.get(), session); 2101 chain->decActiveTrackCnt(); 2102 } 2103 } 2104 2105 // detach all tracks with same session ID from this chain 2106 for (size_t i = 0; i < mTracks.size(); ++i) { 2107 sp<Track> track = mTracks[i]; 2108 if (session == track->sessionId()) { 2109 track->setMainBuffer(mMixBuffer); 2110 chain->decTrackCnt(); 2111 } 2112 } 2113 break; 2114 } 2115 } 2116 return mEffectChains.size(); 2117} 2118 2119status_t AudioFlinger::PlaybackThread::attachAuxEffect( 2120 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId) 2121{ 2122 Mutex::Autolock _l(mLock); 2123 return attachAuxEffect_l(track, EffectId); 2124} 2125 2126status_t AudioFlinger::PlaybackThread::attachAuxEffect_l( 2127 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId) 2128{ 2129 status_t status = NO_ERROR; 2130 2131 if (EffectId == 0) { 2132 track->setAuxBuffer(0, NULL); 2133 } else { 2134 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX 2135 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId); 2136 if (effect != 0) { 2137 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 2138 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer()); 2139 } else { 2140 status = INVALID_OPERATION; 2141 } 2142 } else { 2143 status = BAD_VALUE; 2144 } 2145 } 2146 return status; 2147} 2148 2149void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId) 2150{ 2151 for (size_t i = 0; i < mTracks.size(); ++i) { 2152 sp<Track> track = mTracks[i]; 2153 if (track->auxEffectId() == effectId) { 2154 attachAuxEffect_l(track, 0); 2155 } 2156 } 2157} 2158 2159bool AudioFlinger::PlaybackThread::threadLoop() 2160{ 2161 Vector< sp<Track> > tracksToRemove; 2162 2163 standbyTime = systemTime(); 2164 2165 // MIXER 2166 nsecs_t lastWarning = 0; 2167 2168 // DUPLICATING 2169 // FIXME could this be made local to while loop? 2170 writeFrames = 0; 2171 2172 int lastGeneration = 0; 2173 2174 cacheParameters_l(); 2175 sleepTime = idleSleepTime; 2176 2177 if (mType == MIXER) { 2178 sleepTimeShift = 0; 2179 } 2180 2181 CpuStats cpuStats; 2182 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid())); 2183 2184 acquireWakeLock(); 2185 2186 // mNBLogWriter->log can only be called while thread mutex mLock is held. 2187 // So if you need to log when mutex is unlocked, set logString to a non-NULL string, 2188 // and then that string will be logged at the next convenient opportunity. 2189 const char *logString = NULL; 2190 2191 checkSilentMode_l(); 2192 2193 while (!exitPending()) 2194 { 2195 cpuStats.sample(myName); 2196 2197 Vector< sp<EffectChain> > effectChains; 2198 2199 processConfigEvents(); 2200 2201 { // scope for mLock 2202 2203 Mutex::Autolock _l(mLock); 2204 2205 if (logString != NULL) { 2206 mNBLogWriter->logTimestamp(); 2207 mNBLogWriter->log(logString); 2208 logString = NULL; 2209 } 2210 2211 if (mLatchDValid) { 2212 mLatchQ = mLatchD; 2213 mLatchDValid = false; 2214 mLatchQValid = true; 2215 } 2216 2217 if (checkForNewParameters_l()) { 2218 cacheParameters_l(); 2219 } 2220 2221 saveOutputTracks(); 2222 if (mSignalPending) { 2223 // A signal was raised while we were unlocked 2224 mSignalPending = false; 2225 } else if (waitingAsyncCallback_l()) { 2226 if (exitPending()) { 2227 break; 2228 } 2229 releaseWakeLock_l(); 2230 mWakeLockUids.clear(); 2231 mActiveTracksGeneration++; 2232 ALOGV("wait async completion"); 2233 mWaitWorkCV.wait(mLock); 2234 ALOGV("async completion/wake"); 2235 acquireWakeLock_l(); 2236 standbyTime = systemTime() + standbyDelay; 2237 sleepTime = 0; 2238 2239 continue; 2240 } 2241 if ((!mActiveTracks.size() && systemTime() > standbyTime) || 2242 isSuspended()) { 2243 // put audio hardware into standby after short delay 2244 if (shouldStandby_l()) { 2245 2246 threadLoop_standby(); 2247 2248 mStandby = true; 2249 } 2250 2251 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) { 2252 // we're about to wait, flush the binder command buffer 2253 IPCThreadState::self()->flushCommands(); 2254 2255 clearOutputTracks(); 2256 2257 if (exitPending()) { 2258 break; 2259 } 2260 2261 releaseWakeLock_l(); 2262 mWakeLockUids.clear(); 2263 mActiveTracksGeneration++; 2264 // wait until we have something to do... 2265 ALOGV("%s going to sleep", myName.string()); 2266 mWaitWorkCV.wait(mLock); 2267 ALOGV("%s waking up", myName.string()); 2268 acquireWakeLock_l(); 2269 2270 mMixerStatus = MIXER_IDLE; 2271 mMixerStatusIgnoringFastTracks = MIXER_IDLE; 2272 mBytesWritten = 0; 2273 mBytesRemaining = 0; 2274 checkSilentMode_l(); 2275 2276 standbyTime = systemTime() + standbyDelay; 2277 sleepTime = idleSleepTime; 2278 if (mType == MIXER) { 2279 sleepTimeShift = 0; 2280 } 2281 2282 continue; 2283 } 2284 } 2285 // mMixerStatusIgnoringFastTracks is also updated internally 2286 mMixerStatus = prepareTracks_l(&tracksToRemove); 2287 2288 // compare with previously applied list 2289 if (lastGeneration != mActiveTracksGeneration) { 2290 // update wakelock 2291 updateWakeLockUids_l(mWakeLockUids); 2292 lastGeneration = mActiveTracksGeneration; 2293 } 2294 2295 // prevent any changes in effect chain list and in each effect chain 2296 // during mixing and effect process as the audio buffers could be deleted 2297 // or modified if an effect is created or deleted 2298 lockEffectChains_l(effectChains); 2299 } // mLock scope ends 2300 2301 if (mBytesRemaining == 0) { 2302 mCurrentWriteLength = 0; 2303 if (mMixerStatus == MIXER_TRACKS_READY) { 2304 // threadLoop_mix() sets mCurrentWriteLength 2305 threadLoop_mix(); 2306 } else if ((mMixerStatus != MIXER_DRAIN_TRACK) 2307 && (mMixerStatus != MIXER_DRAIN_ALL)) { 2308 // threadLoop_sleepTime sets sleepTime to 0 if data 2309 // must be written to HAL 2310 threadLoop_sleepTime(); 2311 if (sleepTime == 0) { 2312 mCurrentWriteLength = mixBufferSize; 2313 } 2314 } 2315 mBytesRemaining = mCurrentWriteLength; 2316 if (isSuspended()) { 2317 sleepTime = suspendSleepTimeUs(); 2318 // simulate write to HAL when suspended 2319 mBytesWritten += mixBufferSize; 2320 mBytesRemaining = 0; 2321 } 2322 2323 // only process effects if we're going to write 2324 if (sleepTime == 0 && mType != OFFLOAD) { 2325 for (size_t i = 0; i < effectChains.size(); i ++) { 2326 effectChains[i]->process_l(); 2327 } 2328 } 2329 } 2330 // Process effect chains for offloaded thread even if no audio 2331 // was read from audio track: process only updates effect state 2332 // and thus does have to be synchronized with audio writes but may have 2333 // to be called while waiting for async write callback 2334 if (mType == OFFLOAD) { 2335 for (size_t i = 0; i < effectChains.size(); i ++) { 2336 effectChains[i]->process_l(); 2337 } 2338 } 2339 2340 // enable changes in effect chain 2341 unlockEffectChains(effectChains); 2342 2343 if (!waitingAsyncCallback()) { 2344 // sleepTime == 0 means we must write to audio hardware 2345 if (sleepTime == 0) { 2346 if (mBytesRemaining) { 2347 ssize_t ret = threadLoop_write(); 2348 if (ret < 0) { 2349 mBytesRemaining = 0; 2350 } else { 2351 mBytesWritten += ret; 2352 mBytesRemaining -= ret; 2353 } 2354 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) || 2355 (mMixerStatus == MIXER_DRAIN_ALL)) { 2356 threadLoop_drain(); 2357 } 2358if (mType == MIXER) { 2359 // write blocked detection 2360 nsecs_t now = systemTime(); 2361 nsecs_t delta = now - mLastWriteTime; 2362 if (!mStandby && delta > maxPeriod) { 2363 mNumDelayedWrites++; 2364 if ((now - lastWarning) > kWarningThrottleNs) { 2365 ATRACE_NAME("underrun"); 2366 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p", 2367 ns2ms(delta), mNumDelayedWrites, this); 2368 lastWarning = now; 2369 } 2370 } 2371} 2372 2373 } else { 2374 usleep(sleepTime); 2375 } 2376 } 2377 2378 // Finally let go of removed track(s), without the lock held 2379 // since we can't guarantee the destructors won't acquire that 2380 // same lock. This will also mutate and push a new fast mixer state. 2381 threadLoop_removeTracks(tracksToRemove); 2382 tracksToRemove.clear(); 2383 2384 // FIXME I don't understand the need for this here; 2385 // it was in the original code but maybe the 2386 // assignment in saveOutputTracks() makes this unnecessary? 2387 clearOutputTracks(); 2388 2389 // Effect chains will be actually deleted here if they were removed from 2390 // mEffectChains list during mixing or effects processing 2391 effectChains.clear(); 2392 2393 // FIXME Note that the above .clear() is no longer necessary since effectChains 2394 // is now local to this block, but will keep it for now (at least until merge done). 2395 } 2396 2397 threadLoop_exit(); 2398 2399 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ... 2400 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) { 2401 // put output stream into standby mode 2402 if (!mStandby) { 2403 mOutput->stream->common.standby(&mOutput->stream->common); 2404 } 2405 } 2406 2407 releaseWakeLock(); 2408 mWakeLockUids.clear(); 2409 mActiveTracksGeneration++; 2410 2411 ALOGV("Thread %p type %d exiting", this, mType); 2412 return false; 2413} 2414 2415// removeTracks_l() must be called with ThreadBase::mLock held 2416void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove) 2417{ 2418 size_t count = tracksToRemove.size(); 2419 if (count > 0) { 2420 for (size_t i=0 ; i<count ; i++) { 2421 const sp<Track>& track = tracksToRemove.itemAt(i); 2422 mActiveTracks.remove(track); 2423 mWakeLockUids.remove(track->uid()); 2424 mActiveTracksGeneration++; 2425 ALOGV("removeTracks_l removing track on session %d", track->sessionId()); 2426 sp<EffectChain> chain = getEffectChain_l(track->sessionId()); 2427 if (chain != 0) { 2428 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), 2429 track->sessionId()); 2430 chain->decActiveTrackCnt(); 2431 } 2432 if (track->isTerminated()) { 2433 removeTrack_l(track); 2434 } 2435 } 2436 } 2437 2438} 2439 2440status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp) 2441{ 2442 if (mNormalSink != 0) { 2443 return mNormalSink->getTimestamp(timestamp); 2444 } 2445 if (mType == OFFLOAD && mOutput->stream->get_presentation_position) { 2446 uint64_t position64; 2447 int ret = mOutput->stream->get_presentation_position( 2448 mOutput->stream, &position64, ×tamp.mTime); 2449 if (ret == 0) { 2450 timestamp.mPosition = (uint32_t)position64; 2451 return NO_ERROR; 2452 } 2453 } 2454 return INVALID_OPERATION; 2455} 2456// ---------------------------------------------------------------------------- 2457 2458AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, 2459 audio_io_handle_t id, audio_devices_t device, type_t type) 2460 : PlaybackThread(audioFlinger, output, id, device, type), 2461 // mAudioMixer below 2462 // mFastMixer below 2463 mFastMixerFutex(0) 2464 // mOutputSink below 2465 // mPipeSink below 2466 // mNormalSink below 2467{ 2468 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type); 2469 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, " 2470 "mFrameCount=%d, mNormalFrameCount=%d", 2471 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount, 2472 mNormalFrameCount); 2473 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate); 2474 2475 // FIXME - Current mixer implementation only supports stereo output 2476 if (mChannelCount != FCC_2) { 2477 ALOGE("Invalid audio hardware channel count %d", mChannelCount); 2478 } 2479 2480 // create an NBAIO sink for the HAL output stream, and negotiate 2481 mOutputSink = new AudioStreamOutSink(output->stream); 2482 size_t numCounterOffers = 0; 2483 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)}; 2484 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers); 2485 ALOG_ASSERT(index == 0); 2486 2487 // initialize fast mixer depending on configuration 2488 bool initFastMixer; 2489 switch (kUseFastMixer) { 2490 case FastMixer_Never: 2491 initFastMixer = false; 2492 break; 2493 case FastMixer_Always: 2494 initFastMixer = true; 2495 break; 2496 case FastMixer_Static: 2497 case FastMixer_Dynamic: 2498 initFastMixer = mFrameCount < mNormalFrameCount; 2499 break; 2500 } 2501 if (initFastMixer) { 2502 2503 // create a MonoPipe to connect our submix to FastMixer 2504 NBAIO_Format format = mOutputSink->format(); 2505 // This pipe depth compensates for scheduling latency of the normal mixer thread. 2506 // When it wakes up after a maximum latency, it runs a few cycles quickly before 2507 // finally blocking. Note the pipe implementation rounds up the request to a power of 2. 2508 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/); 2509 const NBAIO_Format offers[1] = {format}; 2510 size_t numCounterOffers = 0; 2511 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers); 2512 ALOG_ASSERT(index == 0); 2513 monoPipe->setAvgFrames((mScreenState & 1) ? 2514 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2); 2515 mPipeSink = monoPipe; 2516 2517#ifdef TEE_SINK 2518 if (mTeeSinkOutputEnabled) { 2519 // create a Pipe to archive a copy of FastMixer's output for dumpsys 2520 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format); 2521 numCounterOffers = 0; 2522 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers); 2523 ALOG_ASSERT(index == 0); 2524 mTeeSink = teeSink; 2525 PipeReader *teeSource = new PipeReader(*teeSink); 2526 numCounterOffers = 0; 2527 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers); 2528 ALOG_ASSERT(index == 0); 2529 mTeeSource = teeSource; 2530 } 2531#endif 2532 2533 // create fast mixer and configure it initially with just one fast track for our submix 2534 mFastMixer = new FastMixer(); 2535 FastMixerStateQueue *sq = mFastMixer->sq(); 2536#ifdef STATE_QUEUE_DUMP 2537 sq->setObserverDump(&mStateQueueObserverDump); 2538 sq->setMutatorDump(&mStateQueueMutatorDump); 2539#endif 2540 FastMixerState *state = sq->begin(); 2541 FastTrack *fastTrack = &state->mFastTracks[0]; 2542 // wrap the source side of the MonoPipe to make it an AudioBufferProvider 2543 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe)); 2544 fastTrack->mVolumeProvider = NULL; 2545 fastTrack->mGeneration++; 2546 state->mFastTracksGen++; 2547 state->mTrackMask = 1; 2548 // fast mixer will use the HAL output sink 2549 state->mOutputSink = mOutputSink.get(); 2550 state->mOutputSinkGen++; 2551 state->mFrameCount = mFrameCount; 2552 state->mCommand = FastMixerState::COLD_IDLE; 2553 // already done in constructor initialization list 2554 //mFastMixerFutex = 0; 2555 state->mColdFutexAddr = &mFastMixerFutex; 2556 state->mColdGen++; 2557 state->mDumpState = &mFastMixerDumpState; 2558#ifdef TEE_SINK 2559 state->mTeeSink = mTeeSink.get(); 2560#endif 2561 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer"); 2562 state->mNBLogWriter = mFastMixerNBLogWriter.get(); 2563 sq->end(); 2564 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 2565 2566 // start the fast mixer 2567 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO); 2568 pid_t tid = mFastMixer->getTid(); 2569 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer); 2570 if (err != 0) { 2571 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d", 2572 kPriorityFastMixer, getpid_cached, tid, err); 2573 } 2574 2575#ifdef AUDIO_WATCHDOG 2576 // create and start the watchdog 2577 mAudioWatchdog = new AudioWatchdog(); 2578 mAudioWatchdog->setDump(&mAudioWatchdogDump); 2579 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO); 2580 tid = mAudioWatchdog->getTid(); 2581 err = requestPriority(getpid_cached, tid, kPriorityFastMixer); 2582 if (err != 0) { 2583 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d", 2584 kPriorityFastMixer, getpid_cached, tid, err); 2585 } 2586#endif 2587 2588 } else { 2589 mFastMixer = NULL; 2590 } 2591 2592 switch (kUseFastMixer) { 2593 case FastMixer_Never: 2594 case FastMixer_Dynamic: 2595 mNormalSink = mOutputSink; 2596 break; 2597 case FastMixer_Always: 2598 mNormalSink = mPipeSink; 2599 break; 2600 case FastMixer_Static: 2601 mNormalSink = initFastMixer ? mPipeSink : mOutputSink; 2602 break; 2603 } 2604} 2605 2606AudioFlinger::MixerThread::~MixerThread() 2607{ 2608 if (mFastMixer != NULL) { 2609 FastMixerStateQueue *sq = mFastMixer->sq(); 2610 FastMixerState *state = sq->begin(); 2611 if (state->mCommand == FastMixerState::COLD_IDLE) { 2612 int32_t old = android_atomic_inc(&mFastMixerFutex); 2613 if (old == -1) { 2614 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1); 2615 } 2616 } 2617 state->mCommand = FastMixerState::EXIT; 2618 sq->end(); 2619 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 2620 mFastMixer->join(); 2621 // Though the fast mixer thread has exited, it's state queue is still valid. 2622 // We'll use that extract the final state which contains one remaining fast track 2623 // corresponding to our sub-mix. 2624 state = sq->begin(); 2625 ALOG_ASSERT(state->mTrackMask == 1); 2626 FastTrack *fastTrack = &state->mFastTracks[0]; 2627 ALOG_ASSERT(fastTrack->mBufferProvider != NULL); 2628 delete fastTrack->mBufferProvider; 2629 sq->end(false /*didModify*/); 2630 delete mFastMixer; 2631#ifdef AUDIO_WATCHDOG 2632 if (mAudioWatchdog != 0) { 2633 mAudioWatchdog->requestExit(); 2634 mAudioWatchdog->requestExitAndWait(); 2635 mAudioWatchdog.clear(); 2636 } 2637#endif 2638 } 2639 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter); 2640 delete mAudioMixer; 2641} 2642 2643 2644uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const 2645{ 2646 if (mFastMixer != NULL) { 2647 MonoPipe *pipe = (MonoPipe *)mPipeSink.get(); 2648 latency += (pipe->getAvgFrames() * 1000) / mSampleRate; 2649 } 2650 return latency; 2651} 2652 2653 2654void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove) 2655{ 2656 PlaybackThread::threadLoop_removeTracks(tracksToRemove); 2657} 2658 2659ssize_t AudioFlinger::MixerThread::threadLoop_write() 2660{ 2661 // FIXME we should only do one push per cycle; confirm this is true 2662 // Start the fast mixer if it's not already running 2663 if (mFastMixer != NULL) { 2664 FastMixerStateQueue *sq = mFastMixer->sq(); 2665 FastMixerState *state = sq->begin(); 2666 if (state->mCommand != FastMixerState::MIX_WRITE && 2667 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) { 2668 if (state->mCommand == FastMixerState::COLD_IDLE) { 2669 int32_t old = android_atomic_inc(&mFastMixerFutex); 2670 if (old == -1) { 2671 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1); 2672 } 2673#ifdef AUDIO_WATCHDOG 2674 if (mAudioWatchdog != 0) { 2675 mAudioWatchdog->resume(); 2676 } 2677#endif 2678 } 2679 state->mCommand = FastMixerState::MIX_WRITE; 2680 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ? 2681 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN); 2682 sq->end(); 2683 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 2684 if (kUseFastMixer == FastMixer_Dynamic) { 2685 mNormalSink = mPipeSink; 2686 } 2687 } else { 2688 sq->end(false /*didModify*/); 2689 } 2690 } 2691 return PlaybackThread::threadLoop_write(); 2692} 2693 2694void AudioFlinger::MixerThread::threadLoop_standby() 2695{ 2696 // Idle the fast mixer if it's currently running 2697 if (mFastMixer != NULL) { 2698 FastMixerStateQueue *sq = mFastMixer->sq(); 2699 FastMixerState *state = sq->begin(); 2700 if (!(state->mCommand & FastMixerState::IDLE)) { 2701 state->mCommand = FastMixerState::COLD_IDLE; 2702 state->mColdFutexAddr = &mFastMixerFutex; 2703 state->mColdGen++; 2704 mFastMixerFutex = 0; 2705 sq->end(); 2706 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now 2707 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED); 2708 if (kUseFastMixer == FastMixer_Dynamic) { 2709 mNormalSink = mOutputSink; 2710 } 2711#ifdef AUDIO_WATCHDOG 2712 if (mAudioWatchdog != 0) { 2713 mAudioWatchdog->pause(); 2714 } 2715#endif 2716 } else { 2717 sq->end(false /*didModify*/); 2718 } 2719 } 2720 PlaybackThread::threadLoop_standby(); 2721} 2722 2723// Empty implementation for standard mixer 2724// Overridden for offloaded playback 2725void AudioFlinger::PlaybackThread::flushOutput_l() 2726{ 2727} 2728 2729bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l() 2730{ 2731 return false; 2732} 2733 2734bool AudioFlinger::PlaybackThread::shouldStandby_l() 2735{ 2736 return !mStandby; 2737} 2738 2739bool AudioFlinger::PlaybackThread::waitingAsyncCallback() 2740{ 2741 Mutex::Autolock _l(mLock); 2742 return waitingAsyncCallback_l(); 2743} 2744 2745// shared by MIXER and DIRECT, overridden by DUPLICATING 2746void AudioFlinger::PlaybackThread::threadLoop_standby() 2747{ 2748 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended); 2749 mOutput->stream->common.standby(&mOutput->stream->common); 2750 if (mUseAsyncWrite != 0) { 2751 // discard any pending drain or write ack by incrementing sequence 2752 mWriteAckSequence = (mWriteAckSequence + 2) & ~1; 2753 mDrainSequence = (mDrainSequence + 2) & ~1; 2754 ALOG_ASSERT(mCallbackThread != 0); 2755 mCallbackThread->setWriteBlocked(mWriteAckSequence); 2756 mCallbackThread->setDraining(mDrainSequence); 2757 } 2758} 2759 2760void AudioFlinger::MixerThread::threadLoop_mix() 2761{ 2762 // obtain the presentation timestamp of the next output buffer 2763 int64_t pts; 2764 status_t status = INVALID_OPERATION; 2765 2766 if (mNormalSink != 0) { 2767 status = mNormalSink->getNextWriteTimestamp(&pts); 2768 } else { 2769 status = mOutputSink->getNextWriteTimestamp(&pts); 2770 } 2771 2772 if (status != NO_ERROR) { 2773 pts = AudioBufferProvider::kInvalidPTS; 2774 } 2775 2776 // mix buffers... 2777 mAudioMixer->process(pts); 2778 mCurrentWriteLength = mixBufferSize; 2779 // increase sleep time progressively when application underrun condition clears. 2780 // Only increase sleep time if the mixer is ready for two consecutive times to avoid 2781 // that a steady state of alternating ready/not ready conditions keeps the sleep time 2782 // such that we would underrun the audio HAL. 2783 if ((sleepTime == 0) && (sleepTimeShift > 0)) { 2784 sleepTimeShift--; 2785 } 2786 sleepTime = 0; 2787 standbyTime = systemTime() + standbyDelay; 2788 //TODO: delay standby when effects have a tail 2789} 2790 2791void AudioFlinger::MixerThread::threadLoop_sleepTime() 2792{ 2793 // If no tracks are ready, sleep once for the duration of an output 2794 // buffer size, then write 0s to the output 2795 if (sleepTime == 0) { 2796 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 2797 sleepTime = activeSleepTime >> sleepTimeShift; 2798 if (sleepTime < kMinThreadSleepTimeUs) { 2799 sleepTime = kMinThreadSleepTimeUs; 2800 } 2801 // reduce sleep time in case of consecutive application underruns to avoid 2802 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer 2803 // duration we would end up writing less data than needed by the audio HAL if 2804 // the condition persists. 2805 if (sleepTimeShift < kMaxThreadSleepTimeShift) { 2806 sleepTimeShift++; 2807 } 2808 } else { 2809 sleepTime = idleSleepTime; 2810 } 2811 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) { 2812 memset(mMixBuffer, 0, mixBufferSize); 2813 sleepTime = 0; 2814 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED), 2815 "anticipated start"); 2816 } 2817 // TODO add standby time extension fct of effect tail 2818} 2819 2820// prepareTracks_l() must be called with ThreadBase::mLock held 2821AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l( 2822 Vector< sp<Track> > *tracksToRemove) 2823{ 2824 2825 mixer_state mixerStatus = MIXER_IDLE; 2826 // find out which tracks need to be processed 2827 size_t count = mActiveTracks.size(); 2828 size_t mixedTracks = 0; 2829 size_t tracksWithEffect = 0; 2830 // counts only _active_ fast tracks 2831 size_t fastTracks = 0; 2832 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset 2833 2834 float masterVolume = mMasterVolume; 2835 bool masterMute = mMasterMute; 2836 2837 if (masterMute) { 2838 masterVolume = 0; 2839 } 2840 // Delegate master volume control to effect in output mix effect chain if needed 2841 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); 2842 if (chain != 0) { 2843 uint32_t v = (uint32_t)(masterVolume * (1 << 24)); 2844 chain->setVolume_l(&v, &v); 2845 masterVolume = (float)((v + (1 << 23)) >> 24); 2846 chain.clear(); 2847 } 2848 2849 // prepare a new state to push 2850 FastMixerStateQueue *sq = NULL; 2851 FastMixerState *state = NULL; 2852 bool didModify = false; 2853 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED; 2854 if (mFastMixer != NULL) { 2855 sq = mFastMixer->sq(); 2856 state = sq->begin(); 2857 } 2858 2859 for (size_t i=0 ; i<count ; i++) { 2860 const sp<Track> t = mActiveTracks[i].promote(); 2861 if (t == 0) { 2862 continue; 2863 } 2864 2865 // this const just means the local variable doesn't change 2866 Track* const track = t.get(); 2867 2868 // process fast tracks 2869 if (track->isFastTrack()) { 2870 2871 // It's theoretically possible (though unlikely) for a fast track to be created 2872 // and then removed within the same normal mix cycle. This is not a problem, as 2873 // the track never becomes active so it's fast mixer slot is never touched. 2874 // The converse, of removing an (active) track and then creating a new track 2875 // at the identical fast mixer slot within the same normal mix cycle, 2876 // is impossible because the slot isn't marked available until the end of each cycle. 2877 int j = track->mFastIndex; 2878 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks); 2879 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j))); 2880 FastTrack *fastTrack = &state->mFastTracks[j]; 2881 2882 // Determine whether the track is currently in underrun condition, 2883 // and whether it had a recent underrun. 2884 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j]; 2885 FastTrackUnderruns underruns = ftDump->mUnderruns; 2886 uint32_t recentFull = (underruns.mBitFields.mFull - 2887 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK; 2888 uint32_t recentPartial = (underruns.mBitFields.mPartial - 2889 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK; 2890 uint32_t recentEmpty = (underruns.mBitFields.mEmpty - 2891 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK; 2892 uint32_t recentUnderruns = recentPartial + recentEmpty; 2893 track->mObservedUnderruns = underruns; 2894 // don't count underruns that occur while stopping or pausing 2895 // or stopped which can occur when flush() is called while active 2896 if (!(track->isStopping() || track->isPausing() || track->isStopped()) && 2897 recentUnderruns > 0) { 2898 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun 2899 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount); 2900 } 2901 2902 // This is similar to the state machine for normal tracks, 2903 // with a few modifications for fast tracks. 2904 bool isActive = true; 2905 switch (track->mState) { 2906 case TrackBase::STOPPING_1: 2907 // track stays active in STOPPING_1 state until first underrun 2908 if (recentUnderruns > 0 || track->isTerminated()) { 2909 track->mState = TrackBase::STOPPING_2; 2910 } 2911 break; 2912 case TrackBase::PAUSING: 2913 // ramp down is not yet implemented 2914 track->setPaused(); 2915 break; 2916 case TrackBase::RESUMING: 2917 // ramp up is not yet implemented 2918 track->mState = TrackBase::ACTIVE; 2919 break; 2920 case TrackBase::ACTIVE: 2921 if (recentFull > 0 || recentPartial > 0) { 2922 // track has provided at least some frames recently: reset retry count 2923 track->mRetryCount = kMaxTrackRetries; 2924 } 2925 if (recentUnderruns == 0) { 2926 // no recent underruns: stay active 2927 break; 2928 } 2929 // there has recently been an underrun of some kind 2930 if (track->sharedBuffer() == 0) { 2931 // were any of the recent underruns "empty" (no frames available)? 2932 if (recentEmpty == 0) { 2933 // no, then ignore the partial underruns as they are allowed indefinitely 2934 break; 2935 } 2936 // there has recently been an "empty" underrun: decrement the retry counter 2937 if (--(track->mRetryCount) > 0) { 2938 break; 2939 } 2940 // indicate to client process that the track was disabled because of underrun; 2941 // it will then automatically call start() when data is available 2942 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags); 2943 // remove from active list, but state remains ACTIVE [confusing but true] 2944 isActive = false; 2945 break; 2946 } 2947 // fall through 2948 case TrackBase::STOPPING_2: 2949 case TrackBase::PAUSED: 2950 case TrackBase::STOPPED: 2951 case TrackBase::FLUSHED: // flush() while active 2952 // Check for presentation complete if track is inactive 2953 // We have consumed all the buffers of this track. 2954 // This would be incomplete if we auto-paused on underrun 2955 { 2956 size_t audioHALFrames = 2957 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000; 2958 size_t framesWritten = mBytesWritten / mFrameSize; 2959 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) { 2960 // track stays in active list until presentation is complete 2961 break; 2962 } 2963 } 2964 if (track->isStopping_2()) { 2965 track->mState = TrackBase::STOPPED; 2966 } 2967 if (track->isStopped()) { 2968 // Can't reset directly, as fast mixer is still polling this track 2969 // track->reset(); 2970 // So instead mark this track as needing to be reset after push with ack 2971 resetMask |= 1 << i; 2972 } 2973 isActive = false; 2974 break; 2975 case TrackBase::IDLE: 2976 default: 2977 LOG_FATAL("unexpected track state %d", track->mState); 2978 } 2979 2980 if (isActive) { 2981 // was it previously inactive? 2982 if (!(state->mTrackMask & (1 << j))) { 2983 ExtendedAudioBufferProvider *eabp = track; 2984 VolumeProvider *vp = track; 2985 fastTrack->mBufferProvider = eabp; 2986 fastTrack->mVolumeProvider = vp; 2987 fastTrack->mSampleRate = track->mSampleRate; 2988 fastTrack->mChannelMask = track->mChannelMask; 2989 fastTrack->mGeneration++; 2990 state->mTrackMask |= 1 << j; 2991 didModify = true; 2992 // no acknowledgement required for newly active tracks 2993 } 2994 // cache the combined master volume and stream type volume for fast mixer; this 2995 // lacks any synchronization or barrier so VolumeProvider may read a stale value 2996 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume; 2997 ++fastTracks; 2998 } else { 2999 // was it previously active? 3000 if (state->mTrackMask & (1 << j)) { 3001 fastTrack->mBufferProvider = NULL; 3002 fastTrack->mGeneration++; 3003 state->mTrackMask &= ~(1 << j); 3004 didModify = true; 3005 // If any fast tracks were removed, we must wait for acknowledgement 3006 // because we're about to decrement the last sp<> on those tracks. 3007 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED; 3008 } else { 3009 LOG_FATAL("fast track %d should have been active", j); 3010 } 3011 tracksToRemove->add(track); 3012 // Avoids a misleading display in dumpsys 3013 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL; 3014 } 3015 continue; 3016 } 3017 3018 { // local variable scope to avoid goto warning 3019 3020 audio_track_cblk_t* cblk = track->cblk(); 3021 3022 // The first time a track is added we wait 3023 // for all its buffers to be filled before processing it 3024 int name = track->name(); 3025 // make sure that we have enough frames to mix one full buffer. 3026 // enforce this condition only once to enable draining the buffer in case the client 3027 // app does not call stop() and relies on underrun to stop: 3028 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed 3029 // during last round 3030 size_t desiredFrames; 3031 uint32_t sr = track->sampleRate(); 3032 if (sr == mSampleRate) { 3033 desiredFrames = mNormalFrameCount; 3034 } else { 3035 // +1 for rounding and +1 for additional sample needed for interpolation 3036 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1; 3037 // add frames already consumed but not yet released by the resampler 3038 // because mAudioTrackServerProxy->framesReady() will include these frames 3039 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name()); 3040 // the minimum track buffer size is normally twice the number of frames necessary 3041 // to fill one buffer and the resampler should not leave more than one buffer worth 3042 // of unreleased frames after each pass, but just in case... 3043 ALOG_ASSERT(desiredFrames <= cblk->frameCount_); 3044 } 3045 uint32_t minFrames = 1; 3046 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() && 3047 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) { 3048 minFrames = desiredFrames; 3049 } 3050 // It's not safe to call framesReady() for a static buffer track, so assume it's ready 3051 size_t framesReady; 3052 if (track->sharedBuffer() == 0) { 3053 framesReady = track->framesReady(); 3054 } else if (track->isStopped()) { 3055 framesReady = 0; 3056 } else { 3057 framesReady = 1; 3058 } 3059 if ((framesReady >= minFrames) && track->isReady() && 3060 !track->isPaused() && !track->isTerminated()) 3061 { 3062 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this); 3063 3064 mixedTracks++; 3065 3066 // track->mainBuffer() != mMixBuffer means there is an effect chain 3067 // connected to the track 3068 chain.clear(); 3069 if (track->mainBuffer() != mMixBuffer) { 3070 chain = getEffectChain_l(track->sessionId()); 3071 // Delegate volume control to effect in track effect chain if needed 3072 if (chain != 0) { 3073 tracksWithEffect++; 3074 } else { 3075 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on " 3076 "session %d", 3077 name, track->sessionId()); 3078 } 3079 } 3080 3081 3082 int param = AudioMixer::VOLUME; 3083 if (track->mFillingUpStatus == Track::FS_FILLED) { 3084 // no ramp for the first volume setting 3085 track->mFillingUpStatus = Track::FS_ACTIVE; 3086 if (track->mState == TrackBase::RESUMING) { 3087 track->mState = TrackBase::ACTIVE; 3088 param = AudioMixer::RAMP_VOLUME; 3089 } 3090 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL); 3091 // FIXME should not make a decision based on mServer 3092 } else if (cblk->mServer != 0) { 3093 // If the track is stopped before the first frame was mixed, 3094 // do not apply ramp 3095 param = AudioMixer::RAMP_VOLUME; 3096 } 3097 3098 // compute volume for this track 3099 uint32_t vl, vr, va; 3100 if (track->isPausing() || mStreamTypes[track->streamType()].mute) { 3101 vl = vr = va = 0; 3102 if (track->isPausing()) { 3103 track->setPaused(); 3104 } 3105 } else { 3106 3107 // read original volumes with volume control 3108 float typeVolume = mStreamTypes[track->streamType()].volume; 3109 float v = masterVolume * typeVolume; 3110 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy; 3111 uint32_t vlr = proxy->getVolumeLR(); 3112 vl = vlr & 0xFFFF; 3113 vr = vlr >> 16; 3114 // track volumes come from shared memory, so can't be trusted and must be clamped 3115 if (vl > MAX_GAIN_INT) { 3116 ALOGV("Track left volume out of range: %04X", vl); 3117 vl = MAX_GAIN_INT; 3118 } 3119 if (vr > MAX_GAIN_INT) { 3120 ALOGV("Track right volume out of range: %04X", vr); 3121 vr = MAX_GAIN_INT; 3122 } 3123 // now apply the master volume and stream type volume 3124 vl = (uint32_t)(v * vl) << 12; 3125 vr = (uint32_t)(v * vr) << 12; 3126 // assuming master volume and stream type volume each go up to 1.0, 3127 // vl and vr are now in 8.24 format 3128 3129 uint16_t sendLevel = proxy->getSendLevel_U4_12(); 3130 // send level comes from shared memory and so may be corrupt 3131 if (sendLevel > MAX_GAIN_INT) { 3132 ALOGV("Track send level out of range: %04X", sendLevel); 3133 sendLevel = MAX_GAIN_INT; 3134 } 3135 va = (uint32_t)(v * sendLevel); 3136 } 3137 3138 // Delegate volume control to effect in track effect chain if needed 3139 if (chain != 0 && chain->setVolume_l(&vl, &vr)) { 3140 // Do not ramp volume if volume is controlled by effect 3141 param = AudioMixer::VOLUME; 3142 track->mHasVolumeController = true; 3143 } else { 3144 // force no volume ramp when volume controller was just disabled or removed 3145 // from effect chain to avoid volume spike 3146 if (track->mHasVolumeController) { 3147 param = AudioMixer::VOLUME; 3148 } 3149 track->mHasVolumeController = false; 3150 } 3151 3152 // Convert volumes from 8.24 to 4.12 format 3153 // This additional clamping is needed in case chain->setVolume_l() overshot 3154 vl = (vl + (1 << 11)) >> 12; 3155 if (vl > MAX_GAIN_INT) { 3156 vl = MAX_GAIN_INT; 3157 } 3158 vr = (vr + (1 << 11)) >> 12; 3159 if (vr > MAX_GAIN_INT) { 3160 vr = MAX_GAIN_INT; 3161 } 3162 3163 if (va > MAX_GAIN_INT) { 3164 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for - 3165 } 3166 3167 // XXX: these things DON'T need to be done each time 3168 mAudioMixer->setBufferProvider(name, track); 3169 mAudioMixer->enable(name); 3170 3171 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl); 3172 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr); 3173 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va); 3174 mAudioMixer->setParameter( 3175 name, 3176 AudioMixer::TRACK, 3177 AudioMixer::FORMAT, (void *)track->format()); 3178 mAudioMixer->setParameter( 3179 name, 3180 AudioMixer::TRACK, 3181 AudioMixer::CHANNEL_MASK, (void *)track->channelMask()); 3182 // limit track sample rate to 2 x output sample rate, which changes at re-configuration 3183 uint32_t maxSampleRate = mSampleRate * 2; 3184 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate(); 3185 if (reqSampleRate == 0) { 3186 reqSampleRate = mSampleRate; 3187 } else if (reqSampleRate > maxSampleRate) { 3188 reqSampleRate = maxSampleRate; 3189 } 3190 mAudioMixer->setParameter( 3191 name, 3192 AudioMixer::RESAMPLE, 3193 AudioMixer::SAMPLE_RATE, 3194 (void *)reqSampleRate); 3195 mAudioMixer->setParameter( 3196 name, 3197 AudioMixer::TRACK, 3198 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer()); 3199 mAudioMixer->setParameter( 3200 name, 3201 AudioMixer::TRACK, 3202 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer()); 3203 3204 // reset retry count 3205 track->mRetryCount = kMaxTrackRetries; 3206 3207 // If one track is ready, set the mixer ready if: 3208 // - the mixer was not ready during previous round OR 3209 // - no other track is not ready 3210 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY || 3211 mixerStatus != MIXER_TRACKS_ENABLED) { 3212 mixerStatus = MIXER_TRACKS_READY; 3213 } 3214 } else { 3215 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) { 3216 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames); 3217 } 3218 // clear effect chain input buffer if an active track underruns to avoid sending 3219 // previous audio buffer again to effects 3220 chain = getEffectChain_l(track->sessionId()); 3221 if (chain != 0) { 3222 chain->clearInputBuffer(); 3223 } 3224 3225 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this); 3226 if ((track->sharedBuffer() != 0) || track->isTerminated() || 3227 track->isStopped() || track->isPaused()) { 3228 // We have consumed all the buffers of this track. 3229 // Remove it from the list of active tracks. 3230 // TODO: use actual buffer filling status instead of latency when available from 3231 // audio HAL 3232 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000; 3233 size_t framesWritten = mBytesWritten / mFrameSize; 3234 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) { 3235 if (track->isStopped()) { 3236 track->reset(); 3237 } 3238 tracksToRemove->add(track); 3239 } 3240 } else { 3241 // No buffers for this track. Give it a few chances to 3242 // fill a buffer, then remove it from active list. 3243 if (--(track->mRetryCount) <= 0) { 3244 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this); 3245 tracksToRemove->add(track); 3246 // indicate to client process that the track was disabled because of underrun; 3247 // it will then automatically call start() when data is available 3248 android_atomic_or(CBLK_DISABLED, &cblk->mFlags); 3249 // If one track is not ready, mark the mixer also not ready if: 3250 // - the mixer was ready during previous round OR 3251 // - no other track is ready 3252 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY || 3253 mixerStatus != MIXER_TRACKS_READY) { 3254 mixerStatus = MIXER_TRACKS_ENABLED; 3255 } 3256 } 3257 mAudioMixer->disable(name); 3258 } 3259 3260 } // local variable scope to avoid goto warning 3261track_is_ready: ; 3262 3263 } 3264 3265 // Push the new FastMixer state if necessary 3266 bool pauseAudioWatchdog = false; 3267 if (didModify) { 3268 state->mFastTracksGen++; 3269 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle 3270 if (kUseFastMixer == FastMixer_Dynamic && 3271 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) { 3272 state->mCommand = FastMixerState::COLD_IDLE; 3273 state->mColdFutexAddr = &mFastMixerFutex; 3274 state->mColdGen++; 3275 mFastMixerFutex = 0; 3276 if (kUseFastMixer == FastMixer_Dynamic) { 3277 mNormalSink = mOutputSink; 3278 } 3279 // If we go into cold idle, need to wait for acknowledgement 3280 // so that fast mixer stops doing I/O. 3281 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED; 3282 pauseAudioWatchdog = true; 3283 } 3284 } 3285 if (sq != NULL) { 3286 sq->end(didModify); 3287 sq->push(block); 3288 } 3289#ifdef AUDIO_WATCHDOG 3290 if (pauseAudioWatchdog && mAudioWatchdog != 0) { 3291 mAudioWatchdog->pause(); 3292 } 3293#endif 3294 3295 // Now perform the deferred reset on fast tracks that have stopped 3296 while (resetMask != 0) { 3297 size_t i = __builtin_ctz(resetMask); 3298 ALOG_ASSERT(i < count); 3299 resetMask &= ~(1 << i); 3300 sp<Track> t = mActiveTracks[i].promote(); 3301 if (t == 0) { 3302 continue; 3303 } 3304 Track* track = t.get(); 3305 ALOG_ASSERT(track->isFastTrack() && track->isStopped()); 3306 track->reset(); 3307 } 3308 3309 // remove all the tracks that need to be... 3310 removeTracks_l(*tracksToRemove); 3311 3312 // mix buffer must be cleared if all tracks are connected to an 3313 // effect chain as in this case the mixer will not write to 3314 // mix buffer and track effects will accumulate into it 3315 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || 3316 (mixedTracks == 0 && fastTracks > 0))) { 3317 // FIXME as a performance optimization, should remember previous zero status 3318 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t)); 3319 } 3320 3321 // if any fast tracks, then status is ready 3322 mMixerStatusIgnoringFastTracks = mixerStatus; 3323 if (fastTracks > 0) { 3324 mixerStatus = MIXER_TRACKS_READY; 3325 } 3326 return mixerStatus; 3327} 3328 3329// getTrackName_l() must be called with ThreadBase::mLock held 3330int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId) 3331{ 3332 return mAudioMixer->getTrackName(channelMask, sessionId); 3333} 3334 3335// deleteTrackName_l() must be called with ThreadBase::mLock held 3336void AudioFlinger::MixerThread::deleteTrackName_l(int name) 3337{ 3338 ALOGV("remove track (%d) and delete from mixer", name); 3339 mAudioMixer->deleteTrackName(name); 3340} 3341 3342// checkForNewParameters_l() must be called with ThreadBase::mLock held 3343bool AudioFlinger::MixerThread::checkForNewParameters_l() 3344{ 3345 // if !&IDLE, holds the FastMixer state to restore after new parameters processed 3346 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE; 3347 bool reconfig = false; 3348 3349 while (!mNewParameters.isEmpty()) { 3350 3351 if (mFastMixer != NULL) { 3352 FastMixerStateQueue *sq = mFastMixer->sq(); 3353 FastMixerState *state = sq->begin(); 3354 if (!(state->mCommand & FastMixerState::IDLE)) { 3355 previousCommand = state->mCommand; 3356 state->mCommand = FastMixerState::HOT_IDLE; 3357 sq->end(); 3358 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED); 3359 } else { 3360 sq->end(false /*didModify*/); 3361 } 3362 } 3363 3364 status_t status = NO_ERROR; 3365 String8 keyValuePair = mNewParameters[0]; 3366 AudioParameter param = AudioParameter(keyValuePair); 3367 int value; 3368 3369 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { 3370 reconfig = true; 3371 } 3372 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { 3373 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) { 3374 status = BAD_VALUE; 3375 } else { 3376 // no need to save value, since it's constant 3377 reconfig = true; 3378 } 3379 } 3380 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { 3381 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) { 3382 status = BAD_VALUE; 3383 } else { 3384 // no need to save value, since it's constant 3385 reconfig = true; 3386 } 3387 } 3388 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 3389 // do not accept frame count changes if tracks are open as the track buffer 3390 // size depends on frame count and correct behavior would not be guaranteed 3391 // if frame count is changed after track creation 3392 if (!mTracks.isEmpty()) { 3393 status = INVALID_OPERATION; 3394 } else { 3395 reconfig = true; 3396 } 3397 } 3398 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 3399#ifdef ADD_BATTERY_DATA 3400 // when changing the audio output device, call addBatteryData to notify 3401 // the change 3402 if (mOutDevice != value) { 3403 uint32_t params = 0; 3404 // check whether speaker is on 3405 if (value & AUDIO_DEVICE_OUT_SPEAKER) { 3406 params |= IMediaPlayerService::kBatteryDataSpeakerOn; 3407 } 3408 3409 audio_devices_t deviceWithoutSpeaker 3410 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER; 3411 // check if any other device (except speaker) is on 3412 if (value & deviceWithoutSpeaker ) { 3413 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn; 3414 } 3415 3416 if (params != 0) { 3417 addBatteryData(params); 3418 } 3419 } 3420#endif 3421 3422 // forward device change to effects that have requested to be 3423 // aware of attached audio device. 3424 if (value != AUDIO_DEVICE_NONE) { 3425 mOutDevice = value; 3426 for (size_t i = 0; i < mEffectChains.size(); i++) { 3427 mEffectChains[i]->setDevice_l(mOutDevice); 3428 } 3429 } 3430 } 3431 3432 if (status == NO_ERROR) { 3433 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3434 keyValuePair.string()); 3435 if (!mStandby && status == INVALID_OPERATION) { 3436 mOutput->stream->common.standby(&mOutput->stream->common); 3437 mStandby = true; 3438 mBytesWritten = 0; 3439 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3440 keyValuePair.string()); 3441 } 3442 if (status == NO_ERROR && reconfig) { 3443 readOutputParameters(); 3444 delete mAudioMixer; 3445 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate); 3446 for (size_t i = 0; i < mTracks.size() ; i++) { 3447 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId); 3448 if (name < 0) { 3449 break; 3450 } 3451 mTracks[i]->mName = name; 3452 } 3453 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED); 3454 } 3455 } 3456 3457 mNewParameters.removeAt(0); 3458 3459 mParamStatus = status; 3460 mParamCond.signal(); 3461 // wait for condition with time out in case the thread calling ThreadBase::setParameters() 3462 // already timed out waiting for the status and will never signal the condition. 3463 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); 3464 } 3465 3466 if (!(previousCommand & FastMixerState::IDLE)) { 3467 ALOG_ASSERT(mFastMixer != NULL); 3468 FastMixerStateQueue *sq = mFastMixer->sq(); 3469 FastMixerState *state = sq->begin(); 3470 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE); 3471 state->mCommand = previousCommand; 3472 sq->end(); 3473 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 3474 } 3475 3476 return reconfig; 3477} 3478 3479 3480void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args) 3481{ 3482 const size_t SIZE = 256; 3483 char buffer[SIZE]; 3484 String8 result; 3485 3486 PlaybackThread::dumpInternals(fd, args); 3487 3488 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames()); 3489 result.append(buffer); 3490 write(fd, result.string(), result.size()); 3491 3492 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us 3493 const FastMixerDumpState copy(mFastMixerDumpState); 3494 copy.dump(fd); 3495 3496#ifdef STATE_QUEUE_DUMP 3497 // Similar for state queue 3498 StateQueueObserverDump observerCopy = mStateQueueObserverDump; 3499 observerCopy.dump(fd); 3500 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump; 3501 mutatorCopy.dump(fd); 3502#endif 3503 3504#ifdef TEE_SINK 3505 // Write the tee output to a .wav file 3506 dumpTee(fd, mTeeSource, mId); 3507#endif 3508 3509#ifdef AUDIO_WATCHDOG 3510 if (mAudioWatchdog != 0) { 3511 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us 3512 AudioWatchdogDump wdCopy = mAudioWatchdogDump; 3513 wdCopy.dump(fd); 3514 } 3515#endif 3516} 3517 3518uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const 3519{ 3520 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2; 3521} 3522 3523uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const 3524{ 3525 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000); 3526} 3527 3528void AudioFlinger::MixerThread::cacheParameters_l() 3529{ 3530 PlaybackThread::cacheParameters_l(); 3531 3532 // FIXME: Relaxed timing because of a certain device that can't meet latency 3533 // Should be reduced to 2x after the vendor fixes the driver issue 3534 // increase threshold again due to low power audio mode. The way this warning 3535 // threshold is calculated and its usefulness should be reconsidered anyway. 3536 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15; 3537} 3538 3539// ---------------------------------------------------------------------------- 3540 3541AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, 3542 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device) 3543 : PlaybackThread(audioFlinger, output, id, device, DIRECT) 3544 // mLeftVolFloat, mRightVolFloat 3545{ 3546} 3547 3548AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, 3549 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, 3550 ThreadBase::type_t type) 3551 : PlaybackThread(audioFlinger, output, id, device, type) 3552 // mLeftVolFloat, mRightVolFloat 3553{ 3554} 3555 3556AudioFlinger::DirectOutputThread::~DirectOutputThread() 3557{ 3558} 3559 3560void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack) 3561{ 3562 audio_track_cblk_t* cblk = track->cblk(); 3563 float left, right; 3564 3565 if (mMasterMute || mStreamTypes[track->streamType()].mute) { 3566 left = right = 0; 3567 } else { 3568 float typeVolume = mStreamTypes[track->streamType()].volume; 3569 float v = mMasterVolume * typeVolume; 3570 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy; 3571 uint32_t vlr = proxy->getVolumeLR(); 3572 float v_clamped = v * (vlr & 0xFFFF); 3573 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN; 3574 left = v_clamped/MAX_GAIN; 3575 v_clamped = v * (vlr >> 16); 3576 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN; 3577 right = v_clamped/MAX_GAIN; 3578 } 3579 3580 if (lastTrack) { 3581 if (left != mLeftVolFloat || right != mRightVolFloat) { 3582 mLeftVolFloat = left; 3583 mRightVolFloat = right; 3584 3585 // Convert volumes from float to 8.24 3586 uint32_t vl = (uint32_t)(left * (1 << 24)); 3587 uint32_t vr = (uint32_t)(right * (1 << 24)); 3588 3589 // Delegate volume control to effect in track effect chain if needed 3590 // only one effect chain can be present on DirectOutputThread, so if 3591 // there is one, the track is connected to it 3592 if (!mEffectChains.isEmpty()) { 3593 mEffectChains[0]->setVolume_l(&vl, &vr); 3594 left = (float)vl / (1 << 24); 3595 right = (float)vr / (1 << 24); 3596 } 3597 if (mOutput->stream->set_volume) { 3598 mOutput->stream->set_volume(mOutput->stream, left, right); 3599 } 3600 } 3601 } 3602} 3603 3604 3605AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l( 3606 Vector< sp<Track> > *tracksToRemove 3607) 3608{ 3609 size_t count = mActiveTracks.size(); 3610 mixer_state mixerStatus = MIXER_IDLE; 3611 3612 // find out which tracks need to be processed 3613 for (size_t i = 0; i < count; i++) { 3614 sp<Track> t = mActiveTracks[i].promote(); 3615 // The track died recently 3616 if (t == 0) { 3617 continue; 3618 } 3619 3620 Track* const track = t.get(); 3621 audio_track_cblk_t* cblk = track->cblk(); 3622 // Only consider last track started for volume and mixer state control. 3623 // In theory an older track could underrun and restart after the new one starts 3624 // but as we only care about the transition phase between two tracks on a 3625 // direct output, it is not a problem to ignore the underrun case. 3626 sp<Track> l = mLatestActiveTrack.promote(); 3627 bool last = l.get() == track; 3628 3629 // The first time a track is added we wait 3630 // for all its buffers to be filled before processing it 3631 uint32_t minFrames; 3632 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) { 3633 minFrames = mNormalFrameCount; 3634 } else { 3635 minFrames = 1; 3636 } 3637 3638 if ((track->framesReady() >= minFrames) && track->isReady() && 3639 !track->isPaused() && !track->isTerminated()) 3640 { 3641 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer); 3642 3643 if (track->mFillingUpStatus == Track::FS_FILLED) { 3644 track->mFillingUpStatus = Track::FS_ACTIVE; 3645 // make sure processVolume_l() will apply new volume even if 0 3646 mLeftVolFloat = mRightVolFloat = -1.0; 3647 if (track->mState == TrackBase::RESUMING) { 3648 track->mState = TrackBase::ACTIVE; 3649 } 3650 } 3651 3652 // compute volume for this track 3653 processVolume_l(track, last); 3654 if (last) { 3655 // reset retry count 3656 track->mRetryCount = kMaxTrackRetriesDirect; 3657 mActiveTrack = t; 3658 mixerStatus = MIXER_TRACKS_READY; 3659 } 3660 } else { 3661 // clear effect chain input buffer if the last active track started underruns 3662 // to avoid sending previous audio buffer again to effects 3663 if (!mEffectChains.isEmpty() && last) { 3664 mEffectChains[0]->clearInputBuffer(); 3665 } 3666 3667 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer); 3668 if ((track->sharedBuffer() != 0) || track->isTerminated() || 3669 track->isStopped() || track->isPaused()) { 3670 // We have consumed all the buffers of this track. 3671 // Remove it from the list of active tracks. 3672 // TODO: implement behavior for compressed audio 3673 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000; 3674 size_t framesWritten = mBytesWritten / mFrameSize; 3675 if (mStandby || !last || 3676 track->presentationComplete(framesWritten, audioHALFrames)) { 3677 if (track->isStopped()) { 3678 track->reset(); 3679 } 3680 tracksToRemove->add(track); 3681 } 3682 } else { 3683 // No buffers for this track. Give it a few chances to 3684 // fill a buffer, then remove it from active list. 3685 // Only consider last track started for mixer state control 3686 if (--(track->mRetryCount) <= 0) { 3687 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name()); 3688 tracksToRemove->add(track); 3689 // indicate to client process that the track was disabled because of underrun; 3690 // it will then automatically call start() when data is available 3691 android_atomic_or(CBLK_DISABLED, &cblk->mFlags); 3692 } else if (last) { 3693 mixerStatus = MIXER_TRACKS_ENABLED; 3694 } 3695 } 3696 } 3697 } 3698 3699 // remove all the tracks that need to be... 3700 removeTracks_l(*tracksToRemove); 3701 3702 return mixerStatus; 3703} 3704 3705void AudioFlinger::DirectOutputThread::threadLoop_mix() 3706{ 3707 size_t frameCount = mFrameCount; 3708 int8_t *curBuf = (int8_t *)mMixBuffer; 3709 // output audio to hardware 3710 while (frameCount) { 3711 AudioBufferProvider::Buffer buffer; 3712 buffer.frameCount = frameCount; 3713 mActiveTrack->getNextBuffer(&buffer); 3714 if (buffer.raw == NULL) { 3715 memset(curBuf, 0, frameCount * mFrameSize); 3716 break; 3717 } 3718 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize); 3719 frameCount -= buffer.frameCount; 3720 curBuf += buffer.frameCount * mFrameSize; 3721 mActiveTrack->releaseBuffer(&buffer); 3722 } 3723 mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer; 3724 sleepTime = 0; 3725 standbyTime = systemTime() + standbyDelay; 3726 mActiveTrack.clear(); 3727} 3728 3729void AudioFlinger::DirectOutputThread::threadLoop_sleepTime() 3730{ 3731 if (sleepTime == 0) { 3732 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 3733 sleepTime = activeSleepTime; 3734 } else { 3735 sleepTime = idleSleepTime; 3736 } 3737 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) { 3738 memset(mMixBuffer, 0, mFrameCount * mFrameSize); 3739 sleepTime = 0; 3740 } 3741} 3742 3743// getTrackName_l() must be called with ThreadBase::mLock held 3744int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask, 3745 int sessionId) 3746{ 3747 return 0; 3748} 3749 3750// deleteTrackName_l() must be called with ThreadBase::mLock held 3751void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name) 3752{ 3753} 3754 3755// checkForNewParameters_l() must be called with ThreadBase::mLock held 3756bool AudioFlinger::DirectOutputThread::checkForNewParameters_l() 3757{ 3758 bool reconfig = false; 3759 3760 while (!mNewParameters.isEmpty()) { 3761 status_t status = NO_ERROR; 3762 String8 keyValuePair = mNewParameters[0]; 3763 AudioParameter param = AudioParameter(keyValuePair); 3764 int value; 3765 3766 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 3767 // do not accept frame count changes if tracks are open as the track buffer 3768 // size depends on frame count and correct behavior would not be garantied 3769 // if frame count is changed after track creation 3770 if (!mTracks.isEmpty()) { 3771 status = INVALID_OPERATION; 3772 } else { 3773 reconfig = true; 3774 } 3775 } 3776 if (status == NO_ERROR) { 3777 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3778 keyValuePair.string()); 3779 if (!mStandby && status == INVALID_OPERATION) { 3780 mOutput->stream->common.standby(&mOutput->stream->common); 3781 mStandby = true; 3782 mBytesWritten = 0; 3783 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3784 keyValuePair.string()); 3785 } 3786 if (status == NO_ERROR && reconfig) { 3787 readOutputParameters(); 3788 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED); 3789 } 3790 } 3791 3792 mNewParameters.removeAt(0); 3793 3794 mParamStatus = status; 3795 mParamCond.signal(); 3796 // wait for condition with time out in case the thread calling ThreadBase::setParameters() 3797 // already timed out waiting for the status and will never signal the condition. 3798 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); 3799 } 3800 return reconfig; 3801} 3802 3803uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const 3804{ 3805 uint32_t time; 3806 if (audio_is_linear_pcm(mFormat)) { 3807 time = PlaybackThread::activeSleepTimeUs(); 3808 } else { 3809 time = 10000; 3810 } 3811 return time; 3812} 3813 3814uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const 3815{ 3816 uint32_t time; 3817 if (audio_is_linear_pcm(mFormat)) { 3818 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2; 3819 } else { 3820 time = 10000; 3821 } 3822 return time; 3823} 3824 3825uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const 3826{ 3827 uint32_t time; 3828 if (audio_is_linear_pcm(mFormat)) { 3829 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000); 3830 } else { 3831 time = 10000; 3832 } 3833 return time; 3834} 3835 3836void AudioFlinger::DirectOutputThread::cacheParameters_l() 3837{ 3838 PlaybackThread::cacheParameters_l(); 3839 3840 // use shorter standby delay as on normal output to release 3841 // hardware resources as soon as possible 3842 if (audio_is_linear_pcm(mFormat)) { 3843 standbyDelay = microseconds(activeSleepTime*2); 3844 } else { 3845 standbyDelay = kOffloadStandbyDelayNs; 3846 } 3847} 3848 3849// ---------------------------------------------------------------------------- 3850 3851AudioFlinger::AsyncCallbackThread::AsyncCallbackThread( 3852 const wp<AudioFlinger::PlaybackThread>& playbackThread) 3853 : Thread(false /*canCallJava*/), 3854 mPlaybackThread(playbackThread), 3855 mWriteAckSequence(0), 3856 mDrainSequence(0) 3857{ 3858} 3859 3860AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread() 3861{ 3862} 3863 3864void AudioFlinger::AsyncCallbackThread::onFirstRef() 3865{ 3866 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO); 3867} 3868 3869bool AudioFlinger::AsyncCallbackThread::threadLoop() 3870{ 3871 while (!exitPending()) { 3872 uint32_t writeAckSequence; 3873 uint32_t drainSequence; 3874 3875 { 3876 Mutex::Autolock _l(mLock); 3877 while (!((mWriteAckSequence & 1) || 3878 (mDrainSequence & 1) || 3879 exitPending())) { 3880 mWaitWorkCV.wait(mLock); 3881 } 3882 3883 if (exitPending()) { 3884 break; 3885 } 3886 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d", 3887 mWriteAckSequence, mDrainSequence); 3888 writeAckSequence = mWriteAckSequence; 3889 mWriteAckSequence &= ~1; 3890 drainSequence = mDrainSequence; 3891 mDrainSequence &= ~1; 3892 } 3893 { 3894 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote(); 3895 if (playbackThread != 0) { 3896 if (writeAckSequence & 1) { 3897 playbackThread->resetWriteBlocked(writeAckSequence >> 1); 3898 } 3899 if (drainSequence & 1) { 3900 playbackThread->resetDraining(drainSequence >> 1); 3901 } 3902 } 3903 } 3904 } 3905 return false; 3906} 3907 3908void AudioFlinger::AsyncCallbackThread::exit() 3909{ 3910 ALOGV("AsyncCallbackThread::exit"); 3911 Mutex::Autolock _l(mLock); 3912 requestExit(); 3913 mWaitWorkCV.broadcast(); 3914} 3915 3916void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence) 3917{ 3918 Mutex::Autolock _l(mLock); 3919 // bit 0 is cleared 3920 mWriteAckSequence = sequence << 1; 3921} 3922 3923void AudioFlinger::AsyncCallbackThread::resetWriteBlocked() 3924{ 3925 Mutex::Autolock _l(mLock); 3926 // ignore unexpected callbacks 3927 if (mWriteAckSequence & 2) { 3928 mWriteAckSequence |= 1; 3929 mWaitWorkCV.signal(); 3930 } 3931} 3932 3933void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence) 3934{ 3935 Mutex::Autolock _l(mLock); 3936 // bit 0 is cleared 3937 mDrainSequence = sequence << 1; 3938} 3939 3940void AudioFlinger::AsyncCallbackThread::resetDraining() 3941{ 3942 Mutex::Autolock _l(mLock); 3943 // ignore unexpected callbacks 3944 if (mDrainSequence & 2) { 3945 mDrainSequence |= 1; 3946 mWaitWorkCV.signal(); 3947 } 3948} 3949 3950 3951// ---------------------------------------------------------------------------- 3952AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger, 3953 AudioStreamOut* output, audio_io_handle_t id, uint32_t device) 3954 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD), 3955 mHwPaused(false), 3956 mFlushPending(false), 3957 mPausedBytesRemaining(0) 3958{ 3959 //FIXME: mStandby should be set to true by ThreadBase constructor 3960 mStandby = true; 3961} 3962 3963void AudioFlinger::OffloadThread::threadLoop_exit() 3964{ 3965 if (mFlushPending || mHwPaused) { 3966 // If a flush is pending or track was paused, just discard buffered data 3967 flushHw_l(); 3968 } else { 3969 mMixerStatus = MIXER_DRAIN_ALL; 3970 threadLoop_drain(); 3971 } 3972 mCallbackThread->exit(); 3973 PlaybackThread::threadLoop_exit(); 3974} 3975 3976AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l( 3977 Vector< sp<Track> > *tracksToRemove 3978) 3979{ 3980 size_t count = mActiveTracks.size(); 3981 3982 mixer_state mixerStatus = MIXER_IDLE; 3983 bool doHwPause = false; 3984 bool doHwResume = false; 3985 3986 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count); 3987 3988 // find out which tracks need to be processed 3989 for (size_t i = 0; i < count; i++) { 3990 sp<Track> t = mActiveTracks[i].promote(); 3991 // The track died recently 3992 if (t == 0) { 3993 continue; 3994 } 3995 Track* const track = t.get(); 3996 audio_track_cblk_t* cblk = track->cblk(); 3997 // Only consider last track started for volume and mixer state control. 3998 // In theory an older track could underrun and restart after the new one starts 3999 // but as we only care about the transition phase between two tracks on a 4000 // direct output, it is not a problem to ignore the underrun case. 4001 sp<Track> l = mLatestActiveTrack.promote(); 4002 bool last = l.get() == track; 4003 4004 if (track->isPausing()) { 4005 track->setPaused(); 4006 if (last) { 4007 if (!mHwPaused) { 4008 doHwPause = true; 4009 mHwPaused = true; 4010 } 4011 // If we were part way through writing the mixbuffer to 4012 // the HAL we must save this until we resume 4013 // BUG - this will be wrong if a different track is made active, 4014 // in that case we want to discard the pending data in the 4015 // mixbuffer and tell the client to present it again when the 4016 // track is resumed 4017 mPausedWriteLength = mCurrentWriteLength; 4018 mPausedBytesRemaining = mBytesRemaining; 4019 mBytesRemaining = 0; // stop writing 4020 } 4021 tracksToRemove->add(track); 4022 } else if (track->framesReady() && track->isReady() && 4023 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) { 4024 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer); 4025 if (track->mFillingUpStatus == Track::FS_FILLED) { 4026 track->mFillingUpStatus = Track::FS_ACTIVE; 4027 // make sure processVolume_l() will apply new volume even if 0 4028 mLeftVolFloat = mRightVolFloat = -1.0; 4029 if (track->mState == TrackBase::RESUMING) { 4030 track->mState = TrackBase::ACTIVE; 4031 if (last) { 4032 if (mPausedBytesRemaining) { 4033 // Need to continue write that was interrupted 4034 mCurrentWriteLength = mPausedWriteLength; 4035 mBytesRemaining = mPausedBytesRemaining; 4036 mPausedBytesRemaining = 0; 4037 } 4038 if (mHwPaused) { 4039 doHwResume = true; 4040 mHwPaused = false; 4041 // threadLoop_mix() will handle the case that we need to 4042 // resume an interrupted write 4043 } 4044 // enable write to audio HAL 4045 sleepTime = 0; 4046 } 4047 } 4048 } 4049 4050 if (last) { 4051 sp<Track> previousTrack = mPreviousTrack.promote(); 4052 if (previousTrack != 0) { 4053 if (track != previousTrack.get()) { 4054 // Flush any data still being written from last track 4055 mBytesRemaining = 0; 4056 if (mPausedBytesRemaining) { 4057 // Last track was paused so we also need to flush saved 4058 // mixbuffer state and invalidate track so that it will 4059 // re-submit that unwritten data when it is next resumed 4060 mPausedBytesRemaining = 0; 4061 // Invalidate is a bit drastic - would be more efficient 4062 // to have a flag to tell client that some of the 4063 // previously written data was lost 4064 previousTrack->invalidate(); 4065 } 4066 // flush data already sent to the DSP if changing audio session as audio 4067 // comes from a different source. Also invalidate previous track to force a 4068 // seek when resuming. 4069 if (previousTrack->sessionId() != track->sessionId()) { 4070 previousTrack->invalidate(); 4071 mFlushPending = true; 4072 } 4073 } 4074 } 4075 mPreviousTrack = track; 4076 // reset retry count 4077 track->mRetryCount = kMaxTrackRetriesOffload; 4078 mActiveTrack = t; 4079 mixerStatus = MIXER_TRACKS_READY; 4080 } 4081 } else { 4082 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer); 4083 if (track->isStopping_1()) { 4084 // Hardware buffer can hold a large amount of audio so we must 4085 // wait for all current track's data to drain before we say 4086 // that the track is stopped. 4087 if (mBytesRemaining == 0) { 4088 // Only start draining when all data in mixbuffer 4089 // has been written 4090 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2"); 4091 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain 4092 // do not drain if no data was ever sent to HAL (mStandby == true) 4093 if (last && !mStandby) { 4094 // do not modify drain sequence if we are already draining. This happens 4095 // when resuming from pause after drain. 4096 if ((mDrainSequence & 1) == 0) { 4097 sleepTime = 0; 4098 standbyTime = systemTime() + standbyDelay; 4099 mixerStatus = MIXER_DRAIN_TRACK; 4100 mDrainSequence += 2; 4101 } 4102 if (mHwPaused) { 4103 // It is possible to move from PAUSED to STOPPING_1 without 4104 // a resume so we must ensure hardware is running 4105 doHwResume = true; 4106 mHwPaused = false; 4107 } 4108 } 4109 } 4110 } else if (track->isStopping_2()) { 4111 // Drain has completed or we are in standby, signal presentation complete 4112 if (!(mDrainSequence & 1) || !last || mStandby) { 4113 track->mState = TrackBase::STOPPED; 4114 size_t audioHALFrames = 4115 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000; 4116 size_t framesWritten = 4117 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common); 4118 track->presentationComplete(framesWritten, audioHALFrames); 4119 track->reset(); 4120 tracksToRemove->add(track); 4121 } 4122 } else { 4123 // No buffers for this track. Give it a few chances to 4124 // fill a buffer, then remove it from active list. 4125 if (--(track->mRetryCount) <= 0) { 4126 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list", 4127 track->name()); 4128 tracksToRemove->add(track); 4129 // indicate to client process that the track was disabled because of underrun; 4130 // it will then automatically call start() when data is available 4131 android_atomic_or(CBLK_DISABLED, &cblk->mFlags); 4132 } else if (last){ 4133 mixerStatus = MIXER_TRACKS_ENABLED; 4134 } 4135 } 4136 } 4137 // compute volume for this track 4138 processVolume_l(track, last); 4139 } 4140 4141 // make sure the pause/flush/resume sequence is executed in the right order. 4142 // If a flush is pending and a track is active but the HW is not paused, force a HW pause 4143 // before flush and then resume HW. This can happen in case of pause/flush/resume 4144 // if resume is received before pause is executed. 4145 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) { 4146 mOutput->stream->pause(mOutput->stream); 4147 if (!doHwPause) { 4148 doHwResume = true; 4149 } 4150 } 4151 if (mFlushPending) { 4152 flushHw_l(); 4153 mFlushPending = false; 4154 } 4155 if (!mStandby && doHwResume) { 4156 mOutput->stream->resume(mOutput->stream); 4157 } 4158 4159 // remove all the tracks that need to be... 4160 removeTracks_l(*tracksToRemove); 4161 4162 return mixerStatus; 4163} 4164 4165void AudioFlinger::OffloadThread::flushOutput_l() 4166{ 4167 mFlushPending = true; 4168} 4169 4170// must be called with thread mutex locked 4171bool AudioFlinger::OffloadThread::waitingAsyncCallback_l() 4172{ 4173 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d", 4174 mWriteAckSequence, mDrainSequence); 4175 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) { 4176 return true; 4177 } 4178 return false; 4179} 4180 4181// must be called with thread mutex locked 4182bool AudioFlinger::OffloadThread::shouldStandby_l() 4183{ 4184 bool trackPaused = false; 4185 4186 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack 4187 // after a timeout and we will enter standby then. 4188 if (mTracks.size() > 0) { 4189 trackPaused = mTracks[mTracks.size() - 1]->isPaused(); 4190 } 4191 4192 return !mStandby && !trackPaused; 4193} 4194 4195 4196bool AudioFlinger::OffloadThread::waitingAsyncCallback() 4197{ 4198 Mutex::Autolock _l(mLock); 4199 return waitingAsyncCallback_l(); 4200} 4201 4202void AudioFlinger::OffloadThread::flushHw_l() 4203{ 4204 mOutput->stream->flush(mOutput->stream); 4205 // Flush anything still waiting in the mixbuffer 4206 mCurrentWriteLength = 0; 4207 mBytesRemaining = 0; 4208 mPausedWriteLength = 0; 4209 mPausedBytesRemaining = 0; 4210 if (mUseAsyncWrite) { 4211 // discard any pending drain or write ack by incrementing sequence 4212 mWriteAckSequence = (mWriteAckSequence + 2) & ~1; 4213 mDrainSequence = (mDrainSequence + 2) & ~1; 4214 ALOG_ASSERT(mCallbackThread != 0); 4215 mCallbackThread->setWriteBlocked(mWriteAckSequence); 4216 mCallbackThread->setDraining(mDrainSequence); 4217 } 4218} 4219 4220// ---------------------------------------------------------------------------- 4221 4222AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, 4223 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id) 4224 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(), 4225 DUPLICATING), 4226 mWaitTimeMs(UINT_MAX) 4227{ 4228 addOutputTrack(mainThread); 4229} 4230 4231AudioFlinger::DuplicatingThread::~DuplicatingThread() 4232{ 4233 for (size_t i = 0; i < mOutputTracks.size(); i++) { 4234 mOutputTracks[i]->destroy(); 4235 } 4236} 4237 4238void AudioFlinger::DuplicatingThread::threadLoop_mix() 4239{ 4240 // mix buffers... 4241 if (outputsReady(outputTracks)) { 4242 mAudioMixer->process(AudioBufferProvider::kInvalidPTS); 4243 } else { 4244 memset(mMixBuffer, 0, mixBufferSize); 4245 } 4246 sleepTime = 0; 4247 writeFrames = mNormalFrameCount; 4248 mCurrentWriteLength = mixBufferSize; 4249 standbyTime = systemTime() + standbyDelay; 4250} 4251 4252void AudioFlinger::DuplicatingThread::threadLoop_sleepTime() 4253{ 4254 if (sleepTime == 0) { 4255 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 4256 sleepTime = activeSleepTime; 4257 } else { 4258 sleepTime = idleSleepTime; 4259 } 4260 } else if (mBytesWritten != 0) { 4261 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 4262 writeFrames = mNormalFrameCount; 4263 memset(mMixBuffer, 0, mixBufferSize); 4264 } else { 4265 // flush remaining overflow buffers in output tracks 4266 writeFrames = 0; 4267 } 4268 sleepTime = 0; 4269 } 4270} 4271 4272ssize_t AudioFlinger::DuplicatingThread::threadLoop_write() 4273{ 4274 for (size_t i = 0; i < outputTracks.size(); i++) { 4275 outputTracks[i]->write(mMixBuffer, writeFrames); 4276 } 4277 mStandby = false; 4278 return (ssize_t)mixBufferSize; 4279} 4280 4281void AudioFlinger::DuplicatingThread::threadLoop_standby() 4282{ 4283 // DuplicatingThread implements standby by stopping all tracks 4284 for (size_t i = 0; i < outputTracks.size(); i++) { 4285 outputTracks[i]->stop(); 4286 } 4287} 4288 4289void AudioFlinger::DuplicatingThread::saveOutputTracks() 4290{ 4291 outputTracks = mOutputTracks; 4292} 4293 4294void AudioFlinger::DuplicatingThread::clearOutputTracks() 4295{ 4296 outputTracks.clear(); 4297} 4298 4299void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread) 4300{ 4301 Mutex::Autolock _l(mLock); 4302 // FIXME explain this formula 4303 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate(); 4304 OutputTrack *outputTrack = new OutputTrack(thread, 4305 this, 4306 mSampleRate, 4307 mFormat, 4308 mChannelMask, 4309 frameCount, 4310 IPCThreadState::self()->getCallingUid()); 4311 if (outputTrack->cblk() != NULL) { 4312 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f); 4313 mOutputTracks.add(outputTrack); 4314 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread); 4315 updateWaitTime_l(); 4316 } 4317} 4318 4319void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread) 4320{ 4321 Mutex::Autolock _l(mLock); 4322 for (size_t i = 0; i < mOutputTracks.size(); i++) { 4323 if (mOutputTracks[i]->thread() == thread) { 4324 mOutputTracks[i]->destroy(); 4325 mOutputTracks.removeAt(i); 4326 updateWaitTime_l(); 4327 return; 4328 } 4329 } 4330 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread); 4331} 4332 4333// caller must hold mLock 4334void AudioFlinger::DuplicatingThread::updateWaitTime_l() 4335{ 4336 mWaitTimeMs = UINT_MAX; 4337 for (size_t i = 0; i < mOutputTracks.size(); i++) { 4338 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote(); 4339 if (strong != 0) { 4340 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate(); 4341 if (waitTimeMs < mWaitTimeMs) { 4342 mWaitTimeMs = waitTimeMs; 4343 } 4344 } 4345 } 4346} 4347 4348 4349bool AudioFlinger::DuplicatingThread::outputsReady( 4350 const SortedVector< sp<OutputTrack> > &outputTracks) 4351{ 4352 for (size_t i = 0; i < outputTracks.size(); i++) { 4353 sp<ThreadBase> thread = outputTracks[i]->thread().promote(); 4354 if (thread == 0) { 4355 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", 4356 outputTracks[i].get()); 4357 return false; 4358 } 4359 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 4360 // see note at standby() declaration 4361 if (playbackThread->standby() && !playbackThread->isSuspended()) { 4362 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), 4363 thread.get()); 4364 return false; 4365 } 4366 } 4367 return true; 4368} 4369 4370uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const 4371{ 4372 return (mWaitTimeMs * 1000) / 2; 4373} 4374 4375void AudioFlinger::DuplicatingThread::cacheParameters_l() 4376{ 4377 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first 4378 updateWaitTime_l(); 4379 4380 MixerThread::cacheParameters_l(); 4381} 4382 4383// ---------------------------------------------------------------------------- 4384// Record 4385// ---------------------------------------------------------------------------- 4386 4387AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, 4388 AudioStreamIn *input, 4389 uint32_t sampleRate, 4390 audio_channel_mask_t channelMask, 4391 audio_io_handle_t id, 4392 audio_devices_t outDevice, 4393 audio_devices_t inDevice 4394#ifdef TEE_SINK 4395 , const sp<NBAIO_Sink>& teeSink 4396#endif 4397 ) : 4398 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD), 4399 mInput(input), mActiveTracksGen(0), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL), 4400 // mRsmpInFrames, mRsmpInFramesP2, mRsmpInUnrel, mRsmpInFront, and mRsmpInRear 4401 // are set by readInputParameters() 4402 // mRsmpInIndex LEGACY 4403 mReqChannelCount(popcount(channelMask)), 4404 mReqSampleRate(sampleRate) 4405 // mBytesRead is only meaningful while active, and so is cleared in start() 4406 // (but might be better to also clear here for dump?) 4407#ifdef TEE_SINK 4408 , mTeeSink(teeSink) 4409#endif 4410{ 4411 snprintf(mName, kNameLength, "AudioIn_%X", id); 4412 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName); 4413 4414 readInputParameters(); 4415} 4416 4417 4418AudioFlinger::RecordThread::~RecordThread() 4419{ 4420 mAudioFlinger->unregisterWriter(mNBLogWriter); 4421 delete[] mRsmpInBuffer; 4422 delete mResampler; 4423 delete[] mRsmpOutBuffer; 4424} 4425 4426void AudioFlinger::RecordThread::onFirstRef() 4427{ 4428 run(mName, PRIORITY_URGENT_AUDIO); 4429} 4430 4431bool AudioFlinger::RecordThread::threadLoop() 4432{ 4433 nsecs_t lastWarning = 0; 4434 4435 inputStandBy(); 4436 4437 // used to verify we've read at least once before evaluating how many bytes were read 4438 bool readOnce = false; 4439 4440 // used to request a deferred sleep, to be executed later while mutex is unlocked 4441 bool doSleep = false; 4442 4443reacquire_wakelock: 4444 sp<RecordTrack> activeTrack; 4445 int activeTracksGen; 4446 { 4447 Mutex::Autolock _l(mLock); 4448 size_t size = mActiveTracks.size(); 4449 activeTracksGen = mActiveTracksGen; 4450 if (size > 0) { 4451 // FIXME an arbitrary choice 4452 activeTrack = mActiveTracks[0]; 4453 acquireWakeLock_l(activeTrack->uid()); 4454 if (size > 1) { 4455 SortedVector<int> tmp; 4456 for (size_t i = 0; i < size; i++) { 4457 tmp.add(mActiveTracks[i]->uid()); 4458 } 4459 updateWakeLockUids_l(tmp); 4460 } 4461 } else { 4462 acquireWakeLock_l(-1); 4463 } 4464 } 4465 4466 // start recording 4467 for (;;) { 4468 TrackBase::track_state activeTrackState; 4469 Vector< sp<EffectChain> > effectChains; 4470 4471 // sleep with mutex unlocked 4472 if (doSleep) { 4473 doSleep = false; 4474 usleep(kRecordThreadSleepUs); 4475 } 4476 4477 { // scope for mLock 4478 Mutex::Autolock _l(mLock); 4479 if (exitPending()) { 4480 break; 4481 } 4482 processConfigEvents_l(); 4483 // return value 'reconfig' is currently unused 4484 bool reconfig = checkForNewParameters_l(); 4485 4486 // if no active track(s), then standby and release wakelock 4487 size_t size = mActiveTracks.size(); 4488 if (size == 0) { 4489 standbyIfNotAlreadyInStandby(); 4490 // exitPending() can't become true here 4491 releaseWakeLock_l(); 4492 ALOGV("RecordThread: loop stopping"); 4493 // go to sleep 4494 mWaitWorkCV.wait(mLock); 4495 ALOGV("RecordThread: loop starting"); 4496 goto reacquire_wakelock; 4497 } 4498 4499 if (mActiveTracksGen != activeTracksGen) { 4500 activeTracksGen = mActiveTracksGen; 4501 SortedVector<int> tmp; 4502 for (size_t i = 0; i < size; i++) { 4503 tmp.add(mActiveTracks[i]->uid()); 4504 } 4505 updateWakeLockUids_l(tmp); 4506 // FIXME an arbitrary choice 4507 activeTrack = mActiveTracks[0]; 4508 } 4509 4510 if (activeTrack->isTerminated()) { 4511 removeTrack_l(activeTrack); 4512 mActiveTracks.remove(activeTrack); 4513 mActiveTracksGen++; 4514 continue; 4515 } 4516 4517 activeTrackState = activeTrack->mState; 4518 switch (activeTrackState) { 4519 case TrackBase::PAUSING: 4520 standbyIfNotAlreadyInStandby(); 4521 mActiveTracks.remove(activeTrack); 4522 mActiveTracksGen++; 4523 mStartStopCond.broadcast(); 4524 doSleep = true; 4525 continue; 4526 4527 case TrackBase::RESUMING: 4528 mStandby = false; 4529 if (mReqChannelCount != activeTrack->channelCount()) { 4530 mActiveTracks.remove(activeTrack); 4531 mActiveTracksGen++; 4532 mStartStopCond.broadcast(); 4533 continue; 4534 } 4535 if (readOnce) { 4536 mStartStopCond.broadcast(); 4537 // record start succeeds only if first read from audio input succeeds 4538 if (mBytesRead < 0) { 4539 mActiveTracks.remove(activeTrack); 4540 mActiveTracksGen++; 4541 continue; 4542 } 4543 activeTrack->mState = TrackBase::ACTIVE; 4544 } 4545 break; 4546 4547 case TrackBase::ACTIVE: 4548 break; 4549 4550 case TrackBase::IDLE: 4551 doSleep = true; 4552 continue; 4553 4554 default: 4555 LOG_FATAL("Unexpected activeTrackState %d", activeTrackState); 4556 } 4557 4558 lockEffectChains_l(effectChains); 4559 } 4560 4561 // thread mutex is now unlocked, mActiveTracks unknown, activeTrack != 0, kept, immutable 4562 // activeTrack->mState unknown, activeTrackState immutable and is ACTIVE or RESUMING 4563 4564 for (size_t i = 0; i < effectChains.size(); i ++) { 4565 // thread mutex is not locked, but effect chain is locked 4566 effectChains[i]->process_l(); 4567 } 4568 4569 AudioBufferProvider::Buffer buffer; 4570 buffer.frameCount = mFrameCount; 4571 status_t status = activeTrack->getNextBuffer(&buffer); 4572 if (status == NO_ERROR) { 4573 readOnce = true; 4574 size_t framesOut = buffer.frameCount; 4575 if (mResampler == NULL) { 4576 // no resampling 4577 while (framesOut) { 4578 size_t framesIn = mFrameCount - mRsmpInIndex; 4579 if (framesIn > 0) { 4580 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize; 4581 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * 4582 activeTrack->mFrameSize; 4583 if (framesIn > framesOut) { 4584 framesIn = framesOut; 4585 } 4586 mRsmpInIndex += framesIn; 4587 framesOut -= framesIn; 4588 if (mChannelCount == mReqChannelCount) { 4589 memcpy(dst, src, framesIn * mFrameSize); 4590 } else { 4591 if (mChannelCount == 1) { 4592 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, 4593 (int16_t *)src, framesIn); 4594 } else { 4595 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, 4596 (int16_t *)src, framesIn); 4597 } 4598 } 4599 } 4600 if (framesOut > 0 && mFrameCount == mRsmpInIndex) { 4601 void *readInto; 4602 if (framesOut == mFrameCount && mChannelCount == mReqChannelCount) { 4603 readInto = buffer.raw; 4604 framesOut = 0; 4605 } else { 4606 readInto = mRsmpInBuffer; 4607 mRsmpInIndex = 0; 4608 } 4609 mBytesRead = mInput->stream->read(mInput->stream, readInto, 4610 mBufferSize); 4611 if (mBytesRead <= 0) { 4612 // TODO: verify that it's benign to use a stale track state 4613 if ((mBytesRead < 0) && (activeTrackState == TrackBase::ACTIVE)) 4614 { 4615 ALOGE("Error reading audio input"); 4616 // Force input into standby so that it tries to 4617 // recover at next read attempt 4618 inputStandBy(); 4619 doSleep = true; 4620 } 4621 mRsmpInIndex = mFrameCount; 4622 framesOut = 0; 4623 buffer.frameCount = 0; 4624 } 4625#ifdef TEE_SINK 4626 else if (mTeeSink != 0) { 4627 (void) mTeeSink->write(readInto, 4628 mBytesRead >> Format_frameBitShift(mTeeSink->format())); 4629 } 4630#endif 4631 } 4632 } 4633 } else { 4634 // resampling 4635 4636 // avoid busy-waiting if client doesn't keep up 4637 bool madeProgress = false; 4638 4639 // keep mRsmpInBuffer full so resampler always has sufficient input 4640 for (;;) { 4641 int32_t rear = mRsmpInRear; 4642 ssize_t filled = rear - mRsmpInFront; 4643 ALOG_ASSERT(0 <= filled && (size_t) filled <= mRsmpInFramesP2); 4644 // exit once there is enough data in buffer for resampler 4645 if ((size_t) filled >= mRsmpInFrames) { 4646 break; 4647 } 4648 size_t avail = mRsmpInFramesP2 - filled; 4649 // Only try to read full HAL buffers. 4650 // But if the HAL read returns a partial buffer, use it. 4651 if (avail < mFrameCount) { 4652 ALOGE("insufficient space to read: avail %d < mFrameCount %d", 4653 avail, mFrameCount); 4654 break; 4655 } 4656 // If 'avail' is non-contiguous, first read past the nominal end of buffer, then 4657 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated. 4658 rear &= mRsmpInFramesP2 - 1; 4659 mBytesRead = mInput->stream->read(mInput->stream, 4660 &mRsmpInBuffer[rear * mChannelCount], mBufferSize); 4661 if (mBytesRead <= 0) { 4662 ALOGE("read failed: mBytesRead=%d < %u", mBytesRead, mBufferSize); 4663 break; 4664 } 4665 ALOG_ASSERT((size_t) mBytesRead <= mBufferSize); 4666 size_t framesRead = mBytesRead / mFrameSize; 4667 ALOG_ASSERT(framesRead > 0); 4668 madeProgress = true; 4669 // If 'avail' was non-contiguous, we now correct for reading past end of buffer. 4670 size_t part1 = mRsmpInFramesP2 - rear; 4671 if (framesRead > part1) { 4672 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount], 4673 (framesRead - part1) * mFrameSize); 4674 } 4675 mRsmpInRear += framesRead; 4676 } 4677 4678 if (!madeProgress) { 4679 ALOGV("Did not make progress"); 4680 usleep(((mFrameCount * 1000) / mSampleRate) * 1000); 4681 } 4682 4683 // resampler accumulates, but we only have one source track 4684 memset(mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t)); 4685 mResampler->resample(mRsmpOutBuffer, framesOut, 4686 this /* AudioBufferProvider* */); 4687 // ditherAndClamp() works as long as all buffers returned by 4688 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true. 4689 if (mReqChannelCount == 1) { 4690 // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t 4691 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut); 4692 // the resampler always outputs stereo samples: 4693 // do post stereo to mono conversion 4694 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer, 4695 framesOut); 4696 } else { 4697 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut); 4698 } 4699 // now done with mRsmpOutBuffer 4700 4701 } 4702 if (mFramestoDrop == 0) { 4703 activeTrack->releaseBuffer(&buffer); 4704 } else { 4705 if (mFramestoDrop > 0) { 4706 mFramestoDrop -= buffer.frameCount; 4707 if (mFramestoDrop <= 0) { 4708 clearSyncStartEvent(); 4709 } 4710 } else { 4711 mFramestoDrop += buffer.frameCount; 4712 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 || 4713 mSyncStartEvent->isCancelled()) { 4714 ALOGW("Synced record %s, session %d, trigger session %d", 4715 (mFramestoDrop >= 0) ? "timed out" : "cancelled", 4716 activeTrack->sessionId(), 4717 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0); 4718 clearSyncStartEvent(); 4719 } 4720 } 4721 } 4722 activeTrack->clearOverflow(); 4723 } 4724 // client isn't retrieving buffers fast enough 4725 else { 4726 if (!activeTrack->setOverflow()) { 4727 nsecs_t now = systemTime(); 4728 if ((now - lastWarning) > kWarningThrottleNs) { 4729 ALOGW("RecordThread: buffer overflow"); 4730 lastWarning = now; 4731 } 4732 } 4733 // Release the processor for a while before asking for a new buffer. 4734 // This will give the application more chance to read from the buffer and 4735 // clear the overflow. 4736 doSleep = true; 4737 } 4738 4739 // enable changes in effect chain 4740 unlockEffectChains(effectChains); 4741 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end 4742 } 4743 4744 standbyIfNotAlreadyInStandby(); 4745 4746 { 4747 Mutex::Autolock _l(mLock); 4748 for (size_t i = 0; i < mTracks.size(); i++) { 4749 sp<RecordTrack> track = mTracks[i]; 4750 track->invalidate(); 4751 } 4752 mActiveTracks.clear(); 4753 mActiveTracksGen++; 4754 mStartStopCond.broadcast(); 4755 } 4756 4757 releaseWakeLock(); 4758 4759 ALOGV("RecordThread %p exiting", this); 4760 return false; 4761} 4762 4763void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby() 4764{ 4765 if (!mStandby) { 4766 inputStandBy(); 4767 mStandby = true; 4768 } 4769} 4770 4771void AudioFlinger::RecordThread::inputStandBy() 4772{ 4773 mInput->stream->common.standby(&mInput->stream->common); 4774} 4775 4776sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l( 4777 const sp<AudioFlinger::Client>& client, 4778 uint32_t sampleRate, 4779 audio_format_t format, 4780 audio_channel_mask_t channelMask, 4781 size_t frameCount, 4782 int sessionId, 4783 int uid, 4784 IAudioFlinger::track_flags_t *flags, 4785 pid_t tid, 4786 status_t *status) 4787{ 4788 sp<RecordTrack> track; 4789 status_t lStatus; 4790 4791 lStatus = initCheck(); 4792 if (lStatus != NO_ERROR) { 4793 ALOGE("createRecordTrack_l() audio driver not initialized"); 4794 goto Exit; 4795 } 4796 // client expresses a preference for FAST, but we get the final say 4797 if (*flags & IAudioFlinger::TRACK_FAST) { 4798 if ( 4799 // use case: callback handler and frame count is default or at least as large as HAL 4800 ( 4801 (tid != -1) && 4802 ((frameCount == 0) || 4803 (frameCount >= (mFrameCount * kFastTrackMultiplier))) 4804 ) && 4805 // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format) 4806 // mono or stereo 4807 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) || 4808 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) && 4809 // hardware sample rate 4810 (sampleRate == mSampleRate) && 4811 // record thread has an associated fast recorder 4812 hasFastRecorder() 4813 // FIXME test that RecordThread for this fast track has a capable output HAL 4814 // FIXME add a permission test also? 4815 ) { 4816 // if frameCount not specified, then it defaults to fast recorder (HAL) frame count 4817 if (frameCount == 0) { 4818 frameCount = mFrameCount * kFastTrackMultiplier; 4819 } 4820 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d", 4821 frameCount, mFrameCount); 4822 } else { 4823 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d " 4824 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u " 4825 "hasFastRecorder=%d tid=%d", 4826 frameCount, mFrameCount, format, 4827 audio_is_linear_pcm(format), 4828 channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid); 4829 *flags &= ~IAudioFlinger::TRACK_FAST; 4830 // For compatibility with AudioRecord calculation, buffer depth is forced 4831 // to be at least 2 x the record thread frame count and cover audio hardware latency. 4832 // This is probably too conservative, but legacy application code may depend on it. 4833 // If you change this calculation, also review the start threshold which is related. 4834 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream); 4835 size_t mNormalFrameCount = 2048; // FIXME 4836 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate); 4837 if (minBufCount < 2) { 4838 minBufCount = 2; 4839 } 4840 size_t minFrameCount = mNormalFrameCount * minBufCount; 4841 if (frameCount < minFrameCount) { 4842 frameCount = minFrameCount; 4843 } 4844 } 4845 } 4846 4847 // FIXME use flags and tid similar to createTrack_l() 4848 4849 { // scope for mLock 4850 Mutex::Autolock _l(mLock); 4851 4852 track = new RecordTrack(this, client, sampleRate, 4853 format, channelMask, frameCount, sessionId, uid); 4854 4855 lStatus = track->initCheck(); 4856 if (lStatus != NO_ERROR) { 4857 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus); 4858 track.clear(); 4859 goto Exit; 4860 } 4861 mTracks.add(track); 4862 4863 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 4864 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 4865 mAudioFlinger->btNrecIsOff(); 4866 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId); 4867 setEffectSuspended_l(FX_IID_NS, suspend, sessionId); 4868 4869 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) { 4870 pid_t callingPid = IPCThreadState::self()->getCallingPid(); 4871 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful, 4872 // so ask activity manager to do this on our behalf 4873 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp); 4874 } 4875 } 4876 lStatus = NO_ERROR; 4877 4878Exit: 4879 *status = lStatus; 4880 return track; 4881} 4882 4883status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, 4884 AudioSystem::sync_event_t event, 4885 int triggerSession) 4886{ 4887 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession); 4888 sp<ThreadBase> strongMe = this; 4889 status_t status = NO_ERROR; 4890 4891 if (event == AudioSystem::SYNC_EVENT_NONE) { 4892 clearSyncStartEvent(); 4893 } else if (event != AudioSystem::SYNC_EVENT_SAME) { 4894 mSyncStartEvent = mAudioFlinger->createSyncEvent(event, 4895 triggerSession, 4896 recordTrack->sessionId(), 4897 syncStartEventCallback, 4898 this); 4899 // Sync event can be cancelled by the trigger session if the track is not in a 4900 // compatible state in which case we start record immediately 4901 if (mSyncStartEvent->isCancelled()) { 4902 clearSyncStartEvent(); 4903 } else { 4904 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs 4905 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000); 4906 } 4907 } 4908 4909 { 4910 // This section is a rendezvous between binder thread executing start() and RecordThread 4911 AutoMutex lock(mLock); 4912 if (mActiveTracks.size() > 0) { 4913 // FIXME does not work for multiple active tracks 4914 if (mActiveTracks.indexOf(recordTrack) != 0) { 4915 status = -EBUSY; 4916 } else if (recordTrack->mState == TrackBase::PAUSING) { 4917 recordTrack->mState = TrackBase::ACTIVE; 4918 } 4919 return status; 4920 } 4921 4922 // FIXME why? already set in constructor, 'STARTING_1' would be more accurate 4923 recordTrack->mState = TrackBase::IDLE; 4924 mActiveTracks.add(recordTrack); 4925 mActiveTracksGen++; 4926 mLock.unlock(); 4927 status_t status = AudioSystem::startInput(mId); 4928 mLock.lock(); 4929 // FIXME should verify that mActiveTrack is still == recordTrack 4930 if (status != NO_ERROR) { 4931 mActiveTracks.remove(recordTrack); 4932 mActiveTracksGen++; 4933 clearSyncStartEvent(); 4934 return status; 4935 } 4936 // FIXME LEGACY 4937 mRsmpInIndex = mFrameCount; 4938 mRsmpInFront = 0; 4939 mRsmpInRear = 0; 4940 mRsmpInUnrel = 0; 4941 mBytesRead = 0; 4942 if (mResampler != NULL) { 4943 mResampler->reset(); 4944 } 4945 // FIXME hijacking a playback track state name which was intended for start after pause; 4946 // here 'STARTING_2' would be more accurate 4947 recordTrack->mState = TrackBase::RESUMING; 4948 // signal thread to start 4949 ALOGV("Signal record thread"); 4950 mWaitWorkCV.broadcast(); 4951 // do not wait for mStartStopCond if exiting 4952 if (exitPending()) { 4953 mActiveTracks.remove(recordTrack); 4954 mActiveTracksGen++; 4955 status = INVALID_OPERATION; 4956 goto startError; 4957 } 4958 // FIXME incorrect usage of wait: no explicit predicate or loop 4959 mStartStopCond.wait(mLock); 4960 if (mActiveTracks.indexOf(recordTrack) < 0) { 4961 ALOGV("Record failed to start"); 4962 status = BAD_VALUE; 4963 goto startError; 4964 } 4965 ALOGV("Record started OK"); 4966 return status; 4967 } 4968 4969startError: 4970 AudioSystem::stopInput(mId); 4971 clearSyncStartEvent(); 4972 return status; 4973} 4974 4975void AudioFlinger::RecordThread::clearSyncStartEvent() 4976{ 4977 if (mSyncStartEvent != 0) { 4978 mSyncStartEvent->cancel(); 4979 } 4980 mSyncStartEvent.clear(); 4981 mFramestoDrop = 0; 4982} 4983 4984void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event) 4985{ 4986 sp<SyncEvent> strongEvent = event.promote(); 4987 4988 if (strongEvent != 0) { 4989 RecordThread *me = (RecordThread *)strongEvent->cookie(); 4990 me->handleSyncStartEvent(strongEvent); 4991 } 4992} 4993 4994void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event) 4995{ 4996 if (event == mSyncStartEvent) { 4997 // TODO: use actual buffer filling status instead of 2 buffers when info is available 4998 // from audio HAL 4999 mFramestoDrop = mFrameCount * 2; 5000 } 5001} 5002 5003bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) { 5004 ALOGV("RecordThread::stop"); 5005 AutoMutex _l(mLock); 5006 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) { 5007 return false; 5008 } 5009 // note that threadLoop may still be processing the track at this point [without lock] 5010 recordTrack->mState = TrackBase::PAUSING; 5011 // do not wait for mStartStopCond if exiting 5012 if (exitPending()) { 5013 return true; 5014 } 5015 // FIXME incorrect usage of wait: no explicit predicate or loop 5016 mStartStopCond.wait(mLock); 5017 // if we have been restarted, recordTrack is in mActiveTracks here 5018 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) { 5019 ALOGV("Record stopped OK"); 5020 return true; 5021 } 5022 return false; 5023} 5024 5025bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const 5026{ 5027 return false; 5028} 5029 5030status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event) 5031{ 5032#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future 5033 if (!isValidSyncEvent(event)) { 5034 return BAD_VALUE; 5035 } 5036 5037 int eventSession = event->triggerSession(); 5038 status_t ret = NAME_NOT_FOUND; 5039 5040 Mutex::Autolock _l(mLock); 5041 5042 for (size_t i = 0; i < mTracks.size(); i++) { 5043 sp<RecordTrack> track = mTracks[i]; 5044 if (eventSession == track->sessionId()) { 5045 (void) track->setSyncEvent(event); 5046 ret = NO_ERROR; 5047 } 5048 } 5049 return ret; 5050#else 5051 return BAD_VALUE; 5052#endif 5053} 5054 5055// destroyTrack_l() must be called with ThreadBase::mLock held 5056void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track) 5057{ 5058 track->terminate(); 5059 track->mState = TrackBase::STOPPED; 5060 // active tracks are removed by threadLoop() 5061 if (mActiveTracks.indexOf(track) < 0) { 5062 removeTrack_l(track); 5063 } 5064} 5065 5066void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track) 5067{ 5068 mTracks.remove(track); 5069 // need anything related to effects here? 5070} 5071 5072void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args) 5073{ 5074 dumpInternals(fd, args); 5075 dumpTracks(fd, args); 5076 dumpEffectChains(fd, args); 5077} 5078 5079void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args) 5080{ 5081 const size_t SIZE = 256; 5082 char buffer[SIZE]; 5083 String8 result; 5084 5085 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this); 5086 result.append(buffer); 5087 5088 if (mActiveTracks.size() > 0) { 5089 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex); 5090 result.append(buffer); 5091 snprintf(buffer, SIZE, "Buffer size: %u bytes\n", mBufferSize); 5092 result.append(buffer); 5093 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL)); 5094 result.append(buffer); 5095 snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount); 5096 result.append(buffer); 5097 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate); 5098 result.append(buffer); 5099 } else { 5100 result.append("No active record client\n"); 5101 } 5102 5103 write(fd, result.string(), result.size()); 5104 5105 dumpBase(fd, args); 5106} 5107 5108void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args) 5109{ 5110 const size_t SIZE = 256; 5111 char buffer[SIZE]; 5112 String8 result; 5113 5114 snprintf(buffer, SIZE, "Input thread %p tracks\n", this); 5115 result.append(buffer); 5116 RecordTrack::appendDumpHeader(result); 5117 for (size_t i = 0; i < mTracks.size(); ++i) { 5118 sp<RecordTrack> track = mTracks[i]; 5119 if (track != 0) { 5120 track->dump(buffer, SIZE); 5121 result.append(buffer); 5122 } 5123 } 5124 5125 size_t size = mActiveTracks.size(); 5126 if (size > 0) { 5127 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this); 5128 result.append(buffer); 5129 RecordTrack::appendDumpHeader(result); 5130 for (size_t i = 0; i < size; ++i) { 5131 sp<RecordTrack> track = mActiveTracks[i]; 5132 track->dump(buffer, SIZE); 5133 result.append(buffer); 5134 } 5135 5136 } 5137 write(fd, result.string(), result.size()); 5138} 5139 5140// AudioBufferProvider interface 5141status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts) 5142{ 5143 int32_t rear = mRsmpInRear; 5144 int32_t front = mRsmpInFront; 5145 ssize_t filled = rear - front; 5146 ALOG_ASSERT(0 <= filled && (size_t) filled <= mRsmpInFramesP2); 5147 // 'filled' may be non-contiguous, so return only the first contiguous chunk 5148 front &= mRsmpInFramesP2 - 1; 5149 size_t part1 = mRsmpInFramesP2 - front; 5150 if (part1 > (size_t) filled) { 5151 part1 = filled; 5152 } 5153 size_t ask = buffer->frameCount; 5154 ALOG_ASSERT(ask > 0); 5155 if (part1 > ask) { 5156 part1 = ask; 5157 } 5158 if (part1 == 0) { 5159 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty 5160 ALOGE("RecordThread::getNextBuffer() starved"); 5161 buffer->raw = NULL; 5162 buffer->frameCount = 0; 5163 mRsmpInUnrel = 0; 5164 return NOT_ENOUGH_DATA; 5165 } 5166 5167 buffer->raw = mRsmpInBuffer + front * mChannelCount; 5168 buffer->frameCount = part1; 5169 mRsmpInUnrel = part1; 5170 return NO_ERROR; 5171} 5172 5173// AudioBufferProvider interface 5174void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer) 5175{ 5176 size_t stepCount = buffer->frameCount; 5177 if (stepCount == 0) { 5178 return; 5179 } 5180 ALOG_ASSERT(stepCount <= mRsmpInUnrel); 5181 mRsmpInUnrel -= stepCount; 5182 mRsmpInFront += stepCount; 5183 buffer->raw = NULL; 5184 buffer->frameCount = 0; 5185} 5186 5187bool AudioFlinger::RecordThread::checkForNewParameters_l() 5188{ 5189 bool reconfig = false; 5190 5191 while (!mNewParameters.isEmpty()) { 5192 status_t status = NO_ERROR; 5193 String8 keyValuePair = mNewParameters[0]; 5194 AudioParameter param = AudioParameter(keyValuePair); 5195 int value; 5196 audio_format_t reqFormat = mFormat; 5197 uint32_t reqSamplingRate = mReqSampleRate; 5198 audio_channel_mask_t reqChannelMask = audio_channel_in_mask_from_count(mReqChannelCount); 5199 5200 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { 5201 reqSamplingRate = value; 5202 reconfig = true; 5203 } 5204 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { 5205 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) { 5206 status = BAD_VALUE; 5207 } else { 5208 reqFormat = (audio_format_t) value; 5209 reconfig = true; 5210 } 5211 } 5212 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { 5213 audio_channel_mask_t mask = (audio_channel_mask_t) value; 5214 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) { 5215 status = BAD_VALUE; 5216 } else { 5217 reqChannelMask = mask; 5218 reconfig = true; 5219 } 5220 } 5221 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 5222 // do not accept frame count changes if tracks are open as the track buffer 5223 // size depends on frame count and correct behavior would not be guaranteed 5224 // if frame count is changed after track creation 5225 if (mActiveTracks.size() > 0) { 5226 status = INVALID_OPERATION; 5227 } else { 5228 reconfig = true; 5229 } 5230 } 5231 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 5232 // forward device change to effects that have requested to be 5233 // aware of attached audio device. 5234 for (size_t i = 0; i < mEffectChains.size(); i++) { 5235 mEffectChains[i]->setDevice_l(value); 5236 } 5237 5238 // store input device and output device but do not forward output device to audio HAL. 5239 // Note that status is ignored by the caller for output device 5240 // (see AudioFlinger::setParameters() 5241 if (audio_is_output_devices(value)) { 5242 mOutDevice = value; 5243 status = BAD_VALUE; 5244 } else { 5245 mInDevice = value; 5246 // disable AEC and NS if the device is a BT SCO headset supporting those 5247 // pre processings 5248 if (mTracks.size() > 0) { 5249 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 5250 mAudioFlinger->btNrecIsOff(); 5251 for (size_t i = 0; i < mTracks.size(); i++) { 5252 sp<RecordTrack> track = mTracks[i]; 5253 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId()); 5254 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId()); 5255 } 5256 } 5257 } 5258 } 5259 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR && 5260 mAudioSource != (audio_source_t)value) { 5261 // forward device change to effects that have requested to be 5262 // aware of attached audio device. 5263 for (size_t i = 0; i < mEffectChains.size(); i++) { 5264 mEffectChains[i]->setAudioSource_l((audio_source_t)value); 5265 } 5266 mAudioSource = (audio_source_t)value; 5267 } 5268 5269 if (status == NO_ERROR) { 5270 status = mInput->stream->common.set_parameters(&mInput->stream->common, 5271 keyValuePair.string()); 5272 if (status == INVALID_OPERATION) { 5273 inputStandBy(); 5274 status = mInput->stream->common.set_parameters(&mInput->stream->common, 5275 keyValuePair.string()); 5276 } 5277 if (reconfig) { 5278 if (status == BAD_VALUE && 5279 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) && 5280 reqFormat == AUDIO_FORMAT_PCM_16_BIT && 5281 (mInput->stream->common.get_sample_rate(&mInput->stream->common) 5282 <= (2 * reqSamplingRate)) && 5283 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) 5284 <= FCC_2 && 5285 (reqChannelMask == AUDIO_CHANNEL_IN_MONO || 5286 reqChannelMask == AUDIO_CHANNEL_IN_STEREO)) { 5287 status = NO_ERROR; 5288 } 5289 if (status == NO_ERROR) { 5290 readInputParameters(); 5291 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED); 5292 } 5293 } 5294 } 5295 5296 mNewParameters.removeAt(0); 5297 5298 mParamStatus = status; 5299 mParamCond.signal(); 5300 // wait for condition with time out in case the thread calling ThreadBase::setParameters() 5301 // already timed out waiting for the status and will never signal the condition. 5302 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); 5303 } 5304 return reconfig; 5305} 5306 5307String8 AudioFlinger::RecordThread::getParameters(const String8& keys) 5308{ 5309 Mutex::Autolock _l(mLock); 5310 if (initCheck() != NO_ERROR) { 5311 return String8(); 5312 } 5313 5314 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string()); 5315 const String8 out_s8(s); 5316 free(s); 5317 return out_s8; 5318} 5319 5320void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) { 5321 AudioSystem::OutputDescriptor desc; 5322 const void *param2 = NULL; 5323 5324 switch (event) { 5325 case AudioSystem::INPUT_OPENED: 5326 case AudioSystem::INPUT_CONFIG_CHANGED: 5327 desc.channelMask = mChannelMask; 5328 desc.samplingRate = mSampleRate; 5329 desc.format = mFormat; 5330 desc.frameCount = mFrameCount; 5331 desc.latency = 0; 5332 param2 = &desc; 5333 break; 5334 5335 case AudioSystem::INPUT_CLOSED: 5336 default: 5337 break; 5338 } 5339 mAudioFlinger->audioConfigChanged_l(event, mId, param2); 5340} 5341 5342void AudioFlinger::RecordThread::readInputParameters() 5343{ 5344 delete[] mRsmpInBuffer; 5345 // mRsmpInBuffer is always assigned a new[] below 5346 delete[] mRsmpOutBuffer; 5347 mRsmpOutBuffer = NULL; 5348 delete mResampler; 5349 mResampler = NULL; 5350 5351 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common); 5352 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common); 5353 mChannelCount = popcount(mChannelMask); 5354 mFormat = mInput->stream->common.get_format(&mInput->stream->common); 5355 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) { 5356 ALOGE("HAL format %d not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat); 5357 } 5358 mFrameSize = audio_stream_frame_size(&mInput->stream->common); 5359 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common); 5360 mFrameCount = mBufferSize / mFrameSize; 5361 // With 3 HAL buffers, we can guarantee ability to down-sample the input by ratio of 2:1 to 5362 // 1 full output buffer, regardless of the alignment of the available input. 5363 mRsmpInFrames = mFrameCount * 3; 5364 mRsmpInFramesP2 = roundup(mRsmpInFrames); 5365 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer 5366 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount]; 5367 mRsmpInFront = 0; 5368 mRsmpInRear = 0; 5369 mRsmpInUnrel = 0; 5370 5371 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2) { 5372 mResampler = AudioResampler::create(16, (int) mChannelCount, mReqSampleRate); 5373 mResampler->setSampleRate(mSampleRate); 5374 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN); 5375 // resampler always outputs stereo 5376 mRsmpOutBuffer = new int32_t[mFrameCount * FCC_2]; 5377 } 5378 mRsmpInIndex = mFrameCount; 5379} 5380 5381unsigned int AudioFlinger::RecordThread::getInputFramesLost() 5382{ 5383 Mutex::Autolock _l(mLock); 5384 if (initCheck() != NO_ERROR) { 5385 return 0; 5386 } 5387 5388 return mInput->stream->get_input_frames_lost(mInput->stream); 5389} 5390 5391uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const 5392{ 5393 Mutex::Autolock _l(mLock); 5394 uint32_t result = 0; 5395 if (getEffectChain_l(sessionId) != 0) { 5396 result = EFFECT_SESSION; 5397 } 5398 5399 for (size_t i = 0; i < mTracks.size(); ++i) { 5400 if (sessionId == mTracks[i]->sessionId()) { 5401 result |= TRACK_SESSION; 5402 break; 5403 } 5404 } 5405 5406 return result; 5407} 5408 5409KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const 5410{ 5411 KeyedVector<int, bool> ids; 5412 Mutex::Autolock _l(mLock); 5413 for (size_t j = 0; j < mTracks.size(); ++j) { 5414 sp<RecordThread::RecordTrack> track = mTracks[j]; 5415 int sessionId = track->sessionId(); 5416 if (ids.indexOfKey(sessionId) < 0) { 5417 ids.add(sessionId, true); 5418 } 5419 } 5420 return ids; 5421} 5422 5423AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput() 5424{ 5425 Mutex::Autolock _l(mLock); 5426 AudioStreamIn *input = mInput; 5427 mInput = NULL; 5428 return input; 5429} 5430 5431// this method must always be called either with ThreadBase mLock held or inside the thread loop 5432audio_stream_t* AudioFlinger::RecordThread::stream() const 5433{ 5434 if (mInput == NULL) { 5435 return NULL; 5436 } 5437 return &mInput->stream->common; 5438} 5439 5440status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain) 5441{ 5442 // only one chain per input thread 5443 if (mEffectChains.size() != 0) { 5444 return INVALID_OPERATION; 5445 } 5446 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this); 5447 5448 chain->setInBuffer(NULL); 5449 chain->setOutBuffer(NULL); 5450 5451 checkSuspendOnAddEffectChain_l(chain); 5452 5453 mEffectChains.add(chain); 5454 5455 return NO_ERROR; 5456} 5457 5458size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain) 5459{ 5460 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this); 5461 ALOGW_IF(mEffectChains.size() != 1, 5462 "removeEffectChain_l() %p invalid chain size %d on thread %p", 5463 chain.get(), mEffectChains.size(), this); 5464 if (mEffectChains.size() == 1) { 5465 mEffectChains.removeAt(0); 5466 } 5467 return 0; 5468} 5469 5470}; // namespace android 5471