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