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