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