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