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