Threads.cpp revision 0230a2a8a413076a138db4c4e1dea018104fd5e2
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 2350status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp) 2351{ 2352 if (mNormalSink != 0) { 2353 return mNormalSink->getTimestamp(timestamp); 2354 } 2355 if (mType == OFFLOAD && mOutput->stream->get_presentation_position) { 2356 uint64_t position64; 2357 int ret = mOutput->stream->get_presentation_position( 2358 mOutput->stream, &position64, ×tamp.mTime); 2359 if (ret == 0) { 2360 timestamp.mPosition = (uint32_t)position64; 2361 return NO_ERROR; 2362 } 2363 } 2364 return INVALID_OPERATION; 2365} 2366// ---------------------------------------------------------------------------- 2367 2368AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, 2369 audio_io_handle_t id, audio_devices_t device, type_t type) 2370 : PlaybackThread(audioFlinger, output, id, device, type), 2371 // mAudioMixer below 2372 // mFastMixer below 2373 mFastMixerFutex(0) 2374 // mOutputSink below 2375 // mPipeSink below 2376 // mNormalSink below 2377{ 2378 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type); 2379 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, " 2380 "mFrameCount=%d, mNormalFrameCount=%d", 2381 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount, 2382 mNormalFrameCount); 2383 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate); 2384 2385 // FIXME - Current mixer implementation only supports stereo output 2386 if (mChannelCount != FCC_2) { 2387 ALOGE("Invalid audio hardware channel count %d", mChannelCount); 2388 } 2389 2390 // create an NBAIO sink for the HAL output stream, and negotiate 2391 mOutputSink = new AudioStreamOutSink(output->stream); 2392 size_t numCounterOffers = 0; 2393 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)}; 2394 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers); 2395 ALOG_ASSERT(index == 0); 2396 2397 // initialize fast mixer depending on configuration 2398 bool initFastMixer; 2399 switch (kUseFastMixer) { 2400 case FastMixer_Never: 2401 initFastMixer = false; 2402 break; 2403 case FastMixer_Always: 2404 initFastMixer = true; 2405 break; 2406 case FastMixer_Static: 2407 case FastMixer_Dynamic: 2408 initFastMixer = mFrameCount < mNormalFrameCount; 2409 break; 2410 } 2411 if (initFastMixer) { 2412 2413 // create a MonoPipe to connect our submix to FastMixer 2414 NBAIO_Format format = mOutputSink->format(); 2415 // This pipe depth compensates for scheduling latency of the normal mixer thread. 2416 // When it wakes up after a maximum latency, it runs a few cycles quickly before 2417 // finally blocking. Note the pipe implementation rounds up the request to a power of 2. 2418 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/); 2419 const NBAIO_Format offers[1] = {format}; 2420 size_t numCounterOffers = 0; 2421 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers); 2422 ALOG_ASSERT(index == 0); 2423 monoPipe->setAvgFrames((mScreenState & 1) ? 2424 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2); 2425 mPipeSink = monoPipe; 2426 2427#ifdef TEE_SINK 2428 if (mTeeSinkOutputEnabled) { 2429 // create a Pipe to archive a copy of FastMixer's output for dumpsys 2430 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format); 2431 numCounterOffers = 0; 2432 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers); 2433 ALOG_ASSERT(index == 0); 2434 mTeeSink = teeSink; 2435 PipeReader *teeSource = new PipeReader(*teeSink); 2436 numCounterOffers = 0; 2437 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers); 2438 ALOG_ASSERT(index == 0); 2439 mTeeSource = teeSource; 2440 } 2441#endif 2442 2443 // create fast mixer and configure it initially with just one fast track for our submix 2444 mFastMixer = new FastMixer(); 2445 FastMixerStateQueue *sq = mFastMixer->sq(); 2446#ifdef STATE_QUEUE_DUMP 2447 sq->setObserverDump(&mStateQueueObserverDump); 2448 sq->setMutatorDump(&mStateQueueMutatorDump); 2449#endif 2450 FastMixerState *state = sq->begin(); 2451 FastTrack *fastTrack = &state->mFastTracks[0]; 2452 // wrap the source side of the MonoPipe to make it an AudioBufferProvider 2453 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe)); 2454 fastTrack->mVolumeProvider = NULL; 2455 fastTrack->mGeneration++; 2456 state->mFastTracksGen++; 2457 state->mTrackMask = 1; 2458 // fast mixer will use the HAL output sink 2459 state->mOutputSink = mOutputSink.get(); 2460 state->mOutputSinkGen++; 2461 state->mFrameCount = mFrameCount; 2462 state->mCommand = FastMixerState::COLD_IDLE; 2463 // already done in constructor initialization list 2464 //mFastMixerFutex = 0; 2465 state->mColdFutexAddr = &mFastMixerFutex; 2466 state->mColdGen++; 2467 state->mDumpState = &mFastMixerDumpState; 2468#ifdef TEE_SINK 2469 state->mTeeSink = mTeeSink.get(); 2470#endif 2471 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer"); 2472 state->mNBLogWriter = mFastMixerNBLogWriter.get(); 2473 sq->end(); 2474 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 2475 2476 // start the fast mixer 2477 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO); 2478 pid_t tid = mFastMixer->getTid(); 2479 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer); 2480 if (err != 0) { 2481 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d", 2482 kPriorityFastMixer, getpid_cached, tid, err); 2483 } 2484 2485#ifdef AUDIO_WATCHDOG 2486 // create and start the watchdog 2487 mAudioWatchdog = new AudioWatchdog(); 2488 mAudioWatchdog->setDump(&mAudioWatchdogDump); 2489 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO); 2490 tid = mAudioWatchdog->getTid(); 2491 err = requestPriority(getpid_cached, tid, kPriorityFastMixer); 2492 if (err != 0) { 2493 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d", 2494 kPriorityFastMixer, getpid_cached, tid, err); 2495 } 2496#endif 2497 2498 } else { 2499 mFastMixer = NULL; 2500 } 2501 2502 switch (kUseFastMixer) { 2503 case FastMixer_Never: 2504 case FastMixer_Dynamic: 2505 mNormalSink = mOutputSink; 2506 break; 2507 case FastMixer_Always: 2508 mNormalSink = mPipeSink; 2509 break; 2510 case FastMixer_Static: 2511 mNormalSink = initFastMixer ? mPipeSink : mOutputSink; 2512 break; 2513 } 2514} 2515 2516AudioFlinger::MixerThread::~MixerThread() 2517{ 2518 if (mFastMixer != NULL) { 2519 FastMixerStateQueue *sq = mFastMixer->sq(); 2520 FastMixerState *state = sq->begin(); 2521 if (state->mCommand == FastMixerState::COLD_IDLE) { 2522 int32_t old = android_atomic_inc(&mFastMixerFutex); 2523 if (old == -1) { 2524 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1); 2525 } 2526 } 2527 state->mCommand = FastMixerState::EXIT; 2528 sq->end(); 2529 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 2530 mFastMixer->join(); 2531 // Though the fast mixer thread has exited, it's state queue is still valid. 2532 // We'll use that extract the final state which contains one remaining fast track 2533 // corresponding to our sub-mix. 2534 state = sq->begin(); 2535 ALOG_ASSERT(state->mTrackMask == 1); 2536 FastTrack *fastTrack = &state->mFastTracks[0]; 2537 ALOG_ASSERT(fastTrack->mBufferProvider != NULL); 2538 delete fastTrack->mBufferProvider; 2539 sq->end(false /*didModify*/); 2540 delete mFastMixer; 2541#ifdef AUDIO_WATCHDOG 2542 if (mAudioWatchdog != 0) { 2543 mAudioWatchdog->requestExit(); 2544 mAudioWatchdog->requestExitAndWait(); 2545 mAudioWatchdog.clear(); 2546 } 2547#endif 2548 } 2549 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter); 2550 delete mAudioMixer; 2551} 2552 2553 2554uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const 2555{ 2556 if (mFastMixer != NULL) { 2557 MonoPipe *pipe = (MonoPipe *)mPipeSink.get(); 2558 latency += (pipe->getAvgFrames() * 1000) / mSampleRate; 2559 } 2560 return latency; 2561} 2562 2563 2564void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove) 2565{ 2566 PlaybackThread::threadLoop_removeTracks(tracksToRemove); 2567} 2568 2569ssize_t AudioFlinger::MixerThread::threadLoop_write() 2570{ 2571 // FIXME we should only do one push per cycle; confirm this is true 2572 // Start the fast mixer if it's not already running 2573 if (mFastMixer != NULL) { 2574 FastMixerStateQueue *sq = mFastMixer->sq(); 2575 FastMixerState *state = sq->begin(); 2576 if (state->mCommand != FastMixerState::MIX_WRITE && 2577 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) { 2578 if (state->mCommand == FastMixerState::COLD_IDLE) { 2579 int32_t old = android_atomic_inc(&mFastMixerFutex); 2580 if (old == -1) { 2581 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1); 2582 } 2583#ifdef AUDIO_WATCHDOG 2584 if (mAudioWatchdog != 0) { 2585 mAudioWatchdog->resume(); 2586 } 2587#endif 2588 } 2589 state->mCommand = FastMixerState::MIX_WRITE; 2590 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ? 2591 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN); 2592 sq->end(); 2593 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 2594 if (kUseFastMixer == FastMixer_Dynamic) { 2595 mNormalSink = mPipeSink; 2596 } 2597 } else { 2598 sq->end(false /*didModify*/); 2599 } 2600 } 2601 return PlaybackThread::threadLoop_write(); 2602} 2603 2604void AudioFlinger::MixerThread::threadLoop_standby() 2605{ 2606 // Idle the fast mixer if it's currently running 2607 if (mFastMixer != NULL) { 2608 FastMixerStateQueue *sq = mFastMixer->sq(); 2609 FastMixerState *state = sq->begin(); 2610 if (!(state->mCommand & FastMixerState::IDLE)) { 2611 state->mCommand = FastMixerState::COLD_IDLE; 2612 state->mColdFutexAddr = &mFastMixerFutex; 2613 state->mColdGen++; 2614 mFastMixerFutex = 0; 2615 sq->end(); 2616 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now 2617 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED); 2618 if (kUseFastMixer == FastMixer_Dynamic) { 2619 mNormalSink = mOutputSink; 2620 } 2621#ifdef AUDIO_WATCHDOG 2622 if (mAudioWatchdog != 0) { 2623 mAudioWatchdog->pause(); 2624 } 2625#endif 2626 } else { 2627 sq->end(false /*didModify*/); 2628 } 2629 } 2630 PlaybackThread::threadLoop_standby(); 2631} 2632 2633// Empty implementation for standard mixer 2634// Overridden for offloaded playback 2635void AudioFlinger::PlaybackThread::flushOutput_l() 2636{ 2637} 2638 2639bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l() 2640{ 2641 return false; 2642} 2643 2644bool AudioFlinger::PlaybackThread::shouldStandby_l() 2645{ 2646 return !mStandby; 2647} 2648 2649bool AudioFlinger::PlaybackThread::waitingAsyncCallback() 2650{ 2651 Mutex::Autolock _l(mLock); 2652 return waitingAsyncCallback_l(); 2653} 2654 2655// shared by MIXER and DIRECT, overridden by DUPLICATING 2656void AudioFlinger::PlaybackThread::threadLoop_standby() 2657{ 2658 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended); 2659 mOutput->stream->common.standby(&mOutput->stream->common); 2660 if (mUseAsyncWrite != 0) { 2661 // discard any pending drain or write ack by incrementing sequence 2662 mWriteAckSequence = (mWriteAckSequence + 2) & ~1; 2663 mDrainSequence = (mDrainSequence + 2) & ~1; 2664 ALOG_ASSERT(mCallbackThread != 0); 2665 mCallbackThread->setWriteBlocked(mWriteAckSequence); 2666 mCallbackThread->setDraining(mDrainSequence); 2667 } 2668} 2669 2670void AudioFlinger::MixerThread::threadLoop_mix() 2671{ 2672 // obtain the presentation timestamp of the next output buffer 2673 int64_t pts; 2674 status_t status = INVALID_OPERATION; 2675 2676 if (mNormalSink != 0) { 2677 status = mNormalSink->getNextWriteTimestamp(&pts); 2678 } else { 2679 status = mOutputSink->getNextWriteTimestamp(&pts); 2680 } 2681 2682 if (status != NO_ERROR) { 2683 pts = AudioBufferProvider::kInvalidPTS; 2684 } 2685 2686 // mix buffers... 2687 mAudioMixer->process(pts); 2688 mCurrentWriteLength = mixBufferSize; 2689 // increase sleep time progressively when application underrun condition clears. 2690 // Only increase sleep time if the mixer is ready for two consecutive times to avoid 2691 // that a steady state of alternating ready/not ready conditions keeps the sleep time 2692 // such that we would underrun the audio HAL. 2693 if ((sleepTime == 0) && (sleepTimeShift > 0)) { 2694 sleepTimeShift--; 2695 } 2696 sleepTime = 0; 2697 standbyTime = systemTime() + standbyDelay; 2698 //TODO: delay standby when effects have a tail 2699} 2700 2701void AudioFlinger::MixerThread::threadLoop_sleepTime() 2702{ 2703 // If no tracks are ready, sleep once for the duration of an output 2704 // buffer size, then write 0s to the output 2705 if (sleepTime == 0) { 2706 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 2707 sleepTime = activeSleepTime >> sleepTimeShift; 2708 if (sleepTime < kMinThreadSleepTimeUs) { 2709 sleepTime = kMinThreadSleepTimeUs; 2710 } 2711 // reduce sleep time in case of consecutive application underruns to avoid 2712 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer 2713 // duration we would end up writing less data than needed by the audio HAL if 2714 // the condition persists. 2715 if (sleepTimeShift < kMaxThreadSleepTimeShift) { 2716 sleepTimeShift++; 2717 } 2718 } else { 2719 sleepTime = idleSleepTime; 2720 } 2721 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) { 2722 memset(mMixBuffer, 0, mixBufferSize); 2723 sleepTime = 0; 2724 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED), 2725 "anticipated start"); 2726 } 2727 // TODO add standby time extension fct of effect tail 2728} 2729 2730// prepareTracks_l() must be called with ThreadBase::mLock held 2731AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l( 2732 Vector< sp<Track> > *tracksToRemove) 2733{ 2734 2735 mixer_state mixerStatus = MIXER_IDLE; 2736 // find out which tracks need to be processed 2737 size_t count = mActiveTracks.size(); 2738 size_t mixedTracks = 0; 2739 size_t tracksWithEffect = 0; 2740 // counts only _active_ fast tracks 2741 size_t fastTracks = 0; 2742 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset 2743 2744 float masterVolume = mMasterVolume; 2745 bool masterMute = mMasterMute; 2746 2747 if (masterMute) { 2748 masterVolume = 0; 2749 } 2750 // Delegate master volume control to effect in output mix effect chain if needed 2751 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); 2752 if (chain != 0) { 2753 uint32_t v = (uint32_t)(masterVolume * (1 << 24)); 2754 chain->setVolume_l(&v, &v); 2755 masterVolume = (float)((v + (1 << 23)) >> 24); 2756 chain.clear(); 2757 } 2758 2759 // prepare a new state to push 2760 FastMixerStateQueue *sq = NULL; 2761 FastMixerState *state = NULL; 2762 bool didModify = false; 2763 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED; 2764 if (mFastMixer != NULL) { 2765 sq = mFastMixer->sq(); 2766 state = sq->begin(); 2767 } 2768 2769 for (size_t i=0 ; i<count ; i++) { 2770 const sp<Track> t = mActiveTracks[i].promote(); 2771 if (t == 0) { 2772 continue; 2773 } 2774 2775 // this const just means the local variable doesn't change 2776 Track* const track = t.get(); 2777 2778 // process fast tracks 2779 if (track->isFastTrack()) { 2780 2781 // It's theoretically possible (though unlikely) for a fast track to be created 2782 // and then removed within the same normal mix cycle. This is not a problem, as 2783 // the track never becomes active so it's fast mixer slot is never touched. 2784 // The converse, of removing an (active) track and then creating a new track 2785 // at the identical fast mixer slot within the same normal mix cycle, 2786 // is impossible because the slot isn't marked available until the end of each cycle. 2787 int j = track->mFastIndex; 2788 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks); 2789 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j))); 2790 FastTrack *fastTrack = &state->mFastTracks[j]; 2791 2792 // Determine whether the track is currently in underrun condition, 2793 // and whether it had a recent underrun. 2794 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j]; 2795 FastTrackUnderruns underruns = ftDump->mUnderruns; 2796 uint32_t recentFull = (underruns.mBitFields.mFull - 2797 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK; 2798 uint32_t recentPartial = (underruns.mBitFields.mPartial - 2799 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK; 2800 uint32_t recentEmpty = (underruns.mBitFields.mEmpty - 2801 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK; 2802 uint32_t recentUnderruns = recentPartial + recentEmpty; 2803 track->mObservedUnderruns = underruns; 2804 // don't count underruns that occur while stopping or pausing 2805 // or stopped which can occur when flush() is called while active 2806 if (!(track->isStopping() || track->isPausing() || track->isStopped()) && 2807 recentUnderruns > 0) { 2808 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun 2809 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount); 2810 } 2811 2812 // This is similar to the state machine for normal tracks, 2813 // with a few modifications for fast tracks. 2814 bool isActive = true; 2815 switch (track->mState) { 2816 case TrackBase::STOPPING_1: 2817 // track stays active in STOPPING_1 state until first underrun 2818 if (recentUnderruns > 0 || track->isTerminated()) { 2819 track->mState = TrackBase::STOPPING_2; 2820 } 2821 break; 2822 case TrackBase::PAUSING: 2823 // ramp down is not yet implemented 2824 track->setPaused(); 2825 break; 2826 case TrackBase::RESUMING: 2827 // ramp up is not yet implemented 2828 track->mState = TrackBase::ACTIVE; 2829 break; 2830 case TrackBase::ACTIVE: 2831 if (recentFull > 0 || recentPartial > 0) { 2832 // track has provided at least some frames recently: reset retry count 2833 track->mRetryCount = kMaxTrackRetries; 2834 } 2835 if (recentUnderruns == 0) { 2836 // no recent underruns: stay active 2837 break; 2838 } 2839 // there has recently been an underrun of some kind 2840 if (track->sharedBuffer() == 0) { 2841 // were any of the recent underruns "empty" (no frames available)? 2842 if (recentEmpty == 0) { 2843 // no, then ignore the partial underruns as they are allowed indefinitely 2844 break; 2845 } 2846 // there has recently been an "empty" underrun: decrement the retry counter 2847 if (--(track->mRetryCount) > 0) { 2848 break; 2849 } 2850 // indicate to client process that the track was disabled because of underrun; 2851 // it will then automatically call start() when data is available 2852 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags); 2853 // remove from active list, but state remains ACTIVE [confusing but true] 2854 isActive = false; 2855 break; 2856 } 2857 // fall through 2858 case TrackBase::STOPPING_2: 2859 case TrackBase::PAUSED: 2860 case TrackBase::STOPPED: 2861 case TrackBase::FLUSHED: // flush() while active 2862 // Check for presentation complete if track is inactive 2863 // We have consumed all the buffers of this track. 2864 // This would be incomplete if we auto-paused on underrun 2865 { 2866 size_t audioHALFrames = 2867 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000; 2868 size_t framesWritten = mBytesWritten / mFrameSize; 2869 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) { 2870 // track stays in active list until presentation is complete 2871 break; 2872 } 2873 } 2874 if (track->isStopping_2()) { 2875 track->mState = TrackBase::STOPPED; 2876 } 2877 if (track->isStopped()) { 2878 // Can't reset directly, as fast mixer is still polling this track 2879 // track->reset(); 2880 // So instead mark this track as needing to be reset after push with ack 2881 resetMask |= 1 << i; 2882 } 2883 isActive = false; 2884 break; 2885 case TrackBase::IDLE: 2886 default: 2887 LOG_FATAL("unexpected track state %d", track->mState); 2888 } 2889 2890 if (isActive) { 2891 // was it previously inactive? 2892 if (!(state->mTrackMask & (1 << j))) { 2893 ExtendedAudioBufferProvider *eabp = track; 2894 VolumeProvider *vp = track; 2895 fastTrack->mBufferProvider = eabp; 2896 fastTrack->mVolumeProvider = vp; 2897 fastTrack->mSampleRate = track->mSampleRate; 2898 fastTrack->mChannelMask = track->mChannelMask; 2899 fastTrack->mGeneration++; 2900 state->mTrackMask |= 1 << j; 2901 didModify = true; 2902 // no acknowledgement required for newly active tracks 2903 } 2904 // cache the combined master volume and stream type volume for fast mixer; this 2905 // lacks any synchronization or barrier so VolumeProvider may read a stale value 2906 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume; 2907 ++fastTracks; 2908 } else { 2909 // was it previously active? 2910 if (state->mTrackMask & (1 << j)) { 2911 fastTrack->mBufferProvider = NULL; 2912 fastTrack->mGeneration++; 2913 state->mTrackMask &= ~(1 << j); 2914 didModify = true; 2915 // If any fast tracks were removed, we must wait for acknowledgement 2916 // because we're about to decrement the last sp<> on those tracks. 2917 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED; 2918 } else { 2919 LOG_FATAL("fast track %d should have been active", j); 2920 } 2921 tracksToRemove->add(track); 2922 // Avoids a misleading display in dumpsys 2923 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL; 2924 } 2925 continue; 2926 } 2927 2928 { // local variable scope to avoid goto warning 2929 2930 audio_track_cblk_t* cblk = track->cblk(); 2931 2932 // The first time a track is added we wait 2933 // for all its buffers to be filled before processing it 2934 int name = track->name(); 2935 // make sure that we have enough frames to mix one full buffer. 2936 // enforce this condition only once to enable draining the buffer in case the client 2937 // app does not call stop() and relies on underrun to stop: 2938 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed 2939 // during last round 2940 size_t desiredFrames; 2941 uint32_t sr = track->sampleRate(); 2942 if (sr == mSampleRate) { 2943 desiredFrames = mNormalFrameCount; 2944 } else { 2945 // +1 for rounding and +1 for additional sample needed for interpolation 2946 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1; 2947 // add frames already consumed but not yet released by the resampler 2948 // because mAudioTrackServerProxy->framesReady() will include these frames 2949 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name()); 2950 // the minimum track buffer size is normally twice the number of frames necessary 2951 // to fill one buffer and the resampler should not leave more than one buffer worth 2952 // of unreleased frames after each pass, but just in case... 2953 ALOG_ASSERT(desiredFrames <= cblk->frameCount_); 2954 } 2955 uint32_t minFrames = 1; 2956 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() && 2957 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) { 2958 minFrames = desiredFrames; 2959 } 2960 // It's not safe to call framesReady() for a static buffer track, so assume it's ready 2961 size_t framesReady; 2962 if (track->sharedBuffer() == 0) { 2963 framesReady = track->framesReady(); 2964 } else if (track->isStopped()) { 2965 framesReady = 0; 2966 } else { 2967 framesReady = 1; 2968 } 2969 if ((framesReady >= minFrames) && track->isReady() && 2970 !track->isPaused() && !track->isTerminated()) 2971 { 2972 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this); 2973 2974 mixedTracks++; 2975 2976 // track->mainBuffer() != mMixBuffer means there is an effect chain 2977 // connected to the track 2978 chain.clear(); 2979 if (track->mainBuffer() != mMixBuffer) { 2980 chain = getEffectChain_l(track->sessionId()); 2981 // Delegate volume control to effect in track effect chain if needed 2982 if (chain != 0) { 2983 tracksWithEffect++; 2984 } else { 2985 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on " 2986 "session %d", 2987 name, track->sessionId()); 2988 } 2989 } 2990 2991 2992 int param = AudioMixer::VOLUME; 2993 if (track->mFillingUpStatus == Track::FS_FILLED) { 2994 // no ramp for the first volume setting 2995 track->mFillingUpStatus = Track::FS_ACTIVE; 2996 if (track->mState == TrackBase::RESUMING) { 2997 track->mState = TrackBase::ACTIVE; 2998 param = AudioMixer::RAMP_VOLUME; 2999 } 3000 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL); 3001 // FIXME should not make a decision based on mServer 3002 } else if (cblk->mServer != 0) { 3003 // If the track is stopped before the first frame was mixed, 3004 // do not apply ramp 3005 param = AudioMixer::RAMP_VOLUME; 3006 } 3007 3008 // compute volume for this track 3009 uint32_t vl, vr, va; 3010 if (track->isPausing() || mStreamTypes[track->streamType()].mute) { 3011 vl = vr = va = 0; 3012 if (track->isPausing()) { 3013 track->setPaused(); 3014 } 3015 } else { 3016 3017 // read original volumes with volume control 3018 float typeVolume = mStreamTypes[track->streamType()].volume; 3019 float v = masterVolume * typeVolume; 3020 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy; 3021 uint32_t vlr = proxy->getVolumeLR(); 3022 vl = vlr & 0xFFFF; 3023 vr = vlr >> 16; 3024 // track volumes come from shared memory, so can't be trusted and must be clamped 3025 if (vl > MAX_GAIN_INT) { 3026 ALOGV("Track left volume out of range: %04X", vl); 3027 vl = MAX_GAIN_INT; 3028 } 3029 if (vr > MAX_GAIN_INT) { 3030 ALOGV("Track right volume out of range: %04X", vr); 3031 vr = MAX_GAIN_INT; 3032 } 3033 // now apply the master volume and stream type volume 3034 vl = (uint32_t)(v * vl) << 12; 3035 vr = (uint32_t)(v * vr) << 12; 3036 // assuming master volume and stream type volume each go up to 1.0, 3037 // vl and vr are now in 8.24 format 3038 3039 uint16_t sendLevel = proxy->getSendLevel_U4_12(); 3040 // send level comes from shared memory and so may be corrupt 3041 if (sendLevel > MAX_GAIN_INT) { 3042 ALOGV("Track send level out of range: %04X", sendLevel); 3043 sendLevel = MAX_GAIN_INT; 3044 } 3045 va = (uint32_t)(v * sendLevel); 3046 } 3047 3048 // Delegate volume control to effect in track effect chain if needed 3049 if (chain != 0 && chain->setVolume_l(&vl, &vr)) { 3050 // Do not ramp volume if volume is controlled by effect 3051 param = AudioMixer::VOLUME; 3052 track->mHasVolumeController = true; 3053 } else { 3054 // force no volume ramp when volume controller was just disabled or removed 3055 // from effect chain to avoid volume spike 3056 if (track->mHasVolumeController) { 3057 param = AudioMixer::VOLUME; 3058 } 3059 track->mHasVolumeController = false; 3060 } 3061 3062 // Convert volumes from 8.24 to 4.12 format 3063 // This additional clamping is needed in case chain->setVolume_l() overshot 3064 vl = (vl + (1 << 11)) >> 12; 3065 if (vl > MAX_GAIN_INT) { 3066 vl = MAX_GAIN_INT; 3067 } 3068 vr = (vr + (1 << 11)) >> 12; 3069 if (vr > MAX_GAIN_INT) { 3070 vr = MAX_GAIN_INT; 3071 } 3072 3073 if (va > MAX_GAIN_INT) { 3074 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for - 3075 } 3076 3077 // XXX: these things DON'T need to be done each time 3078 mAudioMixer->setBufferProvider(name, track); 3079 mAudioMixer->enable(name); 3080 3081 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl); 3082 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr); 3083 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va); 3084 mAudioMixer->setParameter( 3085 name, 3086 AudioMixer::TRACK, 3087 AudioMixer::FORMAT, (void *)track->format()); 3088 mAudioMixer->setParameter( 3089 name, 3090 AudioMixer::TRACK, 3091 AudioMixer::CHANNEL_MASK, (void *)track->channelMask()); 3092 // limit track sample rate to 2 x output sample rate, which changes at re-configuration 3093 uint32_t maxSampleRate = mSampleRate * 2; 3094 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate(); 3095 if (reqSampleRate == 0) { 3096 reqSampleRate = mSampleRate; 3097 } else if (reqSampleRate > maxSampleRate) { 3098 reqSampleRate = maxSampleRate; 3099 } 3100 mAudioMixer->setParameter( 3101 name, 3102 AudioMixer::RESAMPLE, 3103 AudioMixer::SAMPLE_RATE, 3104 (void *)reqSampleRate); 3105 mAudioMixer->setParameter( 3106 name, 3107 AudioMixer::TRACK, 3108 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer()); 3109 mAudioMixer->setParameter( 3110 name, 3111 AudioMixer::TRACK, 3112 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer()); 3113 3114 // reset retry count 3115 track->mRetryCount = kMaxTrackRetries; 3116 3117 // If one track is ready, set the mixer ready if: 3118 // - the mixer was not ready during previous round OR 3119 // - no other track is not ready 3120 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY || 3121 mixerStatus != MIXER_TRACKS_ENABLED) { 3122 mixerStatus = MIXER_TRACKS_READY; 3123 } 3124 } else { 3125 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) { 3126 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames); 3127 } 3128 // clear effect chain input buffer if an active track underruns to avoid sending 3129 // previous audio buffer again to effects 3130 chain = getEffectChain_l(track->sessionId()); 3131 if (chain != 0) { 3132 chain->clearInputBuffer(); 3133 } 3134 3135 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this); 3136 if ((track->sharedBuffer() != 0) || track->isTerminated() || 3137 track->isStopped() || track->isPaused()) { 3138 // We have consumed all the buffers of this track. 3139 // Remove it from the list of active tracks. 3140 // TODO: use actual buffer filling status instead of latency when available from 3141 // audio HAL 3142 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000; 3143 size_t framesWritten = mBytesWritten / mFrameSize; 3144 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) { 3145 if (track->isStopped()) { 3146 track->reset(); 3147 } 3148 tracksToRemove->add(track); 3149 } 3150 } else { 3151 // No buffers for this track. Give it a few chances to 3152 // fill a buffer, then remove it from active list. 3153 if (--(track->mRetryCount) <= 0) { 3154 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this); 3155 tracksToRemove->add(track); 3156 // indicate to client process that the track was disabled because of underrun; 3157 // it will then automatically call start() when data is available 3158 android_atomic_or(CBLK_DISABLED, &cblk->mFlags); 3159 // If one track is not ready, mark the mixer also not ready if: 3160 // - the mixer was ready during previous round OR 3161 // - no other track is ready 3162 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY || 3163 mixerStatus != MIXER_TRACKS_READY) { 3164 mixerStatus = MIXER_TRACKS_ENABLED; 3165 } 3166 } 3167 mAudioMixer->disable(name); 3168 } 3169 3170 } // local variable scope to avoid goto warning 3171track_is_ready: ; 3172 3173 } 3174 3175 // Push the new FastMixer state if necessary 3176 bool pauseAudioWatchdog = false; 3177 if (didModify) { 3178 state->mFastTracksGen++; 3179 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle 3180 if (kUseFastMixer == FastMixer_Dynamic && 3181 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) { 3182 state->mCommand = FastMixerState::COLD_IDLE; 3183 state->mColdFutexAddr = &mFastMixerFutex; 3184 state->mColdGen++; 3185 mFastMixerFutex = 0; 3186 if (kUseFastMixer == FastMixer_Dynamic) { 3187 mNormalSink = mOutputSink; 3188 } 3189 // If we go into cold idle, need to wait for acknowledgement 3190 // so that fast mixer stops doing I/O. 3191 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED; 3192 pauseAudioWatchdog = true; 3193 } 3194 } 3195 if (sq != NULL) { 3196 sq->end(didModify); 3197 sq->push(block); 3198 } 3199#ifdef AUDIO_WATCHDOG 3200 if (pauseAudioWatchdog && mAudioWatchdog != 0) { 3201 mAudioWatchdog->pause(); 3202 } 3203#endif 3204 3205 // Now perform the deferred reset on fast tracks that have stopped 3206 while (resetMask != 0) { 3207 size_t i = __builtin_ctz(resetMask); 3208 ALOG_ASSERT(i < count); 3209 resetMask &= ~(1 << i); 3210 sp<Track> t = mActiveTracks[i].promote(); 3211 if (t == 0) { 3212 continue; 3213 } 3214 Track* track = t.get(); 3215 ALOG_ASSERT(track->isFastTrack() && track->isStopped()); 3216 track->reset(); 3217 } 3218 3219 // remove all the tracks that need to be... 3220 removeTracks_l(*tracksToRemove); 3221 3222 // mix buffer must be cleared if all tracks are connected to an 3223 // effect chain as in this case the mixer will not write to 3224 // mix buffer and track effects will accumulate into it 3225 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || 3226 (mixedTracks == 0 && fastTracks > 0))) { 3227 // FIXME as a performance optimization, should remember previous zero status 3228 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t)); 3229 } 3230 3231 // if any fast tracks, then status is ready 3232 mMixerStatusIgnoringFastTracks = mixerStatus; 3233 if (fastTracks > 0) { 3234 mixerStatus = MIXER_TRACKS_READY; 3235 } 3236 return mixerStatus; 3237} 3238 3239// getTrackName_l() must be called with ThreadBase::mLock held 3240int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId) 3241{ 3242 return mAudioMixer->getTrackName(channelMask, sessionId); 3243} 3244 3245// deleteTrackName_l() must be called with ThreadBase::mLock held 3246void AudioFlinger::MixerThread::deleteTrackName_l(int name) 3247{ 3248 ALOGV("remove track (%d) and delete from mixer", name); 3249 mAudioMixer->deleteTrackName(name); 3250} 3251 3252// checkForNewParameters_l() must be called with ThreadBase::mLock held 3253bool AudioFlinger::MixerThread::checkForNewParameters_l() 3254{ 3255 // if !&IDLE, holds the FastMixer state to restore after new parameters processed 3256 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE; 3257 bool reconfig = false; 3258 3259 while (!mNewParameters.isEmpty()) { 3260 3261 if (mFastMixer != NULL) { 3262 FastMixerStateQueue *sq = mFastMixer->sq(); 3263 FastMixerState *state = sq->begin(); 3264 if (!(state->mCommand & FastMixerState::IDLE)) { 3265 previousCommand = state->mCommand; 3266 state->mCommand = FastMixerState::HOT_IDLE; 3267 sq->end(); 3268 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED); 3269 } else { 3270 sq->end(false /*didModify*/); 3271 } 3272 } 3273 3274 status_t status = NO_ERROR; 3275 String8 keyValuePair = mNewParameters[0]; 3276 AudioParameter param = AudioParameter(keyValuePair); 3277 int value; 3278 3279 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { 3280 reconfig = true; 3281 } 3282 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { 3283 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) { 3284 status = BAD_VALUE; 3285 } else { 3286 // no need to save value, since it's constant 3287 reconfig = true; 3288 } 3289 } 3290 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { 3291 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) { 3292 status = BAD_VALUE; 3293 } else { 3294 // no need to save value, since it's constant 3295 reconfig = true; 3296 } 3297 } 3298 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 3299 // do not accept frame count changes if tracks are open as the track buffer 3300 // size depends on frame count and correct behavior would not be guaranteed 3301 // if frame count is changed after track creation 3302 if (!mTracks.isEmpty()) { 3303 status = INVALID_OPERATION; 3304 } else { 3305 reconfig = true; 3306 } 3307 } 3308 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 3309#ifdef ADD_BATTERY_DATA 3310 // when changing the audio output device, call addBatteryData to notify 3311 // the change 3312 if (mOutDevice != value) { 3313 uint32_t params = 0; 3314 // check whether speaker is on 3315 if (value & AUDIO_DEVICE_OUT_SPEAKER) { 3316 params |= IMediaPlayerService::kBatteryDataSpeakerOn; 3317 } 3318 3319 audio_devices_t deviceWithoutSpeaker 3320 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER; 3321 // check if any other device (except speaker) is on 3322 if (value & deviceWithoutSpeaker ) { 3323 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn; 3324 } 3325 3326 if (params != 0) { 3327 addBatteryData(params); 3328 } 3329 } 3330#endif 3331 3332 // forward device change to effects that have requested to be 3333 // aware of attached audio device. 3334 if (value != AUDIO_DEVICE_NONE) { 3335 mOutDevice = value; 3336 for (size_t i = 0; i < mEffectChains.size(); i++) { 3337 mEffectChains[i]->setDevice_l(mOutDevice); 3338 } 3339 } 3340 } 3341 3342 if (status == NO_ERROR) { 3343 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3344 keyValuePair.string()); 3345 if (!mStandby && status == INVALID_OPERATION) { 3346 mOutput->stream->common.standby(&mOutput->stream->common); 3347 mStandby = true; 3348 mBytesWritten = 0; 3349 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3350 keyValuePair.string()); 3351 } 3352 if (status == NO_ERROR && reconfig) { 3353 readOutputParameters(); 3354 delete mAudioMixer; 3355 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate); 3356 for (size_t i = 0; i < mTracks.size() ; i++) { 3357 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId); 3358 if (name < 0) { 3359 break; 3360 } 3361 mTracks[i]->mName = name; 3362 } 3363 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED); 3364 } 3365 } 3366 3367 mNewParameters.removeAt(0); 3368 3369 mParamStatus = status; 3370 mParamCond.signal(); 3371 // wait for condition with time out in case the thread calling ThreadBase::setParameters() 3372 // already timed out waiting for the status and will never signal the condition. 3373 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); 3374 } 3375 3376 if (!(previousCommand & FastMixerState::IDLE)) { 3377 ALOG_ASSERT(mFastMixer != NULL); 3378 FastMixerStateQueue *sq = mFastMixer->sq(); 3379 FastMixerState *state = sq->begin(); 3380 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE); 3381 state->mCommand = previousCommand; 3382 sq->end(); 3383 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 3384 } 3385 3386 return reconfig; 3387} 3388 3389 3390void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args) 3391{ 3392 const size_t SIZE = 256; 3393 char buffer[SIZE]; 3394 String8 result; 3395 3396 PlaybackThread::dumpInternals(fd, args); 3397 3398 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames()); 3399 result.append(buffer); 3400 write(fd, result.string(), result.size()); 3401 3402 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us 3403 const FastMixerDumpState copy(mFastMixerDumpState); 3404 copy.dump(fd); 3405 3406#ifdef STATE_QUEUE_DUMP 3407 // Similar for state queue 3408 StateQueueObserverDump observerCopy = mStateQueueObserverDump; 3409 observerCopy.dump(fd); 3410 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump; 3411 mutatorCopy.dump(fd); 3412#endif 3413 3414#ifdef TEE_SINK 3415 // Write the tee output to a .wav file 3416 dumpTee(fd, mTeeSource, mId); 3417#endif 3418 3419#ifdef AUDIO_WATCHDOG 3420 if (mAudioWatchdog != 0) { 3421 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us 3422 AudioWatchdogDump wdCopy = mAudioWatchdogDump; 3423 wdCopy.dump(fd); 3424 } 3425#endif 3426} 3427 3428uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const 3429{ 3430 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2; 3431} 3432 3433uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const 3434{ 3435 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000); 3436} 3437 3438void AudioFlinger::MixerThread::cacheParameters_l() 3439{ 3440 PlaybackThread::cacheParameters_l(); 3441 3442 // FIXME: Relaxed timing because of a certain device that can't meet latency 3443 // Should be reduced to 2x after the vendor fixes the driver issue 3444 // increase threshold again due to low power audio mode. The way this warning 3445 // threshold is calculated and its usefulness should be reconsidered anyway. 3446 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15; 3447} 3448 3449// ---------------------------------------------------------------------------- 3450 3451AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, 3452 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device) 3453 : PlaybackThread(audioFlinger, output, id, device, DIRECT) 3454 // mLeftVolFloat, mRightVolFloat 3455{ 3456} 3457 3458AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, 3459 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, 3460 ThreadBase::type_t type) 3461 : PlaybackThread(audioFlinger, output, id, device, type) 3462 // mLeftVolFloat, mRightVolFloat 3463{ 3464} 3465 3466AudioFlinger::DirectOutputThread::~DirectOutputThread() 3467{ 3468} 3469 3470void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack) 3471{ 3472 audio_track_cblk_t* cblk = track->cblk(); 3473 float left, right; 3474 3475 if (mMasterMute || mStreamTypes[track->streamType()].mute) { 3476 left = right = 0; 3477 } else { 3478 float typeVolume = mStreamTypes[track->streamType()].volume; 3479 float v = mMasterVolume * typeVolume; 3480 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy; 3481 uint32_t vlr = proxy->getVolumeLR(); 3482 float v_clamped = v * (vlr & 0xFFFF); 3483 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN; 3484 left = v_clamped/MAX_GAIN; 3485 v_clamped = v * (vlr >> 16); 3486 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN; 3487 right = v_clamped/MAX_GAIN; 3488 } 3489 3490 if (lastTrack) { 3491 if (left != mLeftVolFloat || right != mRightVolFloat) { 3492 mLeftVolFloat = left; 3493 mRightVolFloat = right; 3494 3495 // Convert volumes from float to 8.24 3496 uint32_t vl = (uint32_t)(left * (1 << 24)); 3497 uint32_t vr = (uint32_t)(right * (1 << 24)); 3498 3499 // Delegate volume control to effect in track effect chain if needed 3500 // only one effect chain can be present on DirectOutputThread, so if 3501 // there is one, the track is connected to it 3502 if (!mEffectChains.isEmpty()) { 3503 mEffectChains[0]->setVolume_l(&vl, &vr); 3504 left = (float)vl / (1 << 24); 3505 right = (float)vr / (1 << 24); 3506 } 3507 if (mOutput->stream->set_volume) { 3508 mOutput->stream->set_volume(mOutput->stream, left, right); 3509 } 3510 } 3511 } 3512} 3513 3514 3515AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l( 3516 Vector< sp<Track> > *tracksToRemove 3517) 3518{ 3519 size_t count = mActiveTracks.size(); 3520 mixer_state mixerStatus = MIXER_IDLE; 3521 3522 // find out which tracks need to be processed 3523 for (size_t i = 0; i < count; i++) { 3524 sp<Track> t = mActiveTracks[i].promote(); 3525 // The track died recently 3526 if (t == 0) { 3527 continue; 3528 } 3529 3530 Track* const track = t.get(); 3531 audio_track_cblk_t* cblk = track->cblk(); 3532 3533 // The first time a track is added we wait 3534 // for all its buffers to be filled before processing it 3535 uint32_t minFrames; 3536 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) { 3537 minFrames = mNormalFrameCount; 3538 } else { 3539 minFrames = 1; 3540 } 3541 // Only consider last track started for volume and mixer state control. 3542 // This is the last entry in mActiveTracks unless a track underruns. 3543 // As we only care about the transition phase between two tracks on a 3544 // direct output, it is not a problem to ignore the underrun case. 3545 bool last = (i == (count - 1)); 3546 3547 if ((track->framesReady() >= minFrames) && track->isReady() && 3548 !track->isPaused() && !track->isTerminated()) 3549 { 3550 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer); 3551 3552 if (track->mFillingUpStatus == Track::FS_FILLED) { 3553 track->mFillingUpStatus = Track::FS_ACTIVE; 3554 // make sure processVolume_l() will apply new volume even if 0 3555 mLeftVolFloat = mRightVolFloat = -1.0; 3556 if (track->mState == TrackBase::RESUMING) { 3557 track->mState = TrackBase::ACTIVE; 3558 } 3559 } 3560 3561 // compute volume for this track 3562 processVolume_l(track, last); 3563 if (last) { 3564 // reset retry count 3565 track->mRetryCount = kMaxTrackRetriesDirect; 3566 mActiveTrack = t; 3567 mixerStatus = MIXER_TRACKS_READY; 3568 } 3569 } else { 3570 // clear effect chain input buffer if the last active track started underruns 3571 // to avoid sending previous audio buffer again to effects 3572 if (!mEffectChains.isEmpty() && (i == (count -1))) { 3573 mEffectChains[0]->clearInputBuffer(); 3574 } 3575 3576 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer); 3577 if ((track->sharedBuffer() != 0) || track->isTerminated() || 3578 track->isStopped() || track->isPaused()) { 3579 // We have consumed all the buffers of this track. 3580 // Remove it from the list of active tracks. 3581 // TODO: implement behavior for compressed audio 3582 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000; 3583 size_t framesWritten = mBytesWritten / mFrameSize; 3584 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) { 3585 if (track->isStopped()) { 3586 track->reset(); 3587 } 3588 tracksToRemove->add(track); 3589 } 3590 } else { 3591 // No buffers for this track. Give it a few chances to 3592 // fill a buffer, then remove it from active list. 3593 // Only consider last track started for mixer state control 3594 if (--(track->mRetryCount) <= 0) { 3595 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name()); 3596 tracksToRemove->add(track); 3597 } else if (last) { 3598 mixerStatus = MIXER_TRACKS_ENABLED; 3599 } 3600 } 3601 } 3602 } 3603 3604 // remove all the tracks that need to be... 3605 removeTracks_l(*tracksToRemove); 3606 3607 return mixerStatus; 3608} 3609 3610void AudioFlinger::DirectOutputThread::threadLoop_mix() 3611{ 3612 size_t frameCount = mFrameCount; 3613 int8_t *curBuf = (int8_t *)mMixBuffer; 3614 // output audio to hardware 3615 while (frameCount) { 3616 AudioBufferProvider::Buffer buffer; 3617 buffer.frameCount = frameCount; 3618 mActiveTrack->getNextBuffer(&buffer); 3619 if (buffer.raw == NULL) { 3620 memset(curBuf, 0, frameCount * mFrameSize); 3621 break; 3622 } 3623 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize); 3624 frameCount -= buffer.frameCount; 3625 curBuf += buffer.frameCount * mFrameSize; 3626 mActiveTrack->releaseBuffer(&buffer); 3627 } 3628 mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer; 3629 sleepTime = 0; 3630 standbyTime = systemTime() + standbyDelay; 3631 mActiveTrack.clear(); 3632} 3633 3634void AudioFlinger::DirectOutputThread::threadLoop_sleepTime() 3635{ 3636 if (sleepTime == 0) { 3637 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 3638 sleepTime = activeSleepTime; 3639 } else { 3640 sleepTime = idleSleepTime; 3641 } 3642 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) { 3643 memset(mMixBuffer, 0, mFrameCount * mFrameSize); 3644 sleepTime = 0; 3645 } 3646} 3647 3648// getTrackName_l() must be called with ThreadBase::mLock held 3649int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask, 3650 int sessionId) 3651{ 3652 return 0; 3653} 3654 3655// deleteTrackName_l() must be called with ThreadBase::mLock held 3656void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name) 3657{ 3658} 3659 3660// checkForNewParameters_l() must be called with ThreadBase::mLock held 3661bool AudioFlinger::DirectOutputThread::checkForNewParameters_l() 3662{ 3663 bool reconfig = false; 3664 3665 while (!mNewParameters.isEmpty()) { 3666 status_t status = NO_ERROR; 3667 String8 keyValuePair = mNewParameters[0]; 3668 AudioParameter param = AudioParameter(keyValuePair); 3669 int value; 3670 3671 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 3672 // do not accept frame count changes if tracks are open as the track buffer 3673 // size depends on frame count and correct behavior would not be garantied 3674 // if frame count is changed after track creation 3675 if (!mTracks.isEmpty()) { 3676 status = INVALID_OPERATION; 3677 } else { 3678 reconfig = true; 3679 } 3680 } 3681 if (status == NO_ERROR) { 3682 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3683 keyValuePair.string()); 3684 if (!mStandby && status == INVALID_OPERATION) { 3685 mOutput->stream->common.standby(&mOutput->stream->common); 3686 mStandby = true; 3687 mBytesWritten = 0; 3688 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3689 keyValuePair.string()); 3690 } 3691 if (status == NO_ERROR && reconfig) { 3692 readOutputParameters(); 3693 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED); 3694 } 3695 } 3696 3697 mNewParameters.removeAt(0); 3698 3699 mParamStatus = status; 3700 mParamCond.signal(); 3701 // wait for condition with time out in case the thread calling ThreadBase::setParameters() 3702 // already timed out waiting for the status and will never signal the condition. 3703 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); 3704 } 3705 return reconfig; 3706} 3707 3708uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const 3709{ 3710 uint32_t time; 3711 if (audio_is_linear_pcm(mFormat)) { 3712 time = PlaybackThread::activeSleepTimeUs(); 3713 } else { 3714 time = 10000; 3715 } 3716 return time; 3717} 3718 3719uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const 3720{ 3721 uint32_t time; 3722 if (audio_is_linear_pcm(mFormat)) { 3723 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2; 3724 } else { 3725 time = 10000; 3726 } 3727 return time; 3728} 3729 3730uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const 3731{ 3732 uint32_t time; 3733 if (audio_is_linear_pcm(mFormat)) { 3734 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000); 3735 } else { 3736 time = 10000; 3737 } 3738 return time; 3739} 3740 3741void AudioFlinger::DirectOutputThread::cacheParameters_l() 3742{ 3743 PlaybackThread::cacheParameters_l(); 3744 3745 // use shorter standby delay as on normal output to release 3746 // hardware resources as soon as possible 3747 if (audio_is_linear_pcm(mFormat)) { 3748 standbyDelay = microseconds(activeSleepTime*2); 3749 } else { 3750 standbyDelay = kOffloadStandbyDelayNs; 3751 } 3752} 3753 3754// ---------------------------------------------------------------------------- 3755 3756AudioFlinger::AsyncCallbackThread::AsyncCallbackThread( 3757 const sp<AudioFlinger::OffloadThread>& offloadThread) 3758 : Thread(false /*canCallJava*/), 3759 mOffloadThread(offloadThread), 3760 mWriteAckSequence(0), 3761 mDrainSequence(0) 3762{ 3763} 3764 3765AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread() 3766{ 3767} 3768 3769void AudioFlinger::AsyncCallbackThread::onFirstRef() 3770{ 3771 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO); 3772} 3773 3774bool AudioFlinger::AsyncCallbackThread::threadLoop() 3775{ 3776 while (!exitPending()) { 3777 uint32_t writeAckSequence; 3778 uint32_t drainSequence; 3779 3780 { 3781 Mutex::Autolock _l(mLock); 3782 mWaitWorkCV.wait(mLock); 3783 if (exitPending()) { 3784 break; 3785 } 3786 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d", 3787 mWriteAckSequence, mDrainSequence); 3788 writeAckSequence = mWriteAckSequence; 3789 mWriteAckSequence &= ~1; 3790 drainSequence = mDrainSequence; 3791 mDrainSequence &= ~1; 3792 } 3793 { 3794 sp<AudioFlinger::OffloadThread> offloadThread = mOffloadThread.promote(); 3795 if (offloadThread != 0) { 3796 if (writeAckSequence & 1) { 3797 offloadThread->resetWriteBlocked(writeAckSequence >> 1); 3798 } 3799 if (drainSequence & 1) { 3800 offloadThread->resetDraining(drainSequence >> 1); 3801 } 3802 } 3803 } 3804 } 3805 return false; 3806} 3807 3808void AudioFlinger::AsyncCallbackThread::exit() 3809{ 3810 ALOGV("AsyncCallbackThread::exit"); 3811 Mutex::Autolock _l(mLock); 3812 requestExit(); 3813 mWaitWorkCV.broadcast(); 3814} 3815 3816void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence) 3817{ 3818 Mutex::Autolock _l(mLock); 3819 // bit 0 is cleared 3820 mWriteAckSequence = sequence << 1; 3821} 3822 3823void AudioFlinger::AsyncCallbackThread::resetWriteBlocked() 3824{ 3825 Mutex::Autolock _l(mLock); 3826 // ignore unexpected callbacks 3827 if (mWriteAckSequence & 2) { 3828 mWriteAckSequence |= 1; 3829 mWaitWorkCV.signal(); 3830 } 3831} 3832 3833void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence) 3834{ 3835 Mutex::Autolock _l(mLock); 3836 // bit 0 is cleared 3837 mDrainSequence = sequence << 1; 3838} 3839 3840void AudioFlinger::AsyncCallbackThread::resetDraining() 3841{ 3842 Mutex::Autolock _l(mLock); 3843 // ignore unexpected callbacks 3844 if (mDrainSequence & 2) { 3845 mDrainSequence |= 1; 3846 mWaitWorkCV.signal(); 3847 } 3848} 3849 3850 3851// ---------------------------------------------------------------------------- 3852AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger, 3853 AudioStreamOut* output, audio_io_handle_t id, uint32_t device) 3854 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD), 3855 mHwPaused(false), 3856 mPausedBytesRemaining(0) 3857{ 3858 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this); 3859} 3860 3861AudioFlinger::OffloadThread::~OffloadThread() 3862{ 3863 mPreviousTrack.clear(); 3864} 3865 3866void AudioFlinger::OffloadThread::threadLoop_exit() 3867{ 3868 if (mFlushPending || mHwPaused) { 3869 // If a flush is pending or track was paused, just discard buffered data 3870 flushHw_l(); 3871 } else { 3872 mMixerStatus = MIXER_DRAIN_ALL; 3873 threadLoop_drain(); 3874 } 3875 mCallbackThread->exit(); 3876 PlaybackThread::threadLoop_exit(); 3877} 3878 3879AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l( 3880 Vector< sp<Track> > *tracksToRemove 3881) 3882{ 3883 size_t count = mActiveTracks.size(); 3884 3885 mixer_state mixerStatus = MIXER_IDLE; 3886 bool doHwPause = false; 3887 bool doHwResume = false; 3888 3889 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count); 3890 3891 // find out which tracks need to be processed 3892 for (size_t i = 0; i < count; i++) { 3893 sp<Track> t = mActiveTracks[i].promote(); 3894 // The track died recently 3895 if (t == 0) { 3896 continue; 3897 } 3898 Track* const track = t.get(); 3899 audio_track_cblk_t* cblk = track->cblk(); 3900 if (mPreviousTrack != NULL) { 3901 if (t != mPreviousTrack) { 3902 // Flush any data still being written from last track 3903 mBytesRemaining = 0; 3904 if (mPausedBytesRemaining) { 3905 // Last track was paused so we also need to flush saved 3906 // mixbuffer state and invalidate track so that it will 3907 // re-submit that unwritten data when it is next resumed 3908 mPausedBytesRemaining = 0; 3909 // Invalidate is a bit drastic - would be more efficient 3910 // to have a flag to tell client that some of the 3911 // previously written data was lost 3912 mPreviousTrack->invalidate(); 3913 } 3914 } 3915 } 3916 mPreviousTrack = t; 3917 bool last = (i == (count - 1)); 3918 if (track->isPausing()) { 3919 track->setPaused(); 3920 if (last) { 3921 if (!mHwPaused) { 3922 doHwPause = true; 3923 mHwPaused = true; 3924 } 3925 // If we were part way through writing the mixbuffer to 3926 // the HAL we must save this until we resume 3927 // BUG - this will be wrong if a different track is made active, 3928 // in that case we want to discard the pending data in the 3929 // mixbuffer and tell the client to present it again when the 3930 // track is resumed 3931 mPausedWriteLength = mCurrentWriteLength; 3932 mPausedBytesRemaining = mBytesRemaining; 3933 mBytesRemaining = 0; // stop writing 3934 } 3935 tracksToRemove->add(track); 3936 } else if (track->framesReady() && track->isReady() && 3937 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) { 3938 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer); 3939 if (track->mFillingUpStatus == Track::FS_FILLED) { 3940 track->mFillingUpStatus = Track::FS_ACTIVE; 3941 // make sure processVolume_l() will apply new volume even if 0 3942 mLeftVolFloat = mRightVolFloat = -1.0; 3943 if (track->mState == TrackBase::RESUMING) { 3944 track->mState = TrackBase::ACTIVE; 3945 if (last) { 3946 if (mPausedBytesRemaining) { 3947 // Need to continue write that was interrupted 3948 mCurrentWriteLength = mPausedWriteLength; 3949 mBytesRemaining = mPausedBytesRemaining; 3950 mPausedBytesRemaining = 0; 3951 } 3952 if (mHwPaused) { 3953 doHwResume = true; 3954 mHwPaused = false; 3955 // threadLoop_mix() will handle the case that we need to 3956 // resume an interrupted write 3957 } 3958 // enable write to audio HAL 3959 sleepTime = 0; 3960 } 3961 } 3962 } 3963 3964 if (last) { 3965 // reset retry count 3966 track->mRetryCount = kMaxTrackRetriesOffload; 3967 mActiveTrack = t; 3968 mixerStatus = MIXER_TRACKS_READY; 3969 } 3970 } else { 3971 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer); 3972 if (track->isStopping_1()) { 3973 // Hardware buffer can hold a large amount of audio so we must 3974 // wait for all current track's data to drain before we say 3975 // that the track is stopped. 3976 if (mBytesRemaining == 0) { 3977 // Only start draining when all data in mixbuffer 3978 // has been written 3979 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2"); 3980 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain 3981 if (last) { 3982 sleepTime = 0; 3983 standbyTime = systemTime() + standbyDelay; 3984 mixerStatus = MIXER_DRAIN_TRACK; 3985 mDrainSequence += 2; 3986 if (mHwPaused) { 3987 // It is possible to move from PAUSED to STOPPING_1 without 3988 // a resume so we must ensure hardware is running 3989 mOutput->stream->resume(mOutput->stream); 3990 mHwPaused = false; 3991 } 3992 } 3993 } 3994 } else if (track->isStopping_2()) { 3995 // Drain has completed, signal presentation complete 3996 if (!(mDrainSequence & 1) || !last) { 3997 track->mState = TrackBase::STOPPED; 3998 size_t audioHALFrames = 3999 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000; 4000 size_t framesWritten = 4001 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common); 4002 track->presentationComplete(framesWritten, audioHALFrames); 4003 track->reset(); 4004 tracksToRemove->add(track); 4005 } 4006 } else { 4007 // No buffers for this track. Give it a few chances to 4008 // fill a buffer, then remove it from active list. 4009 if (--(track->mRetryCount) <= 0) { 4010 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list", 4011 track->name()); 4012 tracksToRemove->add(track); 4013 } else if (last){ 4014 mixerStatus = MIXER_TRACKS_ENABLED; 4015 } 4016 } 4017 } 4018 // compute volume for this track 4019 processVolume_l(track, last); 4020 } 4021 4022 // make sure the pause/flush/resume sequence is executed in the right order 4023 if (doHwPause) { 4024 mOutput->stream->pause(mOutput->stream); 4025 } 4026 if (mFlushPending) { 4027 flushHw_l(); 4028 mFlushPending = false; 4029 } 4030 if (doHwResume) { 4031 mOutput->stream->resume(mOutput->stream); 4032 } 4033 4034 // remove all the tracks that need to be... 4035 removeTracks_l(*tracksToRemove); 4036 4037 return mixerStatus; 4038} 4039 4040void AudioFlinger::OffloadThread::flushOutput_l() 4041{ 4042 mFlushPending = true; 4043} 4044 4045// must be called with thread mutex locked 4046bool AudioFlinger::OffloadThread::waitingAsyncCallback_l() 4047{ 4048 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d", 4049 mWriteAckSequence, mDrainSequence); 4050 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) { 4051 return true; 4052 } 4053 return false; 4054} 4055 4056// must be called with thread mutex locked 4057bool AudioFlinger::OffloadThread::shouldStandby_l() 4058{ 4059 bool TrackPaused = false; 4060 4061 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack 4062 // after a timeout and we will enter standby then. 4063 if (mTracks.size() > 0) { 4064 TrackPaused = mTracks[mTracks.size() - 1]->isPaused(); 4065 } 4066 4067 return !mStandby && !TrackPaused; 4068} 4069 4070 4071bool AudioFlinger::OffloadThread::waitingAsyncCallback() 4072{ 4073 Mutex::Autolock _l(mLock); 4074 return waitingAsyncCallback_l(); 4075} 4076 4077void AudioFlinger::OffloadThread::flushHw_l() 4078{ 4079 mOutput->stream->flush(mOutput->stream); 4080 // Flush anything still waiting in the mixbuffer 4081 mCurrentWriteLength = 0; 4082 mBytesRemaining = 0; 4083 mPausedWriteLength = 0; 4084 mPausedBytesRemaining = 0; 4085 if (mUseAsyncWrite) { 4086 // discard any pending drain or write ack by incrementing sequence 4087 mWriteAckSequence = (mWriteAckSequence + 2) & ~1; 4088 mDrainSequence = (mDrainSequence + 2) & ~1; 4089 ALOG_ASSERT(mCallbackThread != 0); 4090 mCallbackThread->setWriteBlocked(mWriteAckSequence); 4091 mCallbackThread->setDraining(mDrainSequence); 4092 } 4093} 4094 4095// ---------------------------------------------------------------------------- 4096 4097AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, 4098 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id) 4099 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(), 4100 DUPLICATING), 4101 mWaitTimeMs(UINT_MAX) 4102{ 4103 addOutputTrack(mainThread); 4104} 4105 4106AudioFlinger::DuplicatingThread::~DuplicatingThread() 4107{ 4108 for (size_t i = 0; i < mOutputTracks.size(); i++) { 4109 mOutputTracks[i]->destroy(); 4110 } 4111} 4112 4113void AudioFlinger::DuplicatingThread::threadLoop_mix() 4114{ 4115 // mix buffers... 4116 if (outputsReady(outputTracks)) { 4117 mAudioMixer->process(AudioBufferProvider::kInvalidPTS); 4118 } else { 4119 memset(mMixBuffer, 0, mixBufferSize); 4120 } 4121 sleepTime = 0; 4122 writeFrames = mNormalFrameCount; 4123 mCurrentWriteLength = mixBufferSize; 4124 standbyTime = systemTime() + standbyDelay; 4125} 4126 4127void AudioFlinger::DuplicatingThread::threadLoop_sleepTime() 4128{ 4129 if (sleepTime == 0) { 4130 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 4131 sleepTime = activeSleepTime; 4132 } else { 4133 sleepTime = idleSleepTime; 4134 } 4135 } else if (mBytesWritten != 0) { 4136 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 4137 writeFrames = mNormalFrameCount; 4138 memset(mMixBuffer, 0, mixBufferSize); 4139 } else { 4140 // flush remaining overflow buffers in output tracks 4141 writeFrames = 0; 4142 } 4143 sleepTime = 0; 4144 } 4145} 4146 4147ssize_t AudioFlinger::DuplicatingThread::threadLoop_write() 4148{ 4149 for (size_t i = 0; i < outputTracks.size(); i++) { 4150 outputTracks[i]->write(mMixBuffer, writeFrames); 4151 } 4152 return (ssize_t)mixBufferSize; 4153} 4154 4155void AudioFlinger::DuplicatingThread::threadLoop_standby() 4156{ 4157 // DuplicatingThread implements standby by stopping all tracks 4158 for (size_t i = 0; i < outputTracks.size(); i++) { 4159 outputTracks[i]->stop(); 4160 } 4161} 4162 4163void AudioFlinger::DuplicatingThread::saveOutputTracks() 4164{ 4165 outputTracks = mOutputTracks; 4166} 4167 4168void AudioFlinger::DuplicatingThread::clearOutputTracks() 4169{ 4170 outputTracks.clear(); 4171} 4172 4173void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread) 4174{ 4175 Mutex::Autolock _l(mLock); 4176 // FIXME explain this formula 4177 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate(); 4178 OutputTrack *outputTrack = new OutputTrack(thread, 4179 this, 4180 mSampleRate, 4181 mFormat, 4182 mChannelMask, 4183 frameCount); 4184 if (outputTrack->cblk() != NULL) { 4185 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f); 4186 mOutputTracks.add(outputTrack); 4187 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread); 4188 updateWaitTime_l(); 4189 } 4190} 4191 4192void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread) 4193{ 4194 Mutex::Autolock _l(mLock); 4195 for (size_t i = 0; i < mOutputTracks.size(); i++) { 4196 if (mOutputTracks[i]->thread() == thread) { 4197 mOutputTracks[i]->destroy(); 4198 mOutputTracks.removeAt(i); 4199 updateWaitTime_l(); 4200 return; 4201 } 4202 } 4203 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread); 4204} 4205 4206// caller must hold mLock 4207void AudioFlinger::DuplicatingThread::updateWaitTime_l() 4208{ 4209 mWaitTimeMs = UINT_MAX; 4210 for (size_t i = 0; i < mOutputTracks.size(); i++) { 4211 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote(); 4212 if (strong != 0) { 4213 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate(); 4214 if (waitTimeMs < mWaitTimeMs) { 4215 mWaitTimeMs = waitTimeMs; 4216 } 4217 } 4218 } 4219} 4220 4221 4222bool AudioFlinger::DuplicatingThread::outputsReady( 4223 const SortedVector< sp<OutputTrack> > &outputTracks) 4224{ 4225 for (size_t i = 0; i < outputTracks.size(); i++) { 4226 sp<ThreadBase> thread = outputTracks[i]->thread().promote(); 4227 if (thread == 0) { 4228 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", 4229 outputTracks[i].get()); 4230 return false; 4231 } 4232 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 4233 // see note at standby() declaration 4234 if (playbackThread->standby() && !playbackThread->isSuspended()) { 4235 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), 4236 thread.get()); 4237 return false; 4238 } 4239 } 4240 return true; 4241} 4242 4243uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const 4244{ 4245 return (mWaitTimeMs * 1000) / 2; 4246} 4247 4248void AudioFlinger::DuplicatingThread::cacheParameters_l() 4249{ 4250 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first 4251 updateWaitTime_l(); 4252 4253 MixerThread::cacheParameters_l(); 4254} 4255 4256// ---------------------------------------------------------------------------- 4257// Record 4258// ---------------------------------------------------------------------------- 4259 4260AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, 4261 AudioStreamIn *input, 4262 uint32_t sampleRate, 4263 audio_channel_mask_t channelMask, 4264 audio_io_handle_t id, 4265 audio_devices_t outDevice, 4266 audio_devices_t inDevice 4267#ifdef TEE_SINK 4268 , const sp<NBAIO_Sink>& teeSink 4269#endif 4270 ) : 4271 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD), 4272 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL), 4273 // mRsmpInIndex set by readInputParameters() 4274 mReqChannelCount(popcount(channelMask)), 4275 mReqSampleRate(sampleRate) 4276 // mBytesRead is only meaningful while active, and so is cleared in start() 4277 // (but might be better to also clear here for dump?) 4278#ifdef TEE_SINK 4279 , mTeeSink(teeSink) 4280#endif 4281{ 4282 snprintf(mName, kNameLength, "AudioIn_%X", id); 4283 4284 readInputParameters(); 4285 4286} 4287 4288 4289AudioFlinger::RecordThread::~RecordThread() 4290{ 4291 delete[] mRsmpInBuffer; 4292 delete mResampler; 4293 delete[] mRsmpOutBuffer; 4294} 4295 4296void AudioFlinger::RecordThread::onFirstRef() 4297{ 4298 run(mName, PRIORITY_URGENT_AUDIO); 4299} 4300 4301bool AudioFlinger::RecordThread::threadLoop() 4302{ 4303 AudioBufferProvider::Buffer buffer; 4304 4305 nsecs_t lastWarning = 0; 4306 4307 inputStandBy(); 4308 acquireWakeLock(); 4309 4310 // used to verify we've read at least once before evaluating how many bytes were read 4311 bool readOnce = false; 4312 4313 // used to request a deferred sleep, to be executed later while mutex is unlocked 4314 bool doSleep = false; 4315 4316 // start recording 4317 for (;;) { 4318 sp<RecordTrack> activeTrack; 4319 TrackBase::track_state activeTrackState; 4320 Vector< sp<EffectChain> > effectChains; 4321 4322 // sleep with mutex unlocked 4323 if (doSleep) { 4324 doSleep = false; 4325 usleep(kRecordThreadSleepUs); 4326 } 4327 4328 { // scope for mLock 4329 Mutex::Autolock _l(mLock); 4330 if (exitPending()) { 4331 break; 4332 } 4333 processConfigEvents_l(); 4334 // return value 'reconfig' is currently unused 4335 bool reconfig = checkForNewParameters_l(); 4336 // make a stable copy of mActiveTrack 4337 activeTrack = mActiveTrack; 4338 if (activeTrack == 0) { 4339 standby(); 4340 // exitPending() can't become true here 4341 releaseWakeLock_l(); 4342 ALOGV("RecordThread: loop stopping"); 4343 // go to sleep 4344 mWaitWorkCV.wait(mLock); 4345 ALOGV("RecordThread: loop starting"); 4346 acquireWakeLock_l(); 4347 continue; 4348 } 4349 4350 if (activeTrack->isTerminated()) { 4351 removeTrack_l(activeTrack); 4352 mActiveTrack.clear(); 4353 continue; 4354 } 4355 4356 activeTrackState = activeTrack->mState; 4357 switch (activeTrackState) { 4358 case TrackBase::PAUSING: 4359 standby(); 4360 mActiveTrack.clear(); 4361 mStartStopCond.broadcast(); 4362 doSleep = true; 4363 continue; 4364 4365 case TrackBase::RESUMING: 4366 mStandby = false; 4367 if (mReqChannelCount != activeTrack->channelCount()) { 4368 mActiveTrack.clear(); 4369 mStartStopCond.broadcast(); 4370 continue; 4371 } 4372 if (readOnce) { 4373 mStartStopCond.broadcast(); 4374 // record start succeeds only if first read from audio input succeeds 4375 if (mBytesRead < 0) { 4376 mActiveTrack.clear(); 4377 continue; 4378 } 4379 activeTrack->mState = TrackBase::ACTIVE; 4380 } 4381 break; 4382 4383 case TrackBase::ACTIVE: 4384 break; 4385 4386 case TrackBase::IDLE: 4387 doSleep = true; 4388 continue; 4389 4390 default: 4391 LOG_FATAL("Unexpected activeTrackState %d", activeTrackState); 4392 } 4393 4394 lockEffectChains_l(effectChains); 4395 } 4396 4397 // thread mutex is now unlocked, mActiveTrack unknown, activeTrack != 0, kept, immutable 4398 // activeTrack->mState unknown, activeTrackState immutable and is ACTIVE or RESUMING 4399 4400 for (size_t i = 0; i < effectChains.size(); i ++) { 4401 // thread mutex is not locked, but effect chain is locked 4402 effectChains[i]->process_l(); 4403 } 4404 4405 buffer.frameCount = mFrameCount; 4406 status_t status = activeTrack->getNextBuffer(&buffer); 4407 if (status == NO_ERROR) { 4408 readOnce = true; 4409 size_t framesOut = buffer.frameCount; 4410 if (mResampler == NULL) { 4411 // no resampling 4412 while (framesOut) { 4413 size_t framesIn = mFrameCount - mRsmpInIndex; 4414 if (framesIn > 0) { 4415 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize; 4416 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * 4417 activeTrack->mFrameSize; 4418 if (framesIn > framesOut) { 4419 framesIn = framesOut; 4420 } 4421 mRsmpInIndex += framesIn; 4422 framesOut -= framesIn; 4423 if (mChannelCount == mReqChannelCount) { 4424 memcpy(dst, src, framesIn * mFrameSize); 4425 } else { 4426 if (mChannelCount == 1) { 4427 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, 4428 (int16_t *)src, framesIn); 4429 } else { 4430 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, 4431 (int16_t *)src, framesIn); 4432 } 4433 } 4434 } 4435 if (framesOut > 0 && mFrameCount == mRsmpInIndex) { 4436 void *readInto; 4437 if (framesOut == mFrameCount && mChannelCount == mReqChannelCount) { 4438 readInto = buffer.raw; 4439 framesOut = 0; 4440 } else { 4441 readInto = mRsmpInBuffer; 4442 mRsmpInIndex = 0; 4443 } 4444 mBytesRead = mInput->stream->read(mInput->stream, readInto, 4445 mBufferSize); 4446 if (mBytesRead <= 0) { 4447 // TODO: verify that it's benign to use a stale track state 4448 if ((mBytesRead < 0) && (activeTrackState == TrackBase::ACTIVE)) 4449 { 4450 ALOGE("Error reading audio input"); 4451 // Force input into standby so that it tries to 4452 // recover at next read attempt 4453 inputStandBy(); 4454 doSleep = true; 4455 } 4456 mRsmpInIndex = mFrameCount; 4457 framesOut = 0; 4458 buffer.frameCount = 0; 4459 } 4460#ifdef TEE_SINK 4461 else if (mTeeSink != 0) { 4462 (void) mTeeSink->write(readInto, 4463 mBytesRead >> Format_frameBitShift(mTeeSink->format())); 4464 } 4465#endif 4466 } 4467 } 4468 } else { 4469 // resampling 4470 4471 // resampler accumulates, but we only have one source track 4472 memset(mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t)); 4473 // alter output frame count as if we were expecting stereo samples 4474 if (mChannelCount == 1 && mReqChannelCount == 1) { 4475 framesOut >>= 1; 4476 } 4477 mResampler->resample(mRsmpOutBuffer, framesOut, 4478 this /* AudioBufferProvider* */); 4479 // ditherAndClamp() works as long as all buffers returned by 4480 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true. 4481 if (mChannelCount == 2 && mReqChannelCount == 1) { 4482 // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t 4483 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut); 4484 // the resampler always outputs stereo samples: 4485 // do post stereo to mono conversion 4486 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer, 4487 framesOut); 4488 } else { 4489 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut); 4490 } 4491 // now done with mRsmpOutBuffer 4492 4493 } 4494 if (mFramestoDrop == 0) { 4495 activeTrack->releaseBuffer(&buffer); 4496 } else { 4497 if (mFramestoDrop > 0) { 4498 mFramestoDrop -= buffer.frameCount; 4499 if (mFramestoDrop <= 0) { 4500 clearSyncStartEvent(); 4501 } 4502 } else { 4503 mFramestoDrop += buffer.frameCount; 4504 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 || 4505 mSyncStartEvent->isCancelled()) { 4506 ALOGW("Synced record %s, session %d, trigger session %d", 4507 (mFramestoDrop >= 0) ? "timed out" : "cancelled", 4508 activeTrack->sessionId(), 4509 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0); 4510 clearSyncStartEvent(); 4511 } 4512 } 4513 } 4514 activeTrack->clearOverflow(); 4515 } 4516 // client isn't retrieving buffers fast enough 4517 else { 4518 if (!activeTrack->setOverflow()) { 4519 nsecs_t now = systemTime(); 4520 if ((now - lastWarning) > kWarningThrottleNs) { 4521 ALOGW("RecordThread: buffer overflow"); 4522 lastWarning = now; 4523 } 4524 } 4525 // Release the processor for a while before asking for a new buffer. 4526 // This will give the application more chance to read from the buffer and 4527 // clear the overflow. 4528 doSleep = true; 4529 } 4530 4531 // enable changes in effect chain 4532 unlockEffectChains(effectChains); 4533 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end 4534 } 4535 4536 standby(); 4537 4538 { 4539 Mutex::Autolock _l(mLock); 4540 for (size_t i = 0; i < mTracks.size(); i++) { 4541 sp<RecordTrack> track = mTracks[i]; 4542 track->invalidate(); 4543 } 4544 mActiveTrack.clear(); 4545 mStartStopCond.broadcast(); 4546 } 4547 4548 releaseWakeLock(); 4549 4550 ALOGV("RecordThread %p exiting", this); 4551 return false; 4552} 4553 4554void AudioFlinger::RecordThread::standby() 4555{ 4556 if (!mStandby) { 4557 inputStandBy(); 4558 mStandby = true; 4559 } 4560} 4561 4562void AudioFlinger::RecordThread::inputStandBy() 4563{ 4564 mInput->stream->common.standby(&mInput->stream->common); 4565} 4566 4567sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l( 4568 const sp<AudioFlinger::Client>& client, 4569 uint32_t sampleRate, 4570 audio_format_t format, 4571 audio_channel_mask_t channelMask, 4572 size_t frameCount, 4573 int sessionId, 4574 IAudioFlinger::track_flags_t *flags, 4575 pid_t tid, 4576 status_t *status) 4577{ 4578 sp<RecordTrack> track; 4579 status_t lStatus; 4580 4581 lStatus = initCheck(); 4582 if (lStatus != NO_ERROR) { 4583 ALOGE("Audio driver not initialized."); 4584 goto Exit; 4585 } 4586 4587 // client expresses a preference for FAST, but we get the final say 4588 if (*flags & IAudioFlinger::TRACK_FAST) { 4589 if ( 4590 // use case: callback handler and frame count is default or at least as large as HAL 4591 ( 4592 (tid != -1) && 4593 ((frameCount == 0) || 4594 (frameCount >= (mFrameCount * kFastTrackMultiplier))) 4595 ) && 4596 // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format) 4597 // mono or stereo 4598 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) || 4599 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) && 4600 // hardware sample rate 4601 (sampleRate == mSampleRate) && 4602 // record thread has an associated fast recorder 4603 hasFastRecorder() 4604 // FIXME test that RecordThread for this fast track has a capable output HAL 4605 // FIXME add a permission test also? 4606 ) { 4607 // if frameCount not specified, then it defaults to fast recorder (HAL) frame count 4608 if (frameCount == 0) { 4609 frameCount = mFrameCount * kFastTrackMultiplier; 4610 } 4611 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d", 4612 frameCount, mFrameCount); 4613 } else { 4614 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d " 4615 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u " 4616 "hasFastRecorder=%d tid=%d", 4617 frameCount, mFrameCount, format, 4618 audio_is_linear_pcm(format), 4619 channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid); 4620 *flags &= ~IAudioFlinger::TRACK_FAST; 4621 // For compatibility with AudioRecord calculation, buffer depth is forced 4622 // to be at least 2 x the record thread frame count and cover audio hardware latency. 4623 // This is probably too conservative, but legacy application code may depend on it. 4624 // If you change this calculation, also review the start threshold which is related. 4625 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream); 4626 size_t mNormalFrameCount = 2048; // FIXME 4627 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate); 4628 if (minBufCount < 2) { 4629 minBufCount = 2; 4630 } 4631 size_t minFrameCount = mNormalFrameCount * minBufCount; 4632 if (frameCount < minFrameCount) { 4633 frameCount = minFrameCount; 4634 } 4635 } 4636 } 4637 4638 // FIXME use flags and tid similar to createTrack_l() 4639 4640 { // scope for mLock 4641 Mutex::Autolock _l(mLock); 4642 4643 track = new RecordTrack(this, client, sampleRate, 4644 format, channelMask, frameCount, sessionId); 4645 4646 lStatus = track->initCheck(); 4647 if (lStatus != NO_ERROR) { 4648 track.clear(); 4649 goto Exit; 4650 } 4651 mTracks.add(track); 4652 4653 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 4654 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 4655 mAudioFlinger->btNrecIsOff(); 4656 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId); 4657 setEffectSuspended_l(FX_IID_NS, suspend, sessionId); 4658 4659 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) { 4660 pid_t callingPid = IPCThreadState::self()->getCallingPid(); 4661 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful, 4662 // so ask activity manager to do this on our behalf 4663 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp); 4664 } 4665 } 4666 lStatus = NO_ERROR; 4667 4668Exit: 4669 *status = lStatus; 4670 return track; 4671} 4672 4673status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, 4674 AudioSystem::sync_event_t event, 4675 int triggerSession) 4676{ 4677 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession); 4678 sp<ThreadBase> strongMe = this; 4679 status_t status = NO_ERROR; 4680 4681 if (event == AudioSystem::SYNC_EVENT_NONE) { 4682 clearSyncStartEvent(); 4683 } else if (event != AudioSystem::SYNC_EVENT_SAME) { 4684 mSyncStartEvent = mAudioFlinger->createSyncEvent(event, 4685 triggerSession, 4686 recordTrack->sessionId(), 4687 syncStartEventCallback, 4688 this); 4689 // Sync event can be cancelled by the trigger session if the track is not in a 4690 // compatible state in which case we start record immediately 4691 if (mSyncStartEvent->isCancelled()) { 4692 clearSyncStartEvent(); 4693 } else { 4694 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs 4695 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000); 4696 } 4697 } 4698 4699 { 4700 // This section is a rendezvous between binder thread executing start() and RecordThread 4701 AutoMutex lock(mLock); 4702 if (mActiveTrack != 0) { 4703 if (recordTrack != mActiveTrack.get()) { 4704 status = -EBUSY; 4705 } else if (mActiveTrack->mState == TrackBase::PAUSING) { 4706 mActiveTrack->mState = TrackBase::ACTIVE; 4707 } 4708 return status; 4709 } 4710 4711 // FIXME why? already set in constructor, 'STARTING_1' would be more accurate 4712 recordTrack->mState = TrackBase::IDLE; 4713 mActiveTrack = recordTrack; 4714 mLock.unlock(); 4715 status_t status = AudioSystem::startInput(mId); 4716 mLock.lock(); 4717 // FIXME should verify that mActiveTrack is still == recordTrack 4718 if (status != NO_ERROR) { 4719 mActiveTrack.clear(); 4720 clearSyncStartEvent(); 4721 return status; 4722 } 4723 mRsmpInIndex = mFrameCount; 4724 mBytesRead = 0; 4725 if (mResampler != NULL) { 4726 mResampler->reset(); 4727 } 4728 // FIXME hijacking a playback track state name which was intended for start after pause; 4729 // here 'STARTING_2' would be more accurate 4730 mActiveTrack->mState = TrackBase::RESUMING; 4731 // signal thread to start 4732 ALOGV("Signal record thread"); 4733 mWaitWorkCV.broadcast(); 4734 // do not wait for mStartStopCond if exiting 4735 if (exitPending()) { 4736 mActiveTrack.clear(); 4737 status = INVALID_OPERATION; 4738 goto startError; 4739 } 4740 // FIXME incorrect usage of wait: no explicit predicate or loop 4741 mStartStopCond.wait(mLock); 4742 if (mActiveTrack == 0) { 4743 ALOGV("Record failed to start"); 4744 status = BAD_VALUE; 4745 goto startError; 4746 } 4747 ALOGV("Record started OK"); 4748 return status; 4749 } 4750 4751startError: 4752 AudioSystem::stopInput(mId); 4753 clearSyncStartEvent(); 4754 return status; 4755} 4756 4757void AudioFlinger::RecordThread::clearSyncStartEvent() 4758{ 4759 if (mSyncStartEvent != 0) { 4760 mSyncStartEvent->cancel(); 4761 } 4762 mSyncStartEvent.clear(); 4763 mFramestoDrop = 0; 4764} 4765 4766void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event) 4767{ 4768 sp<SyncEvent> strongEvent = event.promote(); 4769 4770 if (strongEvent != 0) { 4771 RecordThread *me = (RecordThread *)strongEvent->cookie(); 4772 me->handleSyncStartEvent(strongEvent); 4773 } 4774} 4775 4776void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event) 4777{ 4778 if (event == mSyncStartEvent) { 4779 // TODO: use actual buffer filling status instead of 2 buffers when info is available 4780 // from audio HAL 4781 mFramestoDrop = mFrameCount * 2; 4782 } 4783} 4784 4785bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) { 4786 ALOGV("RecordThread::stop"); 4787 AutoMutex _l(mLock); 4788 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) { 4789 return false; 4790 } 4791 // note that threadLoop may still be processing the track at this point [without lock] 4792 recordTrack->mState = TrackBase::PAUSING; 4793 // do not wait for mStartStopCond if exiting 4794 if (exitPending()) { 4795 return true; 4796 } 4797 // FIXME incorrect usage of wait: no explicit predicate or loop 4798 mStartStopCond.wait(mLock); 4799 // if we have been restarted, recordTrack == mActiveTrack.get() here 4800 if (exitPending() || recordTrack != mActiveTrack.get()) { 4801 ALOGV("Record stopped OK"); 4802 return true; 4803 } 4804 return false; 4805} 4806 4807bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const 4808{ 4809 return false; 4810} 4811 4812status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event) 4813{ 4814#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future 4815 if (!isValidSyncEvent(event)) { 4816 return BAD_VALUE; 4817 } 4818 4819 int eventSession = event->triggerSession(); 4820 status_t ret = NAME_NOT_FOUND; 4821 4822 Mutex::Autolock _l(mLock); 4823 4824 for (size_t i = 0; i < mTracks.size(); i++) { 4825 sp<RecordTrack> track = mTracks[i]; 4826 if (eventSession == track->sessionId()) { 4827 (void) track->setSyncEvent(event); 4828 ret = NO_ERROR; 4829 } 4830 } 4831 return ret; 4832#else 4833 return BAD_VALUE; 4834#endif 4835} 4836 4837// destroyTrack_l() must be called with ThreadBase::mLock held 4838void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track) 4839{ 4840 track->terminate(); 4841 track->mState = TrackBase::STOPPED; 4842 // active tracks are removed by threadLoop() 4843 if (mActiveTrack != track) { 4844 removeTrack_l(track); 4845 } 4846} 4847 4848void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track) 4849{ 4850 mTracks.remove(track); 4851 // need anything related to effects here? 4852} 4853 4854void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args) 4855{ 4856 dumpInternals(fd, args); 4857 dumpTracks(fd, args); 4858 dumpEffectChains(fd, args); 4859} 4860 4861void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args) 4862{ 4863 const size_t SIZE = 256; 4864 char buffer[SIZE]; 4865 String8 result; 4866 4867 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this); 4868 result.append(buffer); 4869 4870 if (mActiveTrack != 0) { 4871 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex); 4872 result.append(buffer); 4873 snprintf(buffer, SIZE, "Buffer size: %u bytes\n", mBufferSize); 4874 result.append(buffer); 4875 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL)); 4876 result.append(buffer); 4877 snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount); 4878 result.append(buffer); 4879 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate); 4880 result.append(buffer); 4881 } else { 4882 result.append("No active record client\n"); 4883 } 4884 4885 write(fd, result.string(), result.size()); 4886 4887 dumpBase(fd, args); 4888} 4889 4890void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args) 4891{ 4892 const size_t SIZE = 256; 4893 char buffer[SIZE]; 4894 String8 result; 4895 4896 snprintf(buffer, SIZE, "Input thread %p tracks\n", this); 4897 result.append(buffer); 4898 RecordTrack::appendDumpHeader(result); 4899 for (size_t i = 0; i < mTracks.size(); ++i) { 4900 sp<RecordTrack> track = mTracks[i]; 4901 if (track != 0) { 4902 track->dump(buffer, SIZE); 4903 result.append(buffer); 4904 } 4905 } 4906 4907 if (mActiveTrack != 0) { 4908 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this); 4909 result.append(buffer); 4910 RecordTrack::appendDumpHeader(result); 4911 mActiveTrack->dump(buffer, SIZE); 4912 result.append(buffer); 4913 4914 } 4915 write(fd, result.string(), result.size()); 4916} 4917 4918// AudioBufferProvider interface 4919status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts) 4920{ 4921 size_t framesReq = buffer->frameCount; 4922 size_t framesReady = mFrameCount - mRsmpInIndex; 4923 int channelCount; 4924 4925 if (framesReady == 0) { 4926 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mBufferSize); 4927 if (mBytesRead <= 0) { 4928 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) { 4929 ALOGE("RecordThread::getNextBuffer() Error reading audio input"); 4930 // Force input into standby so that it tries to 4931 // recover at next read attempt 4932 inputStandBy(); 4933 // FIXME an awkward place to sleep, consider using doSleep when this is pulled up 4934 usleep(kRecordThreadSleepUs); 4935 } 4936 buffer->raw = NULL; 4937 buffer->frameCount = 0; 4938 return NOT_ENOUGH_DATA; 4939 } 4940 mRsmpInIndex = 0; 4941 framesReady = mFrameCount; 4942 } 4943 4944 if (framesReq > framesReady) { 4945 framesReq = framesReady; 4946 } 4947 4948 if (mChannelCount == 1 && mReqChannelCount == 2) { 4949 channelCount = 1; 4950 } else { 4951 channelCount = 2; 4952 } 4953 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount; 4954 buffer->frameCount = framesReq; 4955 return NO_ERROR; 4956} 4957 4958// AudioBufferProvider interface 4959void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer) 4960{ 4961 mRsmpInIndex += buffer->frameCount; 4962 buffer->frameCount = 0; 4963} 4964 4965bool AudioFlinger::RecordThread::checkForNewParameters_l() 4966{ 4967 bool reconfig = false; 4968 4969 while (!mNewParameters.isEmpty()) { 4970 status_t status = NO_ERROR; 4971 String8 keyValuePair = mNewParameters[0]; 4972 AudioParameter param = AudioParameter(keyValuePair); 4973 int value; 4974 audio_format_t reqFormat = mFormat; 4975 uint32_t reqSamplingRate = mReqSampleRate; 4976 audio_channel_mask_t reqChannelMask = audio_channel_in_mask_from_count(mReqChannelCount); 4977 4978 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { 4979 reqSamplingRate = value; 4980 reconfig = true; 4981 } 4982 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { 4983 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) { 4984 status = BAD_VALUE; 4985 } else { 4986 reqFormat = (audio_format_t) value; 4987 reconfig = true; 4988 } 4989 } 4990 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { 4991 audio_channel_mask_t mask = (audio_channel_mask_t) value; 4992 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) { 4993 status = BAD_VALUE; 4994 } else { 4995 reqChannelMask = mask; 4996 reconfig = true; 4997 } 4998 } 4999 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 5000 // do not accept frame count changes if tracks are open as the track buffer 5001 // size depends on frame count and correct behavior would not be guaranteed 5002 // if frame count is changed after track creation 5003 if (mActiveTrack != 0) { 5004 status = INVALID_OPERATION; 5005 } else { 5006 reconfig = true; 5007 } 5008 } 5009 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 5010 // forward device change to effects that have requested to be 5011 // aware of attached audio device. 5012 for (size_t i = 0; i < mEffectChains.size(); i++) { 5013 mEffectChains[i]->setDevice_l(value); 5014 } 5015 5016 // store input device and output device but do not forward output device to audio HAL. 5017 // Note that status is ignored by the caller for output device 5018 // (see AudioFlinger::setParameters() 5019 if (audio_is_output_devices(value)) { 5020 mOutDevice = value; 5021 status = BAD_VALUE; 5022 } else { 5023 mInDevice = value; 5024 // disable AEC and NS if the device is a BT SCO headset supporting those 5025 // pre processings 5026 if (mTracks.size() > 0) { 5027 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 5028 mAudioFlinger->btNrecIsOff(); 5029 for (size_t i = 0; i < mTracks.size(); i++) { 5030 sp<RecordTrack> track = mTracks[i]; 5031 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId()); 5032 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId()); 5033 } 5034 } 5035 } 5036 } 5037 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR && 5038 mAudioSource != (audio_source_t)value) { 5039 // forward device change to effects that have requested to be 5040 // aware of attached audio device. 5041 for (size_t i = 0; i < mEffectChains.size(); i++) { 5042 mEffectChains[i]->setAudioSource_l((audio_source_t)value); 5043 } 5044 mAudioSource = (audio_source_t)value; 5045 } 5046 5047 if (status == NO_ERROR) { 5048 status = mInput->stream->common.set_parameters(&mInput->stream->common, 5049 keyValuePair.string()); 5050 if (status == INVALID_OPERATION) { 5051 inputStandBy(); 5052 status = mInput->stream->common.set_parameters(&mInput->stream->common, 5053 keyValuePair.string()); 5054 } 5055 if (reconfig) { 5056 if (status == BAD_VALUE && 5057 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) && 5058 reqFormat == AUDIO_FORMAT_PCM_16_BIT && 5059 (mInput->stream->common.get_sample_rate(&mInput->stream->common) 5060 <= (2 * reqSamplingRate)) && 5061 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) 5062 <= FCC_2 && 5063 (reqChannelMask == AUDIO_CHANNEL_IN_MONO || 5064 reqChannelMask == AUDIO_CHANNEL_IN_STEREO)) { 5065 status = NO_ERROR; 5066 } 5067 if (status == NO_ERROR) { 5068 readInputParameters(); 5069 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED); 5070 } 5071 } 5072 } 5073 5074 mNewParameters.removeAt(0); 5075 5076 mParamStatus = status; 5077 mParamCond.signal(); 5078 // wait for condition with time out in case the thread calling ThreadBase::setParameters() 5079 // already timed out waiting for the status and will never signal the condition. 5080 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); 5081 } 5082 return reconfig; 5083} 5084 5085String8 AudioFlinger::RecordThread::getParameters(const String8& keys) 5086{ 5087 Mutex::Autolock _l(mLock); 5088 if (initCheck() != NO_ERROR) { 5089 return String8(); 5090 } 5091 5092 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string()); 5093 const String8 out_s8(s); 5094 free(s); 5095 return out_s8; 5096} 5097 5098void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) { 5099 AudioSystem::OutputDescriptor desc; 5100 void *param2 = NULL; 5101 5102 switch (event) { 5103 case AudioSystem::INPUT_OPENED: 5104 case AudioSystem::INPUT_CONFIG_CHANGED: 5105 desc.channelMask = mChannelMask; 5106 desc.samplingRate = mSampleRate; 5107 desc.format = mFormat; 5108 desc.frameCount = mFrameCount; 5109 desc.latency = 0; 5110 param2 = &desc; 5111 break; 5112 5113 case AudioSystem::INPUT_CLOSED: 5114 default: 5115 break; 5116 } 5117 mAudioFlinger->audioConfigChanged_l(event, mId, param2); 5118} 5119 5120void AudioFlinger::RecordThread::readInputParameters() 5121{ 5122 delete[] mRsmpInBuffer; 5123 // mRsmpInBuffer is always assigned a new[] below 5124 delete[] mRsmpOutBuffer; 5125 mRsmpOutBuffer = NULL; 5126 delete mResampler; 5127 mResampler = NULL; 5128 5129 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common); 5130 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common); 5131 mChannelCount = popcount(mChannelMask); 5132 mFormat = mInput->stream->common.get_format(&mInput->stream->common); 5133 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) { 5134 ALOGE("HAL format %d not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat); 5135 } 5136 mFrameSize = audio_stream_frame_size(&mInput->stream->common); 5137 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common); 5138 mFrameCount = mBufferSize / mFrameSize; 5139 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount]; 5140 5141 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2) { 5142 int channelCount; 5143 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid 5144 // stereo to mono post process as the resampler always outputs stereo. 5145 if (mChannelCount == 1 && mReqChannelCount == 2) { 5146 channelCount = 1; 5147 } else { 5148 channelCount = 2; 5149 } 5150 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate); 5151 mResampler->setSampleRate(mSampleRate); 5152 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN); 5153 mRsmpOutBuffer = new int32_t[mFrameCount * FCC_2]; 5154 5155 // optmization: if mono to mono, alter input frame count as if we were inputing 5156 // stereo samples 5157 if (mChannelCount == 1 && mReqChannelCount == 1) { 5158 mFrameCount >>= 1; 5159 } 5160 5161 } 5162 mRsmpInIndex = mFrameCount; 5163} 5164 5165unsigned int AudioFlinger::RecordThread::getInputFramesLost() 5166{ 5167 Mutex::Autolock _l(mLock); 5168 if (initCheck() != NO_ERROR) { 5169 return 0; 5170 } 5171 5172 return mInput->stream->get_input_frames_lost(mInput->stream); 5173} 5174 5175uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const 5176{ 5177 Mutex::Autolock _l(mLock); 5178 uint32_t result = 0; 5179 if (getEffectChain_l(sessionId) != 0) { 5180 result = EFFECT_SESSION; 5181 } 5182 5183 for (size_t i = 0; i < mTracks.size(); ++i) { 5184 if (sessionId == mTracks[i]->sessionId()) { 5185 result |= TRACK_SESSION; 5186 break; 5187 } 5188 } 5189 5190 return result; 5191} 5192 5193KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const 5194{ 5195 KeyedVector<int, bool> ids; 5196 Mutex::Autolock _l(mLock); 5197 for (size_t j = 0; j < mTracks.size(); ++j) { 5198 sp<RecordThread::RecordTrack> track = mTracks[j]; 5199 int sessionId = track->sessionId(); 5200 if (ids.indexOfKey(sessionId) < 0) { 5201 ids.add(sessionId, true); 5202 } 5203 } 5204 return ids; 5205} 5206 5207AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput() 5208{ 5209 Mutex::Autolock _l(mLock); 5210 AudioStreamIn *input = mInput; 5211 mInput = NULL; 5212 return input; 5213} 5214 5215// this method must always be called either with ThreadBase mLock held or inside the thread loop 5216audio_stream_t* AudioFlinger::RecordThread::stream() const 5217{ 5218 if (mInput == NULL) { 5219 return NULL; 5220 } 5221 return &mInput->stream->common; 5222} 5223 5224status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain) 5225{ 5226 // only one chain per input thread 5227 if (mEffectChains.size() != 0) { 5228 return INVALID_OPERATION; 5229 } 5230 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this); 5231 5232 chain->setInBuffer(NULL); 5233 chain->setOutBuffer(NULL); 5234 5235 checkSuspendOnAddEffectChain_l(chain); 5236 5237 mEffectChains.add(chain); 5238 5239 return NO_ERROR; 5240} 5241 5242size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain) 5243{ 5244 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this); 5245 ALOGW_IF(mEffectChains.size() != 1, 5246 "removeEffectChain_l() %p invalid chain size %d on thread %p", 5247 chain.get(), mEffectChains.size(), this); 5248 if (mEffectChains.size() == 1) { 5249 mEffectChains.removeAt(0); 5250 } 5251 return 0; 5252} 5253 5254}; // namespace android 5255