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