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