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