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