Threads.cpp revision 3523e8c40bc60af0c95d1aa71a51a13d69ec80a2
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: %d\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: %u\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 %02d ", 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, " %d 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: %d\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(size_t *halFrames, size_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 return mOutput->stream->get_render_position(mOutput->stream, dspFrames); 1798 } 1799} 1800 1801uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const 1802{ 1803 Mutex::Autolock _l(mLock); 1804 uint32_t result = 0; 1805 if (getEffectChain_l(sessionId) != 0) { 1806 result = EFFECT_SESSION; 1807 } 1808 1809 for (size_t i = 0; i < mTracks.size(); ++i) { 1810 sp<Track> track = mTracks[i]; 1811 if (sessionId == track->sessionId() && !track->isInvalid()) { 1812 result |= TRACK_SESSION; 1813 break; 1814 } 1815 } 1816 1817 return result; 1818} 1819 1820uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId) 1821{ 1822 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that 1823 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected 1824 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) { 1825 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); 1826 } 1827 for (size_t i = 0; i < mTracks.size(); i++) { 1828 sp<Track> track = mTracks[i]; 1829 if (sessionId == track->sessionId() && !track->isInvalid()) { 1830 return AudioSystem::getStrategyForStream(track->streamType()); 1831 } 1832 } 1833 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); 1834} 1835 1836 1837AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const 1838{ 1839 Mutex::Autolock _l(mLock); 1840 return mOutput; 1841} 1842 1843AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput() 1844{ 1845 Mutex::Autolock _l(mLock); 1846 AudioStreamOut *output = mOutput; 1847 mOutput = NULL; 1848 // FIXME FastMixer might also have a raw ptr to mOutputSink; 1849 // must push a NULL and wait for ack 1850 mOutputSink.clear(); 1851 mPipeSink.clear(); 1852 mNormalSink.clear(); 1853 return output; 1854} 1855 1856// this method must always be called either with ThreadBase mLock held or inside the thread loop 1857audio_stream_t* AudioFlinger::PlaybackThread::stream() const 1858{ 1859 if (mOutput == NULL) { 1860 return NULL; 1861 } 1862 return &mOutput->stream->common; 1863} 1864 1865uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const 1866{ 1867 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000); 1868} 1869 1870status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event) 1871{ 1872 if (!isValidSyncEvent(event)) { 1873 return BAD_VALUE; 1874 } 1875 1876 Mutex::Autolock _l(mLock); 1877 1878 for (size_t i = 0; i < mTracks.size(); ++i) { 1879 sp<Track> track = mTracks[i]; 1880 if (event->triggerSession() == track->sessionId()) { 1881 (void) track->setSyncEvent(event); 1882 return NO_ERROR; 1883 } 1884 } 1885 1886 return NAME_NOT_FOUND; 1887} 1888 1889bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const 1890{ 1891 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE; 1892} 1893 1894void AudioFlinger::PlaybackThread::threadLoop_removeTracks( 1895 const Vector< sp<Track> >& tracksToRemove) 1896{ 1897 size_t count = tracksToRemove.size(); 1898 if (count > 0) { 1899 for (size_t i = 0 ; i < count ; i++) { 1900 const sp<Track>& track = tracksToRemove.itemAt(i); 1901 if (!track->isOutputTrack()) { 1902 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId()); 1903#ifdef ADD_BATTERY_DATA 1904 // to track the speaker usage 1905 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop); 1906#endif 1907 if (track->isTerminated()) { 1908 AudioSystem::releaseOutput(mId); 1909 } 1910 } 1911 } 1912 } 1913} 1914 1915void AudioFlinger::PlaybackThread::checkSilentMode_l() 1916{ 1917 if (!mMasterMute) { 1918 char value[PROPERTY_VALUE_MAX]; 1919 if (property_get("ro.audio.silent", value, "0") > 0) { 1920 char *endptr; 1921 unsigned long ul = strtoul(value, &endptr, 0); 1922 if (*endptr == '\0' && ul != 0) { 1923 ALOGD("Silence is golden"); 1924 // The setprop command will not allow a property to be changed after 1925 // the first time it is set, so we don't have to worry about un-muting. 1926 setMasterMute_l(true); 1927 } 1928 } 1929 } 1930} 1931 1932// shared by MIXER and DIRECT, overridden by DUPLICATING 1933ssize_t AudioFlinger::PlaybackThread::threadLoop_write() 1934{ 1935 // FIXME rewrite to reduce number of system calls 1936 mLastWriteTime = systemTime(); 1937 mInWrite = true; 1938 ssize_t bytesWritten; 1939 1940 // If an NBAIO sink is present, use it to write the normal mixer's submix 1941 if (mNormalSink != 0) { 1942#define mBitShift 2 // FIXME 1943 size_t count = mBytesRemaining >> mBitShift; 1944 size_t offset = (mCurrentWriteLength - mBytesRemaining) >> 1; 1945 ATRACE_BEGIN("write"); 1946 // update the setpoint when AudioFlinger::mScreenState changes 1947 uint32_t screenState = AudioFlinger::mScreenState; 1948 if (screenState != mScreenState) { 1949 mScreenState = screenState; 1950 MonoPipe *pipe = (MonoPipe *)mPipeSink.get(); 1951 if (pipe != NULL) { 1952 pipe->setAvgFrames((mScreenState & 1) ? 1953 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2); 1954 } 1955 } 1956 ssize_t framesWritten = mNormalSink->write(mMixBuffer + offset, count); 1957 ATRACE_END(); 1958 if (framesWritten > 0) { 1959 bytesWritten = framesWritten << mBitShift; 1960 } else { 1961 bytesWritten = framesWritten; 1962 } 1963 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp); 1964 if (status == NO_ERROR) { 1965 size_t totalFramesWritten = mNormalSink->framesWritten(); 1966 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) { 1967 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition; 1968 mLatchDValid = true; 1969 } 1970 } 1971 // otherwise use the HAL / AudioStreamOut directly 1972 } else { 1973 // Direct output and offload threads 1974 size_t offset = (mCurrentWriteLength - mBytesRemaining); 1975 if (mUseAsyncWrite) { 1976 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request"); 1977 mWriteAckSequence += 2; 1978 mWriteAckSequence |= 1; 1979 ALOG_ASSERT(mCallbackThread != 0); 1980 mCallbackThread->setWriteBlocked(mWriteAckSequence); 1981 } 1982 // FIXME We should have an implementation of timestamps for direct output threads. 1983 // They are used e.g for multichannel PCM playback over HDMI. 1984 bytesWritten = mOutput->stream->write(mOutput->stream, 1985 (char *)mMixBuffer + offset, mBytesRemaining); 1986 if (mUseAsyncWrite && 1987 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) { 1988 // do not wait for async callback in case of error of full write 1989 mWriteAckSequence &= ~1; 1990 ALOG_ASSERT(mCallbackThread != 0); 1991 mCallbackThread->setWriteBlocked(mWriteAckSequence); 1992 } 1993 } 1994 1995 mNumWrites++; 1996 mInWrite = false; 1997 mStandby = false; 1998 return bytesWritten; 1999} 2000 2001void AudioFlinger::PlaybackThread::threadLoop_drain() 2002{ 2003 if (mOutput->stream->drain) { 2004 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full"); 2005 if (mUseAsyncWrite) { 2006 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request"); 2007 mDrainSequence |= 1; 2008 ALOG_ASSERT(mCallbackThread != 0); 2009 mCallbackThread->setDraining(mDrainSequence); 2010 } 2011 mOutput->stream->drain(mOutput->stream, 2012 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY 2013 : AUDIO_DRAIN_ALL); 2014 } 2015} 2016 2017void AudioFlinger::PlaybackThread::threadLoop_exit() 2018{ 2019 // Default implementation has nothing to do 2020} 2021 2022/* 2023The derived values that are cached: 2024 - mixBufferSize from frame count * frame size 2025 - activeSleepTime from activeSleepTimeUs() 2026 - idleSleepTime from idleSleepTimeUs() 2027 - standbyDelay from mActiveSleepTimeUs (DIRECT only) 2028 - maxPeriod from frame count and sample rate (MIXER only) 2029 2030The parameters that affect these derived values are: 2031 - frame count 2032 - frame size 2033 - sample rate 2034 - device type: A2DP or not 2035 - device latency 2036 - format: PCM or not 2037 - active sleep time 2038 - idle sleep time 2039*/ 2040 2041void AudioFlinger::PlaybackThread::cacheParameters_l() 2042{ 2043 mixBufferSize = mNormalFrameCount * mFrameSize; 2044 activeSleepTime = activeSleepTimeUs(); 2045 idleSleepTime = idleSleepTimeUs(); 2046} 2047 2048void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType) 2049{ 2050 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d", 2051 this, streamType, mTracks.size()); 2052 Mutex::Autolock _l(mLock); 2053 2054 size_t size = mTracks.size(); 2055 for (size_t i = 0; i < size; i++) { 2056 sp<Track> t = mTracks[i]; 2057 if (t->streamType() == streamType) { 2058 t->invalidate(); 2059 } 2060 } 2061} 2062 2063status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain) 2064{ 2065 int session = chain->sessionId(); 2066 int16_t *buffer = mMixBuffer; 2067 bool ownsBuffer = false; 2068 2069 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session); 2070 if (session > 0) { 2071 // Only one effect chain can be present in direct output thread and it uses 2072 // the mix buffer as input 2073 if (mType != DIRECT) { 2074 size_t numSamples = mNormalFrameCount * mChannelCount; 2075 buffer = new int16_t[numSamples]; 2076 memset(buffer, 0, numSamples * sizeof(int16_t)); 2077 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session); 2078 ownsBuffer = true; 2079 } 2080 2081 // Attach all tracks with same session ID to this chain. 2082 for (size_t i = 0; i < mTracks.size(); ++i) { 2083 sp<Track> track = mTracks[i]; 2084 if (session == track->sessionId()) { 2085 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), 2086 buffer); 2087 track->setMainBuffer(buffer); 2088 chain->incTrackCnt(); 2089 } 2090 } 2091 2092 // indicate all active tracks in the chain 2093 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) { 2094 sp<Track> track = mActiveTracks[i].promote(); 2095 if (track == 0) { 2096 continue; 2097 } 2098 if (session == track->sessionId()) { 2099 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session); 2100 chain->incActiveTrackCnt(); 2101 } 2102 } 2103 } 2104 2105 chain->setInBuffer(buffer, ownsBuffer); 2106 chain->setOutBuffer(mMixBuffer); 2107 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect 2108 // chains list in order to be processed last as it contains output stage effects 2109 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before 2110 // session AUDIO_SESSION_OUTPUT_STAGE to be processed 2111 // after track specific effects and before output stage 2112 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and 2113 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX 2114 // Effect chain for other sessions are inserted at beginning of effect 2115 // chains list to be processed before output mix effects. Relative order between other 2116 // sessions is not important 2117 size_t size = mEffectChains.size(); 2118 size_t i = 0; 2119 for (i = 0; i < size; i++) { 2120 if (mEffectChains[i]->sessionId() < session) { 2121 break; 2122 } 2123 } 2124 mEffectChains.insertAt(chain, i); 2125 checkSuspendOnAddEffectChain_l(chain); 2126 2127 return NO_ERROR; 2128} 2129 2130size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain) 2131{ 2132 int session = chain->sessionId(); 2133 2134 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session); 2135 2136 for (size_t i = 0; i < mEffectChains.size(); i++) { 2137 if (chain == mEffectChains[i]) { 2138 mEffectChains.removeAt(i); 2139 // detach all active tracks from the chain 2140 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) { 2141 sp<Track> track = mActiveTracks[i].promote(); 2142 if (track == 0) { 2143 continue; 2144 } 2145 if (session == track->sessionId()) { 2146 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d", 2147 chain.get(), session); 2148 chain->decActiveTrackCnt(); 2149 } 2150 } 2151 2152 // detach all tracks with same session ID from this chain 2153 for (size_t i = 0; i < mTracks.size(); ++i) { 2154 sp<Track> track = mTracks[i]; 2155 if (session == track->sessionId()) { 2156 track->setMainBuffer(mMixBuffer); 2157 chain->decTrackCnt(); 2158 } 2159 } 2160 break; 2161 } 2162 } 2163 return mEffectChains.size(); 2164} 2165 2166status_t AudioFlinger::PlaybackThread::attachAuxEffect( 2167 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId) 2168{ 2169 Mutex::Autolock _l(mLock); 2170 return attachAuxEffect_l(track, EffectId); 2171} 2172 2173status_t AudioFlinger::PlaybackThread::attachAuxEffect_l( 2174 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId) 2175{ 2176 status_t status = NO_ERROR; 2177 2178 if (EffectId == 0) { 2179 track->setAuxBuffer(0, NULL); 2180 } else { 2181 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX 2182 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId); 2183 if (effect != 0) { 2184 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 2185 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer()); 2186 } else { 2187 status = INVALID_OPERATION; 2188 } 2189 } else { 2190 status = BAD_VALUE; 2191 } 2192 } 2193 return status; 2194} 2195 2196void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId) 2197{ 2198 for (size_t i = 0; i < mTracks.size(); ++i) { 2199 sp<Track> track = mTracks[i]; 2200 if (track->auxEffectId() == effectId) { 2201 attachAuxEffect_l(track, 0); 2202 } 2203 } 2204} 2205 2206bool AudioFlinger::PlaybackThread::threadLoop() 2207{ 2208 Vector< sp<Track> > tracksToRemove; 2209 2210 standbyTime = systemTime(); 2211 2212 // MIXER 2213 nsecs_t lastWarning = 0; 2214 2215 // DUPLICATING 2216 // FIXME could this be made local to while loop? 2217 writeFrames = 0; 2218 2219 int lastGeneration = 0; 2220 2221 cacheParameters_l(); 2222 sleepTime = idleSleepTime; 2223 2224 if (mType == MIXER) { 2225 sleepTimeShift = 0; 2226 } 2227 2228 CpuStats cpuStats; 2229 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid())); 2230 2231 acquireWakeLock(); 2232 2233 // mNBLogWriter->log can only be called while thread mutex mLock is held. 2234 // So if you need to log when mutex is unlocked, set logString to a non-NULL string, 2235 // and then that string will be logged at the next convenient opportunity. 2236 const char *logString = NULL; 2237 2238 checkSilentMode_l(); 2239 2240 while (!exitPending()) 2241 { 2242 cpuStats.sample(myName); 2243 2244 Vector< sp<EffectChain> > effectChains; 2245 2246 processConfigEvents(); 2247 2248 { // scope for mLock 2249 2250 Mutex::Autolock _l(mLock); 2251 2252 if (logString != NULL) { 2253 mNBLogWriter->logTimestamp(); 2254 mNBLogWriter->log(logString); 2255 logString = NULL; 2256 } 2257 2258 if (mLatchDValid) { 2259 mLatchQ = mLatchD; 2260 mLatchDValid = false; 2261 mLatchQValid = true; 2262 } 2263 2264 if (checkForNewParameters_l()) { 2265 cacheParameters_l(); 2266 } 2267 2268 saveOutputTracks(); 2269 if (mSignalPending) { 2270 // A signal was raised while we were unlocked 2271 mSignalPending = false; 2272 } else if (waitingAsyncCallback_l()) { 2273 if (exitPending()) { 2274 break; 2275 } 2276 releaseWakeLock_l(); 2277 mWakeLockUids.clear(); 2278 mActiveTracksGeneration++; 2279 ALOGV("wait async completion"); 2280 mWaitWorkCV.wait(mLock); 2281 ALOGV("async completion/wake"); 2282 acquireWakeLock_l(); 2283 standbyTime = systemTime() + standbyDelay; 2284 sleepTime = 0; 2285 2286 continue; 2287 } 2288 if ((!mActiveTracks.size() && systemTime() > standbyTime) || 2289 isSuspended()) { 2290 // put audio hardware into standby after short delay 2291 if (shouldStandby_l()) { 2292 2293 threadLoop_standby(); 2294 2295 mStandby = true; 2296 } 2297 2298 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) { 2299 // we're about to wait, flush the binder command buffer 2300 IPCThreadState::self()->flushCommands(); 2301 2302 clearOutputTracks(); 2303 2304 if (exitPending()) { 2305 break; 2306 } 2307 2308 releaseWakeLock_l(); 2309 mWakeLockUids.clear(); 2310 mActiveTracksGeneration++; 2311 // wait until we have something to do... 2312 ALOGV("%s going to sleep", myName.string()); 2313 mWaitWorkCV.wait(mLock); 2314 ALOGV("%s waking up", myName.string()); 2315 acquireWakeLock_l(); 2316 2317 mMixerStatus = MIXER_IDLE; 2318 mMixerStatusIgnoringFastTracks = MIXER_IDLE; 2319 mBytesWritten = 0; 2320 mBytesRemaining = 0; 2321 checkSilentMode_l(); 2322 2323 standbyTime = systemTime() + standbyDelay; 2324 sleepTime = idleSleepTime; 2325 if (mType == MIXER) { 2326 sleepTimeShift = 0; 2327 } 2328 2329 continue; 2330 } 2331 } 2332 // mMixerStatusIgnoringFastTracks is also updated internally 2333 mMixerStatus = prepareTracks_l(&tracksToRemove); 2334 2335 // compare with previously applied list 2336 if (lastGeneration != mActiveTracksGeneration) { 2337 // update wakelock 2338 updateWakeLockUids_l(mWakeLockUids); 2339 lastGeneration = mActiveTracksGeneration; 2340 } 2341 2342 // prevent any changes in effect chain list and in each effect chain 2343 // during mixing and effect process as the audio buffers could be deleted 2344 // or modified if an effect is created or deleted 2345 lockEffectChains_l(effectChains); 2346 } // mLock scope ends 2347 2348 if (mBytesRemaining == 0) { 2349 mCurrentWriteLength = 0; 2350 if (mMixerStatus == MIXER_TRACKS_READY) { 2351 // threadLoop_mix() sets mCurrentWriteLength 2352 threadLoop_mix(); 2353 } else if ((mMixerStatus != MIXER_DRAIN_TRACK) 2354 && (mMixerStatus != MIXER_DRAIN_ALL)) { 2355 // threadLoop_sleepTime sets sleepTime to 0 if data 2356 // must be written to HAL 2357 threadLoop_sleepTime(); 2358 if (sleepTime == 0) { 2359 mCurrentWriteLength = mixBufferSize; 2360 } 2361 } 2362 mBytesRemaining = mCurrentWriteLength; 2363 if (isSuspended()) { 2364 sleepTime = suspendSleepTimeUs(); 2365 // simulate write to HAL when suspended 2366 mBytesWritten += mixBufferSize; 2367 mBytesRemaining = 0; 2368 } 2369 2370 // only process effects if we're going to write 2371 if (sleepTime == 0 && mType != OFFLOAD) { 2372 for (size_t i = 0; i < effectChains.size(); i ++) { 2373 effectChains[i]->process_l(); 2374 } 2375 } 2376 } 2377 // Process effect chains for offloaded thread even if no audio 2378 // was read from audio track: process only updates effect state 2379 // and thus does have to be synchronized with audio writes but may have 2380 // to be called while waiting for async write callback 2381 if (mType == OFFLOAD) { 2382 for (size_t i = 0; i < effectChains.size(); i ++) { 2383 effectChains[i]->process_l(); 2384 } 2385 } 2386 2387 // enable changes in effect chain 2388 unlockEffectChains(effectChains); 2389 2390 if (!waitingAsyncCallback()) { 2391 // sleepTime == 0 means we must write to audio hardware 2392 if (sleepTime == 0) { 2393 if (mBytesRemaining) { 2394 ssize_t ret = threadLoop_write(); 2395 if (ret < 0) { 2396 mBytesRemaining = 0; 2397 } else { 2398 mBytesWritten += ret; 2399 mBytesRemaining -= ret; 2400 } 2401 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) || 2402 (mMixerStatus == MIXER_DRAIN_ALL)) { 2403 threadLoop_drain(); 2404 } 2405 if (mType == MIXER) { 2406 // write blocked detection 2407 nsecs_t now = systemTime(); 2408 nsecs_t delta = now - mLastWriteTime; 2409 if (!mStandby && delta > maxPeriod) { 2410 mNumDelayedWrites++; 2411 if ((now - lastWarning) > kWarningThrottleNs) { 2412 ATRACE_NAME("underrun"); 2413 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p", 2414 ns2ms(delta), mNumDelayedWrites, this); 2415 lastWarning = now; 2416 } 2417 } 2418 } 2419 2420 } else { 2421 usleep(sleepTime); 2422 } 2423 } 2424 2425 // Finally let go of removed track(s), without the lock held 2426 // since we can't guarantee the destructors won't acquire that 2427 // same lock. This will also mutate and push a new fast mixer state. 2428 threadLoop_removeTracks(tracksToRemove); 2429 tracksToRemove.clear(); 2430 2431 // FIXME I don't understand the need for this here; 2432 // it was in the original code but maybe the 2433 // assignment in saveOutputTracks() makes this unnecessary? 2434 clearOutputTracks(); 2435 2436 // Effect chains will be actually deleted here if they were removed from 2437 // mEffectChains list during mixing or effects processing 2438 effectChains.clear(); 2439 2440 // FIXME Note that the above .clear() is no longer necessary since effectChains 2441 // is now local to this block, but will keep it for now (at least until merge done). 2442 } 2443 2444 threadLoop_exit(); 2445 2446 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ... 2447 if (mType == MIXER || mType == DIRECT || mType == OFFLOAD) { 2448 // put output stream into standby mode 2449 if (!mStandby) { 2450 mOutput->stream->common.standby(&mOutput->stream->common); 2451 } 2452 } 2453 2454 releaseWakeLock(); 2455 mWakeLockUids.clear(); 2456 mActiveTracksGeneration++; 2457 2458 ALOGV("Thread %p type %d exiting", this, mType); 2459 return false; 2460} 2461 2462// removeTracks_l() must be called with ThreadBase::mLock held 2463void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove) 2464{ 2465 size_t count = tracksToRemove.size(); 2466 if (count > 0) { 2467 for (size_t i=0 ; i<count ; i++) { 2468 const sp<Track>& track = tracksToRemove.itemAt(i); 2469 mActiveTracks.remove(track); 2470 mWakeLockUids.remove(track->uid()); 2471 mActiveTracksGeneration++; 2472 ALOGV("removeTracks_l removing track on session %d", track->sessionId()); 2473 sp<EffectChain> chain = getEffectChain_l(track->sessionId()); 2474 if (chain != 0) { 2475 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), 2476 track->sessionId()); 2477 chain->decActiveTrackCnt(); 2478 } 2479 if (track->isTerminated()) { 2480 removeTrack_l(track); 2481 } 2482 } 2483 } 2484 2485} 2486 2487status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp) 2488{ 2489 if (mNormalSink != 0) { 2490 return mNormalSink->getTimestamp(timestamp); 2491 } 2492 if (mType == OFFLOAD && mOutput->stream->get_presentation_position) { 2493 uint64_t position64; 2494 int ret = mOutput->stream->get_presentation_position( 2495 mOutput->stream, &position64, ×tamp.mTime); 2496 if (ret == 0) { 2497 timestamp.mPosition = (uint32_t)position64; 2498 return NO_ERROR; 2499 } 2500 } 2501 return INVALID_OPERATION; 2502} 2503// ---------------------------------------------------------------------------- 2504 2505AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, 2506 audio_io_handle_t id, audio_devices_t device, type_t type) 2507 : PlaybackThread(audioFlinger, output, id, device, type), 2508 // mAudioMixer below 2509 // mFastMixer below 2510 mFastMixerFutex(0) 2511 // mOutputSink below 2512 // mPipeSink below 2513 // mNormalSink below 2514{ 2515 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type); 2516 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, " 2517 "mFrameCount=%d, mNormalFrameCount=%d", 2518 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount, 2519 mNormalFrameCount); 2520 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate); 2521 2522 // FIXME - Current mixer implementation only supports stereo output 2523 if (mChannelCount != FCC_2) { 2524 ALOGE("Invalid audio hardware channel count %d", mChannelCount); 2525 } 2526 2527 // create an NBAIO sink for the HAL output stream, and negotiate 2528 mOutputSink = new AudioStreamOutSink(output->stream); 2529 size_t numCounterOffers = 0; 2530 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)}; 2531 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers); 2532 ALOG_ASSERT(index == 0); 2533 2534 // initialize fast mixer depending on configuration 2535 bool initFastMixer; 2536 switch (kUseFastMixer) { 2537 case FastMixer_Never: 2538 initFastMixer = false; 2539 break; 2540 case FastMixer_Always: 2541 initFastMixer = true; 2542 break; 2543 case FastMixer_Static: 2544 case FastMixer_Dynamic: 2545 initFastMixer = mFrameCount < mNormalFrameCount; 2546 break; 2547 } 2548 if (initFastMixer) { 2549 2550 // create a MonoPipe to connect our submix to FastMixer 2551 NBAIO_Format format = mOutputSink->format(); 2552 // This pipe depth compensates for scheduling latency of the normal mixer thread. 2553 // When it wakes up after a maximum latency, it runs a few cycles quickly before 2554 // finally blocking. Note the pipe implementation rounds up the request to a power of 2. 2555 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/); 2556 const NBAIO_Format offers[1] = {format}; 2557 size_t numCounterOffers = 0; 2558 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers); 2559 ALOG_ASSERT(index == 0); 2560 monoPipe->setAvgFrames((mScreenState & 1) ? 2561 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2); 2562 mPipeSink = monoPipe; 2563 2564#ifdef TEE_SINK 2565 if (mTeeSinkOutputEnabled) { 2566 // create a Pipe to archive a copy of FastMixer's output for dumpsys 2567 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, format); 2568 numCounterOffers = 0; 2569 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers); 2570 ALOG_ASSERT(index == 0); 2571 mTeeSink = teeSink; 2572 PipeReader *teeSource = new PipeReader(*teeSink); 2573 numCounterOffers = 0; 2574 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers); 2575 ALOG_ASSERT(index == 0); 2576 mTeeSource = teeSource; 2577 } 2578#endif 2579 2580 // create fast mixer and configure it initially with just one fast track for our submix 2581 mFastMixer = new FastMixer(); 2582 FastMixerStateQueue *sq = mFastMixer->sq(); 2583#ifdef STATE_QUEUE_DUMP 2584 sq->setObserverDump(&mStateQueueObserverDump); 2585 sq->setMutatorDump(&mStateQueueMutatorDump); 2586#endif 2587 FastMixerState *state = sq->begin(); 2588 FastTrack *fastTrack = &state->mFastTracks[0]; 2589 // wrap the source side of the MonoPipe to make it an AudioBufferProvider 2590 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe)); 2591 fastTrack->mVolumeProvider = NULL; 2592 fastTrack->mGeneration++; 2593 state->mFastTracksGen++; 2594 state->mTrackMask = 1; 2595 // fast mixer will use the HAL output sink 2596 state->mOutputSink = mOutputSink.get(); 2597 state->mOutputSinkGen++; 2598 state->mFrameCount = mFrameCount; 2599 state->mCommand = FastMixerState::COLD_IDLE; 2600 // already done in constructor initialization list 2601 //mFastMixerFutex = 0; 2602 state->mColdFutexAddr = &mFastMixerFutex; 2603 state->mColdGen++; 2604 state->mDumpState = &mFastMixerDumpState; 2605#ifdef TEE_SINK 2606 state->mTeeSink = mTeeSink.get(); 2607#endif 2608 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer"); 2609 state->mNBLogWriter = mFastMixerNBLogWriter.get(); 2610 sq->end(); 2611 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 2612 2613 // start the fast mixer 2614 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO); 2615 pid_t tid = mFastMixer->getTid(); 2616 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer); 2617 if (err != 0) { 2618 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d", 2619 kPriorityFastMixer, getpid_cached, tid, err); 2620 } 2621 2622#ifdef AUDIO_WATCHDOG 2623 // create and start the watchdog 2624 mAudioWatchdog = new AudioWatchdog(); 2625 mAudioWatchdog->setDump(&mAudioWatchdogDump); 2626 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO); 2627 tid = mAudioWatchdog->getTid(); 2628 err = requestPriority(getpid_cached, tid, kPriorityFastMixer); 2629 if (err != 0) { 2630 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d", 2631 kPriorityFastMixer, getpid_cached, tid, err); 2632 } 2633#endif 2634 2635 } else { 2636 mFastMixer = NULL; 2637 } 2638 2639 switch (kUseFastMixer) { 2640 case FastMixer_Never: 2641 case FastMixer_Dynamic: 2642 mNormalSink = mOutputSink; 2643 break; 2644 case FastMixer_Always: 2645 mNormalSink = mPipeSink; 2646 break; 2647 case FastMixer_Static: 2648 mNormalSink = initFastMixer ? mPipeSink : mOutputSink; 2649 break; 2650 } 2651} 2652 2653AudioFlinger::MixerThread::~MixerThread() 2654{ 2655 if (mFastMixer != NULL) { 2656 FastMixerStateQueue *sq = mFastMixer->sq(); 2657 FastMixerState *state = sq->begin(); 2658 if (state->mCommand == FastMixerState::COLD_IDLE) { 2659 int32_t old = android_atomic_inc(&mFastMixerFutex); 2660 if (old == -1) { 2661 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1); 2662 } 2663 } 2664 state->mCommand = FastMixerState::EXIT; 2665 sq->end(); 2666 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 2667 mFastMixer->join(); 2668 // Though the fast mixer thread has exited, it's state queue is still valid. 2669 // We'll use that extract the final state which contains one remaining fast track 2670 // corresponding to our sub-mix. 2671 state = sq->begin(); 2672 ALOG_ASSERT(state->mTrackMask == 1); 2673 FastTrack *fastTrack = &state->mFastTracks[0]; 2674 ALOG_ASSERT(fastTrack->mBufferProvider != NULL); 2675 delete fastTrack->mBufferProvider; 2676 sq->end(false /*didModify*/); 2677 delete mFastMixer; 2678#ifdef AUDIO_WATCHDOG 2679 if (mAudioWatchdog != 0) { 2680 mAudioWatchdog->requestExit(); 2681 mAudioWatchdog->requestExitAndWait(); 2682 mAudioWatchdog.clear(); 2683 } 2684#endif 2685 } 2686 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter); 2687 delete mAudioMixer; 2688} 2689 2690 2691uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const 2692{ 2693 if (mFastMixer != NULL) { 2694 MonoPipe *pipe = (MonoPipe *)mPipeSink.get(); 2695 latency += (pipe->getAvgFrames() * 1000) / mSampleRate; 2696 } 2697 return latency; 2698} 2699 2700 2701void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove) 2702{ 2703 PlaybackThread::threadLoop_removeTracks(tracksToRemove); 2704} 2705 2706ssize_t AudioFlinger::MixerThread::threadLoop_write() 2707{ 2708 // FIXME we should only do one push per cycle; confirm this is true 2709 // Start the fast mixer if it's not already running 2710 if (mFastMixer != NULL) { 2711 FastMixerStateQueue *sq = mFastMixer->sq(); 2712 FastMixerState *state = sq->begin(); 2713 if (state->mCommand != FastMixerState::MIX_WRITE && 2714 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) { 2715 if (state->mCommand == FastMixerState::COLD_IDLE) { 2716 int32_t old = android_atomic_inc(&mFastMixerFutex); 2717 if (old == -1) { 2718 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1); 2719 } 2720#ifdef AUDIO_WATCHDOG 2721 if (mAudioWatchdog != 0) { 2722 mAudioWatchdog->resume(); 2723 } 2724#endif 2725 } 2726 state->mCommand = FastMixerState::MIX_WRITE; 2727 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ? 2728 FastMixerDumpState::kSamplingNforLowRamDevice : FastMixerDumpState::kSamplingN); 2729 sq->end(); 2730 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 2731 if (kUseFastMixer == FastMixer_Dynamic) { 2732 mNormalSink = mPipeSink; 2733 } 2734 } else { 2735 sq->end(false /*didModify*/); 2736 } 2737 } 2738 return PlaybackThread::threadLoop_write(); 2739} 2740 2741void AudioFlinger::MixerThread::threadLoop_standby() 2742{ 2743 // Idle the fast mixer if it's currently running 2744 if (mFastMixer != NULL) { 2745 FastMixerStateQueue *sq = mFastMixer->sq(); 2746 FastMixerState *state = sq->begin(); 2747 if (!(state->mCommand & FastMixerState::IDLE)) { 2748 state->mCommand = FastMixerState::COLD_IDLE; 2749 state->mColdFutexAddr = &mFastMixerFutex; 2750 state->mColdGen++; 2751 mFastMixerFutex = 0; 2752 sq->end(); 2753 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now 2754 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED); 2755 if (kUseFastMixer == FastMixer_Dynamic) { 2756 mNormalSink = mOutputSink; 2757 } 2758#ifdef AUDIO_WATCHDOG 2759 if (mAudioWatchdog != 0) { 2760 mAudioWatchdog->pause(); 2761 } 2762#endif 2763 } else { 2764 sq->end(false /*didModify*/); 2765 } 2766 } 2767 PlaybackThread::threadLoop_standby(); 2768} 2769 2770bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l() 2771{ 2772 return false; 2773} 2774 2775bool AudioFlinger::PlaybackThread::shouldStandby_l() 2776{ 2777 return !mStandby; 2778} 2779 2780bool AudioFlinger::PlaybackThread::waitingAsyncCallback() 2781{ 2782 Mutex::Autolock _l(mLock); 2783 return waitingAsyncCallback_l(); 2784} 2785 2786// shared by MIXER and DIRECT, overridden by DUPLICATING 2787void AudioFlinger::PlaybackThread::threadLoop_standby() 2788{ 2789 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended); 2790 mOutput->stream->common.standby(&mOutput->stream->common); 2791 if (mUseAsyncWrite != 0) { 2792 // discard any pending drain or write ack by incrementing sequence 2793 mWriteAckSequence = (mWriteAckSequence + 2) & ~1; 2794 mDrainSequence = (mDrainSequence + 2) & ~1; 2795 ALOG_ASSERT(mCallbackThread != 0); 2796 mCallbackThread->setWriteBlocked(mWriteAckSequence); 2797 mCallbackThread->setDraining(mDrainSequence); 2798 } 2799} 2800 2801void AudioFlinger::PlaybackThread::onAddNewTrack_l() 2802{ 2803 ALOGV("signal playback thread"); 2804 broadcast_l(); 2805} 2806 2807void AudioFlinger::MixerThread::threadLoop_mix() 2808{ 2809 // obtain the presentation timestamp of the next output buffer 2810 int64_t pts; 2811 status_t status = INVALID_OPERATION; 2812 2813 if (mNormalSink != 0) { 2814 status = mNormalSink->getNextWriteTimestamp(&pts); 2815 } else { 2816 status = mOutputSink->getNextWriteTimestamp(&pts); 2817 } 2818 2819 if (status != NO_ERROR) { 2820 pts = AudioBufferProvider::kInvalidPTS; 2821 } 2822 2823 // mix buffers... 2824 mAudioMixer->process(pts); 2825 mCurrentWriteLength = mixBufferSize; 2826 // increase sleep time progressively when application underrun condition clears. 2827 // Only increase sleep time if the mixer is ready for two consecutive times to avoid 2828 // that a steady state of alternating ready/not ready conditions keeps the sleep time 2829 // such that we would underrun the audio HAL. 2830 if ((sleepTime == 0) && (sleepTimeShift > 0)) { 2831 sleepTimeShift--; 2832 } 2833 sleepTime = 0; 2834 standbyTime = systemTime() + standbyDelay; 2835 //TODO: delay standby when effects have a tail 2836} 2837 2838void AudioFlinger::MixerThread::threadLoop_sleepTime() 2839{ 2840 // If no tracks are ready, sleep once for the duration of an output 2841 // buffer size, then write 0s to the output 2842 if (sleepTime == 0) { 2843 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 2844 sleepTime = activeSleepTime >> sleepTimeShift; 2845 if (sleepTime < kMinThreadSleepTimeUs) { 2846 sleepTime = kMinThreadSleepTimeUs; 2847 } 2848 // reduce sleep time in case of consecutive application underruns to avoid 2849 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer 2850 // duration we would end up writing less data than needed by the audio HAL if 2851 // the condition persists. 2852 if (sleepTimeShift < kMaxThreadSleepTimeShift) { 2853 sleepTimeShift++; 2854 } 2855 } else { 2856 sleepTime = idleSleepTime; 2857 } 2858 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) { 2859 memset(mMixBuffer, 0, mixBufferSize); 2860 sleepTime = 0; 2861 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED), 2862 "anticipated start"); 2863 } 2864 // TODO add standby time extension fct of effect tail 2865} 2866 2867// prepareTracks_l() must be called with ThreadBase::mLock held 2868AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l( 2869 Vector< sp<Track> > *tracksToRemove) 2870{ 2871 2872 mixer_state mixerStatus = MIXER_IDLE; 2873 // find out which tracks need to be processed 2874 size_t count = mActiveTracks.size(); 2875 size_t mixedTracks = 0; 2876 size_t tracksWithEffect = 0; 2877 // counts only _active_ fast tracks 2878 size_t fastTracks = 0; 2879 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset 2880 2881 float masterVolume = mMasterVolume; 2882 bool masterMute = mMasterMute; 2883 2884 if (masterMute) { 2885 masterVolume = 0; 2886 } 2887 // Delegate master volume control to effect in output mix effect chain if needed 2888 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); 2889 if (chain != 0) { 2890 uint32_t v = (uint32_t)(masterVolume * (1 << 24)); 2891 chain->setVolume_l(&v, &v); 2892 masterVolume = (float)((v + (1 << 23)) >> 24); 2893 chain.clear(); 2894 } 2895 2896 // prepare a new state to push 2897 FastMixerStateQueue *sq = NULL; 2898 FastMixerState *state = NULL; 2899 bool didModify = false; 2900 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED; 2901 if (mFastMixer != NULL) { 2902 sq = mFastMixer->sq(); 2903 state = sq->begin(); 2904 } 2905 2906 for (size_t i=0 ; i<count ; i++) { 2907 const sp<Track> t = mActiveTracks[i].promote(); 2908 if (t == 0) { 2909 continue; 2910 } 2911 2912 // this const just means the local variable doesn't change 2913 Track* const track = t.get(); 2914 2915 // process fast tracks 2916 if (track->isFastTrack()) { 2917 2918 // It's theoretically possible (though unlikely) for a fast track to be created 2919 // and then removed within the same normal mix cycle. This is not a problem, as 2920 // the track never becomes active so it's fast mixer slot is never touched. 2921 // The converse, of removing an (active) track and then creating a new track 2922 // at the identical fast mixer slot within the same normal mix cycle, 2923 // is impossible because the slot isn't marked available until the end of each cycle. 2924 int j = track->mFastIndex; 2925 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks); 2926 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j))); 2927 FastTrack *fastTrack = &state->mFastTracks[j]; 2928 2929 // Determine whether the track is currently in underrun condition, 2930 // and whether it had a recent underrun. 2931 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j]; 2932 FastTrackUnderruns underruns = ftDump->mUnderruns; 2933 uint32_t recentFull = (underruns.mBitFields.mFull - 2934 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK; 2935 uint32_t recentPartial = (underruns.mBitFields.mPartial - 2936 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK; 2937 uint32_t recentEmpty = (underruns.mBitFields.mEmpty - 2938 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK; 2939 uint32_t recentUnderruns = recentPartial + recentEmpty; 2940 track->mObservedUnderruns = underruns; 2941 // don't count underruns that occur while stopping or pausing 2942 // or stopped which can occur when flush() is called while active 2943 if (!(track->isStopping() || track->isPausing() || track->isStopped()) && 2944 recentUnderruns > 0) { 2945 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun 2946 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount); 2947 } 2948 2949 // This is similar to the state machine for normal tracks, 2950 // with a few modifications for fast tracks. 2951 bool isActive = true; 2952 switch (track->mState) { 2953 case TrackBase::STOPPING_1: 2954 // track stays active in STOPPING_1 state until first underrun 2955 if (recentUnderruns > 0 || track->isTerminated()) { 2956 track->mState = TrackBase::STOPPING_2; 2957 } 2958 break; 2959 case TrackBase::PAUSING: 2960 // ramp down is not yet implemented 2961 track->setPaused(); 2962 break; 2963 case TrackBase::RESUMING: 2964 // ramp up is not yet implemented 2965 track->mState = TrackBase::ACTIVE; 2966 break; 2967 case TrackBase::ACTIVE: 2968 if (recentFull > 0 || recentPartial > 0) { 2969 // track has provided at least some frames recently: reset retry count 2970 track->mRetryCount = kMaxTrackRetries; 2971 } 2972 if (recentUnderruns == 0) { 2973 // no recent underruns: stay active 2974 break; 2975 } 2976 // there has recently been an underrun of some kind 2977 if (track->sharedBuffer() == 0) { 2978 // were any of the recent underruns "empty" (no frames available)? 2979 if (recentEmpty == 0) { 2980 // no, then ignore the partial underruns as they are allowed indefinitely 2981 break; 2982 } 2983 // there has recently been an "empty" underrun: decrement the retry counter 2984 if (--(track->mRetryCount) > 0) { 2985 break; 2986 } 2987 // indicate to client process that the track was disabled because of underrun; 2988 // it will then automatically call start() when data is available 2989 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags); 2990 // remove from active list, but state remains ACTIVE [confusing but true] 2991 isActive = false; 2992 break; 2993 } 2994 // fall through 2995 case TrackBase::STOPPING_2: 2996 case TrackBase::PAUSED: 2997 case TrackBase::STOPPED: 2998 case TrackBase::FLUSHED: // flush() while active 2999 // Check for presentation complete if track is inactive 3000 // We have consumed all the buffers of this track. 3001 // This would be incomplete if we auto-paused on underrun 3002 { 3003 size_t audioHALFrames = 3004 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000; 3005 size_t framesWritten = mBytesWritten / mFrameSize; 3006 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) { 3007 // track stays in active list until presentation is complete 3008 break; 3009 } 3010 } 3011 if (track->isStopping_2()) { 3012 track->mState = TrackBase::STOPPED; 3013 } 3014 if (track->isStopped()) { 3015 // Can't reset directly, as fast mixer is still polling this track 3016 // track->reset(); 3017 // So instead mark this track as needing to be reset after push with ack 3018 resetMask |= 1 << i; 3019 } 3020 isActive = false; 3021 break; 3022 case TrackBase::IDLE: 3023 default: 3024 LOG_FATAL("unexpected track state %d", track->mState); 3025 } 3026 3027 if (isActive) { 3028 // was it previously inactive? 3029 if (!(state->mTrackMask & (1 << j))) { 3030 ExtendedAudioBufferProvider *eabp = track; 3031 VolumeProvider *vp = track; 3032 fastTrack->mBufferProvider = eabp; 3033 fastTrack->mVolumeProvider = vp; 3034 fastTrack->mSampleRate = track->mSampleRate; 3035 fastTrack->mChannelMask = track->mChannelMask; 3036 fastTrack->mGeneration++; 3037 state->mTrackMask |= 1 << j; 3038 didModify = true; 3039 // no acknowledgement required for newly active tracks 3040 } 3041 // cache the combined master volume and stream type volume for fast mixer; this 3042 // lacks any synchronization or barrier so VolumeProvider may read a stale value 3043 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume; 3044 ++fastTracks; 3045 } else { 3046 // was it previously active? 3047 if (state->mTrackMask & (1 << j)) { 3048 fastTrack->mBufferProvider = NULL; 3049 fastTrack->mGeneration++; 3050 state->mTrackMask &= ~(1 << j); 3051 didModify = true; 3052 // If any fast tracks were removed, we must wait for acknowledgement 3053 // because we're about to decrement the last sp<> on those tracks. 3054 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED; 3055 } else { 3056 LOG_FATAL("fast track %d should have been active", j); 3057 } 3058 tracksToRemove->add(track); 3059 // Avoids a misleading display in dumpsys 3060 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL; 3061 } 3062 continue; 3063 } 3064 3065 { // local variable scope to avoid goto warning 3066 3067 audio_track_cblk_t* cblk = track->cblk(); 3068 3069 // The first time a track is added we wait 3070 // for all its buffers to be filled before processing it 3071 int name = track->name(); 3072 // make sure that we have enough frames to mix one full buffer. 3073 // enforce this condition only once to enable draining the buffer in case the client 3074 // app does not call stop() and relies on underrun to stop: 3075 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed 3076 // during last round 3077 size_t desiredFrames; 3078 uint32_t sr = track->sampleRate(); 3079 if (sr == mSampleRate) { 3080 desiredFrames = mNormalFrameCount; 3081 } else { 3082 // +1 for rounding and +1 for additional sample needed for interpolation 3083 desiredFrames = (mNormalFrameCount * sr) / mSampleRate + 1 + 1; 3084 // add frames already consumed but not yet released by the resampler 3085 // because mAudioTrackServerProxy->framesReady() will include these frames 3086 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name()); 3087#if 0 3088 // the minimum track buffer size is normally twice the number of frames necessary 3089 // to fill one buffer and the resampler should not leave more than one buffer worth 3090 // of unreleased frames after each pass, but just in case... 3091 ALOG_ASSERT(desiredFrames <= cblk->frameCount_); 3092#endif 3093 } 3094 uint32_t minFrames = 1; 3095 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() && 3096 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) { 3097 minFrames = desiredFrames; 3098 } 3099 3100 size_t framesReady = track->framesReady(); 3101 if ((framesReady >= minFrames) && track->isReady() && 3102 !track->isPaused() && !track->isTerminated()) 3103 { 3104 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this); 3105 3106 mixedTracks++; 3107 3108 // track->mainBuffer() != mMixBuffer means there is an effect chain 3109 // connected to the track 3110 chain.clear(); 3111 if (track->mainBuffer() != mMixBuffer) { 3112 chain = getEffectChain_l(track->sessionId()); 3113 // Delegate volume control to effect in track effect chain if needed 3114 if (chain != 0) { 3115 tracksWithEffect++; 3116 } else { 3117 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on " 3118 "session %d", 3119 name, track->sessionId()); 3120 } 3121 } 3122 3123 3124 int param = AudioMixer::VOLUME; 3125 if (track->mFillingUpStatus == Track::FS_FILLED) { 3126 // no ramp for the first volume setting 3127 track->mFillingUpStatus = Track::FS_ACTIVE; 3128 if (track->mState == TrackBase::RESUMING) { 3129 track->mState = TrackBase::ACTIVE; 3130 param = AudioMixer::RAMP_VOLUME; 3131 } 3132 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL); 3133 // FIXME should not make a decision based on mServer 3134 } else if (cblk->mServer != 0) { 3135 // If the track is stopped before the first frame was mixed, 3136 // do not apply ramp 3137 param = AudioMixer::RAMP_VOLUME; 3138 } 3139 3140 // compute volume for this track 3141 uint32_t vl, vr, va; 3142 if (track->isPausing() || mStreamTypes[track->streamType()].mute) { 3143 vl = vr = va = 0; 3144 if (track->isPausing()) { 3145 track->setPaused(); 3146 } 3147 } else { 3148 3149 // read original volumes with volume control 3150 float typeVolume = mStreamTypes[track->streamType()].volume; 3151 float v = masterVolume * typeVolume; 3152 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy; 3153 uint32_t vlr = proxy->getVolumeLR(); 3154 vl = vlr & 0xFFFF; 3155 vr = vlr >> 16; 3156 // track volumes come from shared memory, so can't be trusted and must be clamped 3157 if (vl > MAX_GAIN_INT) { 3158 ALOGV("Track left volume out of range: %04X", vl); 3159 vl = MAX_GAIN_INT; 3160 } 3161 if (vr > MAX_GAIN_INT) { 3162 ALOGV("Track right volume out of range: %04X", vr); 3163 vr = MAX_GAIN_INT; 3164 } 3165 // now apply the master volume and stream type volume 3166 vl = (uint32_t)(v * vl) << 12; 3167 vr = (uint32_t)(v * vr) << 12; 3168 // assuming master volume and stream type volume each go up to 1.0, 3169 // vl and vr are now in 8.24 format 3170 3171 uint16_t sendLevel = proxy->getSendLevel_U4_12(); 3172 // send level comes from shared memory and so may be corrupt 3173 if (sendLevel > MAX_GAIN_INT) { 3174 ALOGV("Track send level out of range: %04X", sendLevel); 3175 sendLevel = MAX_GAIN_INT; 3176 } 3177 va = (uint32_t)(v * sendLevel); 3178 } 3179 3180 // Delegate volume control to effect in track effect chain if needed 3181 if (chain != 0 && chain->setVolume_l(&vl, &vr)) { 3182 // Do not ramp volume if volume is controlled by effect 3183 param = AudioMixer::VOLUME; 3184 track->mHasVolumeController = true; 3185 } else { 3186 // force no volume ramp when volume controller was just disabled or removed 3187 // from effect chain to avoid volume spike 3188 if (track->mHasVolumeController) { 3189 param = AudioMixer::VOLUME; 3190 } 3191 track->mHasVolumeController = false; 3192 } 3193 3194 // Convert volumes from 8.24 to 4.12 format 3195 // This additional clamping is needed in case chain->setVolume_l() overshot 3196 vl = (vl + (1 << 11)) >> 12; 3197 if (vl > MAX_GAIN_INT) { 3198 vl = MAX_GAIN_INT; 3199 } 3200 vr = (vr + (1 << 11)) >> 12; 3201 if (vr > MAX_GAIN_INT) { 3202 vr = MAX_GAIN_INT; 3203 } 3204 3205 if (va > MAX_GAIN_INT) { 3206 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for - 3207 } 3208 3209 // XXX: these things DON'T need to be done each time 3210 mAudioMixer->setBufferProvider(name, track); 3211 mAudioMixer->enable(name); 3212 3213 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl); 3214 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr); 3215 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va); 3216 mAudioMixer->setParameter( 3217 name, 3218 AudioMixer::TRACK, 3219 AudioMixer::FORMAT, (void *)track->format()); 3220 mAudioMixer->setParameter( 3221 name, 3222 AudioMixer::TRACK, 3223 AudioMixer::CHANNEL_MASK, (void *)track->channelMask()); 3224 // limit track sample rate to 2 x output sample rate, which changes at re-configuration 3225 uint32_t maxSampleRate = mSampleRate * 2; 3226 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate(); 3227 if (reqSampleRate == 0) { 3228 reqSampleRate = mSampleRate; 3229 } else if (reqSampleRate > maxSampleRate) { 3230 reqSampleRate = maxSampleRate; 3231 } 3232 mAudioMixer->setParameter( 3233 name, 3234 AudioMixer::RESAMPLE, 3235 AudioMixer::SAMPLE_RATE, 3236 (void *)reqSampleRate); 3237 mAudioMixer->setParameter( 3238 name, 3239 AudioMixer::TRACK, 3240 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer()); 3241 mAudioMixer->setParameter( 3242 name, 3243 AudioMixer::TRACK, 3244 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer()); 3245 3246 // reset retry count 3247 track->mRetryCount = kMaxTrackRetries; 3248 3249 // If one track is ready, set the mixer ready if: 3250 // - the mixer was not ready during previous round OR 3251 // - no other track is not ready 3252 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY || 3253 mixerStatus != MIXER_TRACKS_ENABLED) { 3254 mixerStatus = MIXER_TRACKS_READY; 3255 } 3256 } else { 3257 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) { 3258 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames); 3259 } 3260 // clear effect chain input buffer if an active track underruns to avoid sending 3261 // previous audio buffer again to effects 3262 chain = getEffectChain_l(track->sessionId()); 3263 if (chain != 0) { 3264 chain->clearInputBuffer(); 3265 } 3266 3267 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this); 3268 if ((track->sharedBuffer() != 0) || track->isTerminated() || 3269 track->isStopped() || track->isPaused()) { 3270 // We have consumed all the buffers of this track. 3271 // Remove it from the list of active tracks. 3272 // TODO: use actual buffer filling status instead of latency when available from 3273 // audio HAL 3274 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000; 3275 size_t framesWritten = mBytesWritten / mFrameSize; 3276 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) { 3277 if (track->isStopped()) { 3278 track->reset(); 3279 } 3280 tracksToRemove->add(track); 3281 } 3282 } else { 3283 // No buffers for this track. Give it a few chances to 3284 // fill a buffer, then remove it from active list. 3285 if (--(track->mRetryCount) <= 0) { 3286 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this); 3287 tracksToRemove->add(track); 3288 // indicate to client process that the track was disabled because of underrun; 3289 // it will then automatically call start() when data is available 3290 android_atomic_or(CBLK_DISABLED, &cblk->mFlags); 3291 // If one track is not ready, mark the mixer also not ready if: 3292 // - the mixer was ready during previous round OR 3293 // - no other track is ready 3294 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY || 3295 mixerStatus != MIXER_TRACKS_READY) { 3296 mixerStatus = MIXER_TRACKS_ENABLED; 3297 } 3298 } 3299 mAudioMixer->disable(name); 3300 } 3301 3302 } // local variable scope to avoid goto warning 3303track_is_ready: ; 3304 3305 } 3306 3307 // Push the new FastMixer state if necessary 3308 bool pauseAudioWatchdog = false; 3309 if (didModify) { 3310 state->mFastTracksGen++; 3311 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle 3312 if (kUseFastMixer == FastMixer_Dynamic && 3313 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) { 3314 state->mCommand = FastMixerState::COLD_IDLE; 3315 state->mColdFutexAddr = &mFastMixerFutex; 3316 state->mColdGen++; 3317 mFastMixerFutex = 0; 3318 if (kUseFastMixer == FastMixer_Dynamic) { 3319 mNormalSink = mOutputSink; 3320 } 3321 // If we go into cold idle, need to wait for acknowledgement 3322 // so that fast mixer stops doing I/O. 3323 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED; 3324 pauseAudioWatchdog = true; 3325 } 3326 } 3327 if (sq != NULL) { 3328 sq->end(didModify); 3329 sq->push(block); 3330 } 3331#ifdef AUDIO_WATCHDOG 3332 if (pauseAudioWatchdog && mAudioWatchdog != 0) { 3333 mAudioWatchdog->pause(); 3334 } 3335#endif 3336 3337 // Now perform the deferred reset on fast tracks that have stopped 3338 while (resetMask != 0) { 3339 size_t i = __builtin_ctz(resetMask); 3340 ALOG_ASSERT(i < count); 3341 resetMask &= ~(1 << i); 3342 sp<Track> t = mActiveTracks[i].promote(); 3343 if (t == 0) { 3344 continue; 3345 } 3346 Track* track = t.get(); 3347 ALOG_ASSERT(track->isFastTrack() && track->isStopped()); 3348 track->reset(); 3349 } 3350 3351 // remove all the tracks that need to be... 3352 removeTracks_l(*tracksToRemove); 3353 3354 // mix buffer must be cleared if all tracks are connected to an 3355 // effect chain as in this case the mixer will not write to 3356 // mix buffer and track effects will accumulate into it 3357 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || 3358 (mixedTracks == 0 && fastTracks > 0))) { 3359 // FIXME as a performance optimization, should remember previous zero status 3360 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t)); 3361 } 3362 3363 // if any fast tracks, then status is ready 3364 mMixerStatusIgnoringFastTracks = mixerStatus; 3365 if (fastTracks > 0) { 3366 mixerStatus = MIXER_TRACKS_READY; 3367 } 3368 return mixerStatus; 3369} 3370 3371// getTrackName_l() must be called with ThreadBase::mLock held 3372int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId) 3373{ 3374 return mAudioMixer->getTrackName(channelMask, sessionId); 3375} 3376 3377// deleteTrackName_l() must be called with ThreadBase::mLock held 3378void AudioFlinger::MixerThread::deleteTrackName_l(int name) 3379{ 3380 ALOGV("remove track (%d) and delete from mixer", name); 3381 mAudioMixer->deleteTrackName(name); 3382} 3383 3384// checkForNewParameters_l() must be called with ThreadBase::mLock held 3385bool AudioFlinger::MixerThread::checkForNewParameters_l() 3386{ 3387 // if !&IDLE, holds the FastMixer state to restore after new parameters processed 3388 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE; 3389 bool reconfig = false; 3390 3391 while (!mNewParameters.isEmpty()) { 3392 3393 if (mFastMixer != NULL) { 3394 FastMixerStateQueue *sq = mFastMixer->sq(); 3395 FastMixerState *state = sq->begin(); 3396 if (!(state->mCommand & FastMixerState::IDLE)) { 3397 previousCommand = state->mCommand; 3398 state->mCommand = FastMixerState::HOT_IDLE; 3399 sq->end(); 3400 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED); 3401 } else { 3402 sq->end(false /*didModify*/); 3403 } 3404 } 3405 3406 status_t status = NO_ERROR; 3407 String8 keyValuePair = mNewParameters[0]; 3408 AudioParameter param = AudioParameter(keyValuePair); 3409 int value; 3410 3411 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { 3412 reconfig = true; 3413 } 3414 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { 3415 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) { 3416 status = BAD_VALUE; 3417 } else { 3418 // no need to save value, since it's constant 3419 reconfig = true; 3420 } 3421 } 3422 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { 3423 if ((audio_channel_mask_t) value != AUDIO_CHANNEL_OUT_STEREO) { 3424 status = BAD_VALUE; 3425 } else { 3426 // no need to save value, since it's constant 3427 reconfig = true; 3428 } 3429 } 3430 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 3431 // do not accept frame count changes if tracks are open as the track buffer 3432 // size depends on frame count and correct behavior would not be guaranteed 3433 // if frame count is changed after track creation 3434 if (!mTracks.isEmpty()) { 3435 status = INVALID_OPERATION; 3436 } else { 3437 reconfig = true; 3438 } 3439 } 3440 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 3441#ifdef ADD_BATTERY_DATA 3442 // when changing the audio output device, call addBatteryData to notify 3443 // the change 3444 if (mOutDevice != value) { 3445 uint32_t params = 0; 3446 // check whether speaker is on 3447 if (value & AUDIO_DEVICE_OUT_SPEAKER) { 3448 params |= IMediaPlayerService::kBatteryDataSpeakerOn; 3449 } 3450 3451 audio_devices_t deviceWithoutSpeaker 3452 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER; 3453 // check if any other device (except speaker) is on 3454 if (value & deviceWithoutSpeaker ) { 3455 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn; 3456 } 3457 3458 if (params != 0) { 3459 addBatteryData(params); 3460 } 3461 } 3462#endif 3463 3464 // forward device change to effects that have requested to be 3465 // aware of attached audio device. 3466 if (value != AUDIO_DEVICE_NONE) { 3467 mOutDevice = value; 3468 for (size_t i = 0; i < mEffectChains.size(); i++) { 3469 mEffectChains[i]->setDevice_l(mOutDevice); 3470 } 3471 } 3472 } 3473 3474 if (status == NO_ERROR) { 3475 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3476 keyValuePair.string()); 3477 if (!mStandby && status == INVALID_OPERATION) { 3478 mOutput->stream->common.standby(&mOutput->stream->common); 3479 mStandby = true; 3480 mBytesWritten = 0; 3481 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3482 keyValuePair.string()); 3483 } 3484 if (status == NO_ERROR && reconfig) { 3485 readOutputParameters(); 3486 delete mAudioMixer; 3487 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate); 3488 for (size_t i = 0; i < mTracks.size() ; i++) { 3489 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId); 3490 if (name < 0) { 3491 break; 3492 } 3493 mTracks[i]->mName = name; 3494 } 3495 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED); 3496 } 3497 } 3498 3499 mNewParameters.removeAt(0); 3500 3501 mParamStatus = status; 3502 mParamCond.signal(); 3503 // wait for condition with time out in case the thread calling ThreadBase::setParameters() 3504 // already timed out waiting for the status and will never signal the condition. 3505 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); 3506 } 3507 3508 if (!(previousCommand & FastMixerState::IDLE)) { 3509 ALOG_ASSERT(mFastMixer != NULL); 3510 FastMixerStateQueue *sq = mFastMixer->sq(); 3511 FastMixerState *state = sq->begin(); 3512 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE); 3513 state->mCommand = previousCommand; 3514 sq->end(); 3515 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 3516 } 3517 3518 return reconfig; 3519} 3520 3521 3522void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args) 3523{ 3524 const size_t SIZE = 256; 3525 char buffer[SIZE]; 3526 String8 result; 3527 3528 PlaybackThread::dumpInternals(fd, args); 3529 3530 fdprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames()); 3531 3532 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us 3533 const FastMixerDumpState copy(mFastMixerDumpState); 3534 copy.dump(fd); 3535 3536#ifdef STATE_QUEUE_DUMP 3537 // Similar for state queue 3538 StateQueueObserverDump observerCopy = mStateQueueObserverDump; 3539 observerCopy.dump(fd); 3540 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump; 3541 mutatorCopy.dump(fd); 3542#endif 3543 3544#ifdef TEE_SINK 3545 // Write the tee output to a .wav file 3546 dumpTee(fd, mTeeSource, mId); 3547#endif 3548 3549#ifdef AUDIO_WATCHDOG 3550 if (mAudioWatchdog != 0) { 3551 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us 3552 AudioWatchdogDump wdCopy = mAudioWatchdogDump; 3553 wdCopy.dump(fd); 3554 } 3555#endif 3556} 3557 3558uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const 3559{ 3560 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2; 3561} 3562 3563uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const 3564{ 3565 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000); 3566} 3567 3568void AudioFlinger::MixerThread::cacheParameters_l() 3569{ 3570 PlaybackThread::cacheParameters_l(); 3571 3572 // FIXME: Relaxed timing because of a certain device that can't meet latency 3573 // Should be reduced to 2x after the vendor fixes the driver issue 3574 // increase threshold again due to low power audio mode. The way this warning 3575 // threshold is calculated and its usefulness should be reconsidered anyway. 3576 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15; 3577} 3578 3579// ---------------------------------------------------------------------------- 3580 3581AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, 3582 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device) 3583 : PlaybackThread(audioFlinger, output, id, device, DIRECT) 3584 // mLeftVolFloat, mRightVolFloat 3585{ 3586} 3587 3588AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, 3589 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, 3590 ThreadBase::type_t type) 3591 : PlaybackThread(audioFlinger, output, id, device, type) 3592 // mLeftVolFloat, mRightVolFloat 3593{ 3594} 3595 3596AudioFlinger::DirectOutputThread::~DirectOutputThread() 3597{ 3598} 3599 3600void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack) 3601{ 3602 audio_track_cblk_t* cblk = track->cblk(); 3603 float left, right; 3604 3605 if (mMasterMute || mStreamTypes[track->streamType()].mute) { 3606 left = right = 0; 3607 } else { 3608 float typeVolume = mStreamTypes[track->streamType()].volume; 3609 float v = mMasterVolume * typeVolume; 3610 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy; 3611 uint32_t vlr = proxy->getVolumeLR(); 3612 float v_clamped = v * (vlr & 0xFFFF); 3613 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN; 3614 left = v_clamped/MAX_GAIN; 3615 v_clamped = v * (vlr >> 16); 3616 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN; 3617 right = v_clamped/MAX_GAIN; 3618 } 3619 3620 if (lastTrack) { 3621 if (left != mLeftVolFloat || right != mRightVolFloat) { 3622 mLeftVolFloat = left; 3623 mRightVolFloat = right; 3624 3625 // Convert volumes from float to 8.24 3626 uint32_t vl = (uint32_t)(left * (1 << 24)); 3627 uint32_t vr = (uint32_t)(right * (1 << 24)); 3628 3629 // Delegate volume control to effect in track effect chain if needed 3630 // only one effect chain can be present on DirectOutputThread, so if 3631 // there is one, the track is connected to it 3632 if (!mEffectChains.isEmpty()) { 3633 mEffectChains[0]->setVolume_l(&vl, &vr); 3634 left = (float)vl / (1 << 24); 3635 right = (float)vr / (1 << 24); 3636 } 3637 if (mOutput->stream->set_volume) { 3638 mOutput->stream->set_volume(mOutput->stream, left, right); 3639 } 3640 } 3641 } 3642} 3643 3644 3645AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l( 3646 Vector< sp<Track> > *tracksToRemove 3647) 3648{ 3649 size_t count = mActiveTracks.size(); 3650 mixer_state mixerStatus = MIXER_IDLE; 3651 3652 // find out which tracks need to be processed 3653 for (size_t i = 0; i < count; i++) { 3654 sp<Track> t = mActiveTracks[i].promote(); 3655 // The track died recently 3656 if (t == 0) { 3657 continue; 3658 } 3659 3660 Track* const track = t.get(); 3661 audio_track_cblk_t* cblk = track->cblk(); 3662 // Only consider last track started for volume and mixer state control. 3663 // In theory an older track could underrun and restart after the new one starts 3664 // but as we only care about the transition phase between two tracks on a 3665 // direct output, it is not a problem to ignore the underrun case. 3666 sp<Track> l = mLatestActiveTrack.promote(); 3667 bool last = l.get() == track; 3668 3669 // The first time a track is added we wait 3670 // for all its buffers to be filled before processing it 3671 uint32_t minFrames; 3672 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) { 3673 minFrames = mNormalFrameCount; 3674 } else { 3675 minFrames = 1; 3676 } 3677 3678 if ((track->framesReady() >= minFrames) && track->isReady() && 3679 !track->isPaused() && !track->isTerminated()) 3680 { 3681 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer); 3682 3683 if (track->mFillingUpStatus == Track::FS_FILLED) { 3684 track->mFillingUpStatus = Track::FS_ACTIVE; 3685 // make sure processVolume_l() will apply new volume even if 0 3686 mLeftVolFloat = mRightVolFloat = -1.0; 3687 if (track->mState == TrackBase::RESUMING) { 3688 track->mState = TrackBase::ACTIVE; 3689 } 3690 } 3691 3692 // compute volume for this track 3693 processVolume_l(track, last); 3694 if (last) { 3695 // reset retry count 3696 track->mRetryCount = kMaxTrackRetriesDirect; 3697 mActiveTrack = t; 3698 mixerStatus = MIXER_TRACKS_READY; 3699 } 3700 } else { 3701 // clear effect chain input buffer if the last active track started underruns 3702 // to avoid sending previous audio buffer again to effects 3703 if (!mEffectChains.isEmpty() && last) { 3704 mEffectChains[0]->clearInputBuffer(); 3705 } 3706 3707 ALOGVV("track %d s=%08x [NOT READY]", track->name(), cblk->mServer); 3708 if ((track->sharedBuffer() != 0) || track->isTerminated() || 3709 track->isStopped() || track->isPaused()) { 3710 // We have consumed all the buffers of this track. 3711 // Remove it from the list of active tracks. 3712 // TODO: implement behavior for compressed audio 3713 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000; 3714 size_t framesWritten = mBytesWritten / mFrameSize; 3715 if (mStandby || !last || 3716 track->presentationComplete(framesWritten, audioHALFrames)) { 3717 if (track->isStopped()) { 3718 track->reset(); 3719 } 3720 tracksToRemove->add(track); 3721 } 3722 } else { 3723 // No buffers for this track. Give it a few chances to 3724 // fill a buffer, then remove it from active list. 3725 // Only consider last track started for mixer state control 3726 if (--(track->mRetryCount) <= 0) { 3727 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name()); 3728 tracksToRemove->add(track); 3729 // indicate to client process that the track was disabled because of underrun; 3730 // it will then automatically call start() when data is available 3731 android_atomic_or(CBLK_DISABLED, &cblk->mFlags); 3732 } else if (last) { 3733 mixerStatus = MIXER_TRACKS_ENABLED; 3734 } 3735 } 3736 } 3737 } 3738 3739 // remove all the tracks that need to be... 3740 removeTracks_l(*tracksToRemove); 3741 3742 return mixerStatus; 3743} 3744 3745void AudioFlinger::DirectOutputThread::threadLoop_mix() 3746{ 3747 size_t frameCount = mFrameCount; 3748 int8_t *curBuf = (int8_t *)mMixBuffer; 3749 // output audio to hardware 3750 while (frameCount) { 3751 AudioBufferProvider::Buffer buffer; 3752 buffer.frameCount = frameCount; 3753 mActiveTrack->getNextBuffer(&buffer); 3754 if (buffer.raw == NULL) { 3755 memset(curBuf, 0, frameCount * mFrameSize); 3756 break; 3757 } 3758 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize); 3759 frameCount -= buffer.frameCount; 3760 curBuf += buffer.frameCount * mFrameSize; 3761 mActiveTrack->releaseBuffer(&buffer); 3762 } 3763 mCurrentWriteLength = curBuf - (int8_t *)mMixBuffer; 3764 sleepTime = 0; 3765 standbyTime = systemTime() + standbyDelay; 3766 mActiveTrack.clear(); 3767} 3768 3769void AudioFlinger::DirectOutputThread::threadLoop_sleepTime() 3770{ 3771 if (sleepTime == 0) { 3772 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 3773 sleepTime = activeSleepTime; 3774 } else { 3775 sleepTime = idleSleepTime; 3776 } 3777 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) { 3778 memset(mMixBuffer, 0, mFrameCount * mFrameSize); 3779 sleepTime = 0; 3780 } 3781} 3782 3783// getTrackName_l() must be called with ThreadBase::mLock held 3784int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused, 3785 int sessionId __unused) 3786{ 3787 return 0; 3788} 3789 3790// deleteTrackName_l() must be called with ThreadBase::mLock held 3791void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused) 3792{ 3793} 3794 3795// checkForNewParameters_l() must be called with ThreadBase::mLock held 3796bool AudioFlinger::DirectOutputThread::checkForNewParameters_l() 3797{ 3798 bool reconfig = false; 3799 3800 while (!mNewParameters.isEmpty()) { 3801 status_t status = NO_ERROR; 3802 String8 keyValuePair = mNewParameters[0]; 3803 AudioParameter param = AudioParameter(keyValuePair); 3804 int value; 3805 3806 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 3807 // do not accept frame count changes if tracks are open as the track buffer 3808 // size depends on frame count and correct behavior would not be garantied 3809 // if frame count is changed after track creation 3810 if (!mTracks.isEmpty()) { 3811 status = INVALID_OPERATION; 3812 } else { 3813 reconfig = true; 3814 } 3815 } 3816 if (status == NO_ERROR) { 3817 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3818 keyValuePair.string()); 3819 if (!mStandby && status == INVALID_OPERATION) { 3820 mOutput->stream->common.standby(&mOutput->stream->common); 3821 mStandby = true; 3822 mBytesWritten = 0; 3823 status = mOutput->stream->common.set_parameters(&mOutput->stream->common, 3824 keyValuePair.string()); 3825 } 3826 if (status == NO_ERROR && reconfig) { 3827 readOutputParameters(); 3828 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED); 3829 } 3830 } 3831 3832 mNewParameters.removeAt(0); 3833 3834 mParamStatus = status; 3835 mParamCond.signal(); 3836 // wait for condition with time out in case the thread calling ThreadBase::setParameters() 3837 // already timed out waiting for the status and will never signal the condition. 3838 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); 3839 } 3840 return reconfig; 3841} 3842 3843uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const 3844{ 3845 uint32_t time; 3846 if (audio_is_linear_pcm(mFormat)) { 3847 time = PlaybackThread::activeSleepTimeUs(); 3848 } else { 3849 time = 10000; 3850 } 3851 return time; 3852} 3853 3854uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const 3855{ 3856 uint32_t time; 3857 if (audio_is_linear_pcm(mFormat)) { 3858 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2; 3859 } else { 3860 time = 10000; 3861 } 3862 return time; 3863} 3864 3865uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const 3866{ 3867 uint32_t time; 3868 if (audio_is_linear_pcm(mFormat)) { 3869 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000); 3870 } else { 3871 time = 10000; 3872 } 3873 return time; 3874} 3875 3876void AudioFlinger::DirectOutputThread::cacheParameters_l() 3877{ 3878 PlaybackThread::cacheParameters_l(); 3879 3880 // use shorter standby delay as on normal output to release 3881 // hardware resources as soon as possible 3882 if (audio_is_linear_pcm(mFormat)) { 3883 standbyDelay = microseconds(activeSleepTime*2); 3884 } else { 3885 standbyDelay = kOffloadStandbyDelayNs; 3886 } 3887} 3888 3889// ---------------------------------------------------------------------------- 3890 3891AudioFlinger::AsyncCallbackThread::AsyncCallbackThread( 3892 const wp<AudioFlinger::PlaybackThread>& playbackThread) 3893 : Thread(false /*canCallJava*/), 3894 mPlaybackThread(playbackThread), 3895 mWriteAckSequence(0), 3896 mDrainSequence(0) 3897{ 3898} 3899 3900AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread() 3901{ 3902} 3903 3904void AudioFlinger::AsyncCallbackThread::onFirstRef() 3905{ 3906 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO); 3907} 3908 3909bool AudioFlinger::AsyncCallbackThread::threadLoop() 3910{ 3911 while (!exitPending()) { 3912 uint32_t writeAckSequence; 3913 uint32_t drainSequence; 3914 3915 { 3916 Mutex::Autolock _l(mLock); 3917 while (!((mWriteAckSequence & 1) || 3918 (mDrainSequence & 1) || 3919 exitPending())) { 3920 mWaitWorkCV.wait(mLock); 3921 } 3922 3923 if (exitPending()) { 3924 break; 3925 } 3926 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d", 3927 mWriteAckSequence, mDrainSequence); 3928 writeAckSequence = mWriteAckSequence; 3929 mWriteAckSequence &= ~1; 3930 drainSequence = mDrainSequence; 3931 mDrainSequence &= ~1; 3932 } 3933 { 3934 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote(); 3935 if (playbackThread != 0) { 3936 if (writeAckSequence & 1) { 3937 playbackThread->resetWriteBlocked(writeAckSequence >> 1); 3938 } 3939 if (drainSequence & 1) { 3940 playbackThread->resetDraining(drainSequence >> 1); 3941 } 3942 } 3943 } 3944 } 3945 return false; 3946} 3947 3948void AudioFlinger::AsyncCallbackThread::exit() 3949{ 3950 ALOGV("AsyncCallbackThread::exit"); 3951 Mutex::Autolock _l(mLock); 3952 requestExit(); 3953 mWaitWorkCV.broadcast(); 3954} 3955 3956void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence) 3957{ 3958 Mutex::Autolock _l(mLock); 3959 // bit 0 is cleared 3960 mWriteAckSequence = sequence << 1; 3961} 3962 3963void AudioFlinger::AsyncCallbackThread::resetWriteBlocked() 3964{ 3965 Mutex::Autolock _l(mLock); 3966 // ignore unexpected callbacks 3967 if (mWriteAckSequence & 2) { 3968 mWriteAckSequence |= 1; 3969 mWaitWorkCV.signal(); 3970 } 3971} 3972 3973void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence) 3974{ 3975 Mutex::Autolock _l(mLock); 3976 // bit 0 is cleared 3977 mDrainSequence = sequence << 1; 3978} 3979 3980void AudioFlinger::AsyncCallbackThread::resetDraining() 3981{ 3982 Mutex::Autolock _l(mLock); 3983 // ignore unexpected callbacks 3984 if (mDrainSequence & 2) { 3985 mDrainSequence |= 1; 3986 mWaitWorkCV.signal(); 3987 } 3988} 3989 3990 3991// ---------------------------------------------------------------------------- 3992AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger, 3993 AudioStreamOut* output, audio_io_handle_t id, uint32_t device) 3994 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD), 3995 mHwPaused(false), 3996 mFlushPending(false), 3997 mPausedBytesRemaining(0) 3998{ 3999 //FIXME: mStandby should be set to true by ThreadBase constructor 4000 mStandby = true; 4001} 4002 4003void AudioFlinger::OffloadThread::threadLoop_exit() 4004{ 4005 if (mFlushPending || mHwPaused) { 4006 // If a flush is pending or track was paused, just discard buffered data 4007 flushHw_l(); 4008 } else { 4009 mMixerStatus = MIXER_DRAIN_ALL; 4010 threadLoop_drain(); 4011 } 4012 mCallbackThread->exit(); 4013 PlaybackThread::threadLoop_exit(); 4014} 4015 4016AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l( 4017 Vector< sp<Track> > *tracksToRemove 4018) 4019{ 4020 size_t count = mActiveTracks.size(); 4021 4022 mixer_state mixerStatus = MIXER_IDLE; 4023 bool doHwPause = false; 4024 bool doHwResume = false; 4025 4026 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count); 4027 4028 // find out which tracks need to be processed 4029 for (size_t i = 0; i < count; i++) { 4030 sp<Track> t = mActiveTracks[i].promote(); 4031 // The track died recently 4032 if (t == 0) { 4033 continue; 4034 } 4035 Track* const track = t.get(); 4036 audio_track_cblk_t* cblk = track->cblk(); 4037 // Only consider last track started for volume and mixer state control. 4038 // In theory an older track could underrun and restart after the new one starts 4039 // but as we only care about the transition phase between two tracks on a 4040 // direct output, it is not a problem to ignore the underrun case. 4041 sp<Track> l = mLatestActiveTrack.promote(); 4042 bool last = l.get() == track; 4043 4044 if (track->isInvalid()) { 4045 ALOGW("An invalidated track shouldn't be in active list"); 4046 tracksToRemove->add(track); 4047 continue; 4048 } 4049 4050 if (track->mState == TrackBase::IDLE) { 4051 ALOGW("An idle track shouldn't be in active list"); 4052 continue; 4053 } 4054 4055 if (track->isPausing()) { 4056 track->setPaused(); 4057 if (last) { 4058 if (!mHwPaused) { 4059 doHwPause = true; 4060 mHwPaused = true; 4061 } 4062 // If we were part way through writing the mixbuffer to 4063 // the HAL we must save this until we resume 4064 // BUG - this will be wrong if a different track is made active, 4065 // in that case we want to discard the pending data in the 4066 // mixbuffer and tell the client to present it again when the 4067 // track is resumed 4068 mPausedWriteLength = mCurrentWriteLength; 4069 mPausedBytesRemaining = mBytesRemaining; 4070 mBytesRemaining = 0; // stop writing 4071 } 4072 tracksToRemove->add(track); 4073 } else if (track->isFlushPending()) { 4074 track->flushAck(); 4075 if (last) { 4076 mFlushPending = true; 4077 } 4078 } else if (track->framesReady() && track->isReady() && 4079 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) { 4080 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer); 4081 if (track->mFillingUpStatus == Track::FS_FILLED) { 4082 track->mFillingUpStatus = Track::FS_ACTIVE; 4083 // make sure processVolume_l() will apply new volume even if 0 4084 mLeftVolFloat = mRightVolFloat = -1.0; 4085 if (track->mState == TrackBase::RESUMING) { 4086 track->mState = TrackBase::ACTIVE; 4087 if (last) { 4088 if (mPausedBytesRemaining) { 4089 // Need to continue write that was interrupted 4090 mCurrentWriteLength = mPausedWriteLength; 4091 mBytesRemaining = mPausedBytesRemaining; 4092 mPausedBytesRemaining = 0; 4093 } 4094 if (mHwPaused) { 4095 doHwResume = true; 4096 mHwPaused = false; 4097 // threadLoop_mix() will handle the case that we need to 4098 // resume an interrupted write 4099 } 4100 // enable write to audio HAL 4101 sleepTime = 0; 4102 } 4103 } 4104 } 4105 4106 if (last) { 4107 sp<Track> previousTrack = mPreviousTrack.promote(); 4108 if (previousTrack != 0) { 4109 if (track != previousTrack.get()) { 4110 // Flush any data still being written from last track 4111 mBytesRemaining = 0; 4112 if (mPausedBytesRemaining) { 4113 // Last track was paused so we also need to flush saved 4114 // mixbuffer state and invalidate track so that it will 4115 // re-submit that unwritten data when it is next resumed 4116 mPausedBytesRemaining = 0; 4117 // Invalidate is a bit drastic - would be more efficient 4118 // to have a flag to tell client that some of the 4119 // previously written data was lost 4120 previousTrack->invalidate(); 4121 } 4122 // flush data already sent to the DSP if changing audio session as audio 4123 // comes from a different source. Also invalidate previous track to force a 4124 // seek when resuming. 4125 if (previousTrack->sessionId() != track->sessionId()) { 4126 previousTrack->invalidate(); 4127 } 4128 } 4129 } 4130 mPreviousTrack = track; 4131 // reset retry count 4132 track->mRetryCount = kMaxTrackRetriesOffload; 4133 mActiveTrack = t; 4134 mixerStatus = MIXER_TRACKS_READY; 4135 } 4136 } else { 4137 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer); 4138 if (track->isStopping_1()) { 4139 // Hardware buffer can hold a large amount of audio so we must 4140 // wait for all current track's data to drain before we say 4141 // that the track is stopped. 4142 if (mBytesRemaining == 0) { 4143 // Only start draining when all data in mixbuffer 4144 // has been written 4145 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2"); 4146 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain 4147 // do not drain if no data was ever sent to HAL (mStandby == true) 4148 if (last && !mStandby) { 4149 // do not modify drain sequence if we are already draining. This happens 4150 // when resuming from pause after drain. 4151 if ((mDrainSequence & 1) == 0) { 4152 sleepTime = 0; 4153 standbyTime = systemTime() + standbyDelay; 4154 mixerStatus = MIXER_DRAIN_TRACK; 4155 mDrainSequence += 2; 4156 } 4157 if (mHwPaused) { 4158 // It is possible to move from PAUSED to STOPPING_1 without 4159 // a resume so we must ensure hardware is running 4160 doHwResume = true; 4161 mHwPaused = false; 4162 } 4163 } 4164 } 4165 } else if (track->isStopping_2()) { 4166 // Drain has completed or we are in standby, signal presentation complete 4167 if (!(mDrainSequence & 1) || !last || mStandby) { 4168 track->mState = TrackBase::STOPPED; 4169 size_t audioHALFrames = 4170 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000; 4171 size_t framesWritten = 4172 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common); 4173 track->presentationComplete(framesWritten, audioHALFrames); 4174 track->reset(); 4175 tracksToRemove->add(track); 4176 } 4177 } else { 4178 // No buffers for this track. Give it a few chances to 4179 // fill a buffer, then remove it from active list. 4180 if (--(track->mRetryCount) <= 0) { 4181 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list", 4182 track->name()); 4183 tracksToRemove->add(track); 4184 // indicate to client process that the track was disabled because of underrun; 4185 // it will then automatically call start() when data is available 4186 android_atomic_or(CBLK_DISABLED, &cblk->mFlags); 4187 } else if (last){ 4188 mixerStatus = MIXER_TRACKS_ENABLED; 4189 } 4190 } 4191 } 4192 // compute volume for this track 4193 processVolume_l(track, last); 4194 } 4195 4196 // make sure the pause/flush/resume sequence is executed in the right order. 4197 // If a flush is pending and a track is active but the HW is not paused, force a HW pause 4198 // before flush and then resume HW. This can happen in case of pause/flush/resume 4199 // if resume is received before pause is executed. 4200 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) { 4201 mOutput->stream->pause(mOutput->stream); 4202 } 4203 if (mFlushPending) { 4204 flushHw_l(); 4205 mFlushPending = false; 4206 } 4207 if (!mStandby && doHwResume) { 4208 mOutput->stream->resume(mOutput->stream); 4209 } 4210 4211 // remove all the tracks that need to be... 4212 removeTracks_l(*tracksToRemove); 4213 4214 return mixerStatus; 4215} 4216 4217// must be called with thread mutex locked 4218bool AudioFlinger::OffloadThread::waitingAsyncCallback_l() 4219{ 4220 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d", 4221 mWriteAckSequence, mDrainSequence); 4222 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) { 4223 return true; 4224 } 4225 return false; 4226} 4227 4228// must be called with thread mutex locked 4229bool AudioFlinger::OffloadThread::shouldStandby_l() 4230{ 4231 bool trackPaused = false; 4232 4233 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack 4234 // after a timeout and we will enter standby then. 4235 if (mTracks.size() > 0) { 4236 trackPaused = mTracks[mTracks.size() - 1]->isPaused(); 4237 } 4238 4239 return !mStandby && !trackPaused; 4240} 4241 4242 4243bool AudioFlinger::OffloadThread::waitingAsyncCallback() 4244{ 4245 Mutex::Autolock _l(mLock); 4246 return waitingAsyncCallback_l(); 4247} 4248 4249void AudioFlinger::OffloadThread::flushHw_l() 4250{ 4251 mOutput->stream->flush(mOutput->stream); 4252 // Flush anything still waiting in the mixbuffer 4253 mCurrentWriteLength = 0; 4254 mBytesRemaining = 0; 4255 mPausedWriteLength = 0; 4256 mPausedBytesRemaining = 0; 4257 mHwPaused = false; 4258 4259 if (mUseAsyncWrite) { 4260 // discard any pending drain or write ack by incrementing sequence 4261 mWriteAckSequence = (mWriteAckSequence + 2) & ~1; 4262 mDrainSequence = (mDrainSequence + 2) & ~1; 4263 ALOG_ASSERT(mCallbackThread != 0); 4264 mCallbackThread->setWriteBlocked(mWriteAckSequence); 4265 mCallbackThread->setDraining(mDrainSequence); 4266 } 4267} 4268 4269void AudioFlinger::OffloadThread::onAddNewTrack_l() 4270{ 4271 sp<Track> previousTrack = mPreviousTrack.promote(); 4272 sp<Track> latestTrack = mLatestActiveTrack.promote(); 4273 4274 if (previousTrack != 0 && latestTrack != 0 && 4275 (previousTrack->sessionId() != latestTrack->sessionId())) { 4276 mFlushPending = true; 4277 } 4278 PlaybackThread::onAddNewTrack_l(); 4279} 4280 4281// ---------------------------------------------------------------------------- 4282 4283AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, 4284 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id) 4285 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(), 4286 DUPLICATING), 4287 mWaitTimeMs(UINT_MAX) 4288{ 4289 addOutputTrack(mainThread); 4290} 4291 4292AudioFlinger::DuplicatingThread::~DuplicatingThread() 4293{ 4294 for (size_t i = 0; i < mOutputTracks.size(); i++) { 4295 mOutputTracks[i]->destroy(); 4296 } 4297} 4298 4299void AudioFlinger::DuplicatingThread::threadLoop_mix() 4300{ 4301 // mix buffers... 4302 if (outputsReady(outputTracks)) { 4303 mAudioMixer->process(AudioBufferProvider::kInvalidPTS); 4304 } else { 4305 memset(mMixBuffer, 0, mixBufferSize); 4306 } 4307 sleepTime = 0; 4308 writeFrames = mNormalFrameCount; 4309 mCurrentWriteLength = mixBufferSize; 4310 standbyTime = systemTime() + standbyDelay; 4311} 4312 4313void AudioFlinger::DuplicatingThread::threadLoop_sleepTime() 4314{ 4315 if (sleepTime == 0) { 4316 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 4317 sleepTime = activeSleepTime; 4318 } else { 4319 sleepTime = idleSleepTime; 4320 } 4321 } else if (mBytesWritten != 0) { 4322 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 4323 writeFrames = mNormalFrameCount; 4324 memset(mMixBuffer, 0, mixBufferSize); 4325 } else { 4326 // flush remaining overflow buffers in output tracks 4327 writeFrames = 0; 4328 } 4329 sleepTime = 0; 4330 } 4331} 4332 4333ssize_t AudioFlinger::DuplicatingThread::threadLoop_write() 4334{ 4335 for (size_t i = 0; i < outputTracks.size(); i++) { 4336 outputTracks[i]->write(mMixBuffer, writeFrames); 4337 } 4338 mStandby = false; 4339 return (ssize_t)mixBufferSize; 4340} 4341 4342void AudioFlinger::DuplicatingThread::threadLoop_standby() 4343{ 4344 // DuplicatingThread implements standby by stopping all tracks 4345 for (size_t i = 0; i < outputTracks.size(); i++) { 4346 outputTracks[i]->stop(); 4347 } 4348} 4349 4350void AudioFlinger::DuplicatingThread::saveOutputTracks() 4351{ 4352 outputTracks = mOutputTracks; 4353} 4354 4355void AudioFlinger::DuplicatingThread::clearOutputTracks() 4356{ 4357 outputTracks.clear(); 4358} 4359 4360void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread) 4361{ 4362 Mutex::Autolock _l(mLock); 4363 // FIXME explain this formula 4364 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate(); 4365 OutputTrack *outputTrack = new OutputTrack(thread, 4366 this, 4367 mSampleRate, 4368 mFormat, 4369 mChannelMask, 4370 frameCount, 4371 IPCThreadState::self()->getCallingUid()); 4372 if (outputTrack->cblk() != NULL) { 4373 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f); 4374 mOutputTracks.add(outputTrack); 4375 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread); 4376 updateWaitTime_l(); 4377 } 4378} 4379 4380void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread) 4381{ 4382 Mutex::Autolock _l(mLock); 4383 for (size_t i = 0; i < mOutputTracks.size(); i++) { 4384 if (mOutputTracks[i]->thread() == thread) { 4385 mOutputTracks[i]->destroy(); 4386 mOutputTracks.removeAt(i); 4387 updateWaitTime_l(); 4388 return; 4389 } 4390 } 4391 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread); 4392} 4393 4394// caller must hold mLock 4395void AudioFlinger::DuplicatingThread::updateWaitTime_l() 4396{ 4397 mWaitTimeMs = UINT_MAX; 4398 for (size_t i = 0; i < mOutputTracks.size(); i++) { 4399 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote(); 4400 if (strong != 0) { 4401 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate(); 4402 if (waitTimeMs < mWaitTimeMs) { 4403 mWaitTimeMs = waitTimeMs; 4404 } 4405 } 4406 } 4407} 4408 4409 4410bool AudioFlinger::DuplicatingThread::outputsReady( 4411 const SortedVector< sp<OutputTrack> > &outputTracks) 4412{ 4413 for (size_t i = 0; i < outputTracks.size(); i++) { 4414 sp<ThreadBase> thread = outputTracks[i]->thread().promote(); 4415 if (thread == 0) { 4416 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", 4417 outputTracks[i].get()); 4418 return false; 4419 } 4420 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 4421 // see note at standby() declaration 4422 if (playbackThread->standby() && !playbackThread->isSuspended()) { 4423 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), 4424 thread.get()); 4425 return false; 4426 } 4427 } 4428 return true; 4429} 4430 4431uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const 4432{ 4433 return (mWaitTimeMs * 1000) / 2; 4434} 4435 4436void AudioFlinger::DuplicatingThread::cacheParameters_l() 4437{ 4438 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first 4439 updateWaitTime_l(); 4440 4441 MixerThread::cacheParameters_l(); 4442} 4443 4444// ---------------------------------------------------------------------------- 4445// Record 4446// ---------------------------------------------------------------------------- 4447 4448AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, 4449 AudioStreamIn *input, 4450 uint32_t sampleRate, 4451 audio_channel_mask_t channelMask, 4452 audio_io_handle_t id, 4453 audio_devices_t outDevice, 4454 audio_devices_t inDevice 4455#ifdef TEE_SINK 4456 , const sp<NBAIO_Sink>& teeSink 4457#endif 4458 ) : 4459 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD), 4460 mInput(input), mActiveTracksGen(0), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL), 4461 // mRsmpInFrames, mRsmpInFramesP2, mRsmpInUnrel, mRsmpInFront, and mRsmpInRear 4462 // are set by readInputParameters() 4463 // mRsmpInIndex LEGACY 4464 mReqChannelCount(popcount(channelMask)), 4465 mReqSampleRate(sampleRate) 4466 // mBytesRead is only meaningful while active, and so is cleared in start() 4467 // (but might be better to also clear here for dump?) 4468#ifdef TEE_SINK 4469 , mTeeSink(teeSink) 4470#endif 4471{ 4472 snprintf(mName, kNameLength, "AudioIn_%X", id); 4473 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName); 4474 4475 readInputParameters(); 4476} 4477 4478 4479AudioFlinger::RecordThread::~RecordThread() 4480{ 4481 mAudioFlinger->unregisterWriter(mNBLogWriter); 4482 delete[] mRsmpInBuffer; 4483 delete mResampler; 4484 delete[] mRsmpOutBuffer; 4485} 4486 4487void AudioFlinger::RecordThread::onFirstRef() 4488{ 4489 run(mName, PRIORITY_URGENT_AUDIO); 4490} 4491 4492bool AudioFlinger::RecordThread::threadLoop() 4493{ 4494 nsecs_t lastWarning = 0; 4495 4496 inputStandBy(); 4497 4498 // used to verify we've read at least once before evaluating how many bytes were read 4499 bool readOnce = false; 4500 4501 // used to request a deferred sleep, to be executed later while mutex is unlocked 4502 bool doSleep = false; 4503 4504reacquire_wakelock: 4505 sp<RecordTrack> activeTrack; 4506 int activeTracksGen; 4507 { 4508 Mutex::Autolock _l(mLock); 4509 size_t size = mActiveTracks.size(); 4510 activeTracksGen = mActiveTracksGen; 4511 if (size > 0) { 4512 // FIXME an arbitrary choice 4513 activeTrack = mActiveTracks[0]; 4514 acquireWakeLock_l(activeTrack->uid()); 4515 if (size > 1) { 4516 SortedVector<int> tmp; 4517 for (size_t i = 0; i < size; i++) { 4518 tmp.add(mActiveTracks[i]->uid()); 4519 } 4520 updateWakeLockUids_l(tmp); 4521 } 4522 } else { 4523 acquireWakeLock_l(-1); 4524 } 4525 } 4526 4527 // start recording 4528 for (;;) { 4529 TrackBase::track_state activeTrackState; 4530 Vector< sp<EffectChain> > effectChains; 4531 4532 // sleep with mutex unlocked 4533 if (doSleep) { 4534 doSleep = false; 4535 usleep(kRecordThreadSleepUs); 4536 } 4537 4538 { // scope for mLock 4539 Mutex::Autolock _l(mLock); 4540 4541 processConfigEvents_l(); 4542 // return value 'reconfig' is currently unused 4543 bool reconfig = checkForNewParameters_l(); 4544 4545 // check exitPending here because checkForNewParameters_l() and 4546 // checkForNewParameters_l() can temporarily release mLock 4547 if (exitPending()) { 4548 break; 4549 } 4550 4551 // if no active track(s), then standby and release wakelock 4552 size_t size = mActiveTracks.size(); 4553 if (size == 0) { 4554 standbyIfNotAlreadyInStandby(); 4555 // exitPending() can't become true here 4556 releaseWakeLock_l(); 4557 ALOGV("RecordThread: loop stopping"); 4558 // go to sleep 4559 mWaitWorkCV.wait(mLock); 4560 ALOGV("RecordThread: loop starting"); 4561 goto reacquire_wakelock; 4562 } 4563 4564 if (mActiveTracksGen != activeTracksGen) { 4565 activeTracksGen = mActiveTracksGen; 4566 SortedVector<int> tmp; 4567 for (size_t i = 0; i < size; i++) { 4568 tmp.add(mActiveTracks[i]->uid()); 4569 } 4570 updateWakeLockUids_l(tmp); 4571 // FIXME an arbitrary choice 4572 activeTrack = mActiveTracks[0]; 4573 } 4574 4575 if (activeTrack->isTerminated()) { 4576 removeTrack_l(activeTrack); 4577 mActiveTracks.remove(activeTrack); 4578 mActiveTracksGen++; 4579 continue; 4580 } 4581 4582 activeTrackState = activeTrack->mState; 4583 switch (activeTrackState) { 4584 case TrackBase::PAUSING: 4585 standbyIfNotAlreadyInStandby(); 4586 mActiveTracks.remove(activeTrack); 4587 mActiveTracksGen++; 4588 mStartStopCond.broadcast(); 4589 doSleep = true; 4590 continue; 4591 4592 case TrackBase::RESUMING: 4593 mStandby = false; 4594 if (mReqChannelCount != activeTrack->channelCount()) { 4595 mActiveTracks.remove(activeTrack); 4596 mActiveTracksGen++; 4597 mStartStopCond.broadcast(); 4598 continue; 4599 } 4600 if (readOnce) { 4601 mStartStopCond.broadcast(); 4602 // record start succeeds only if first read from audio input succeeds 4603 if (mBytesRead < 0) { 4604 mActiveTracks.remove(activeTrack); 4605 mActiveTracksGen++; 4606 continue; 4607 } 4608 activeTrack->mState = TrackBase::ACTIVE; 4609 } 4610 break; 4611 4612 case TrackBase::ACTIVE: 4613 break; 4614 4615 case TrackBase::IDLE: 4616 doSleep = true; 4617 continue; 4618 4619 default: 4620 LOG_FATAL("Unexpected activeTrackState %d", activeTrackState); 4621 } 4622 4623 lockEffectChains_l(effectChains); 4624 } 4625 4626 // thread mutex is now unlocked, mActiveTracks unknown, activeTrack != 0, kept, immutable 4627 // activeTrack->mState unknown, activeTrackState immutable and is ACTIVE or RESUMING 4628 4629 for (size_t i = 0; i < effectChains.size(); i ++) { 4630 // thread mutex is not locked, but effect chain is locked 4631 effectChains[i]->process_l(); 4632 } 4633 4634 AudioBufferProvider::Buffer buffer; 4635 buffer.frameCount = mFrameCount; 4636 status_t status = activeTrack->getNextBuffer(&buffer); 4637 if (status == NO_ERROR) { 4638 readOnce = true; 4639 size_t framesOut = buffer.frameCount; 4640 if (mResampler == NULL) { 4641 // no resampling 4642 while (framesOut) { 4643 size_t framesIn = mFrameCount - mRsmpInIndex; 4644 if (framesIn > 0) { 4645 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize; 4646 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * 4647 activeTrack->mFrameSize; 4648 if (framesIn > framesOut) { 4649 framesIn = framesOut; 4650 } 4651 mRsmpInIndex += framesIn; 4652 framesOut -= framesIn; 4653 if (mChannelCount == mReqChannelCount) { 4654 memcpy(dst, src, framesIn * mFrameSize); 4655 } else { 4656 if (mChannelCount == 1) { 4657 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, 4658 (int16_t *)src, framesIn); 4659 } else { 4660 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst, 4661 (int16_t *)src, framesIn); 4662 } 4663 } 4664 } 4665 if (framesOut > 0 && mFrameCount == mRsmpInIndex) { 4666 void *readInto; 4667 if (framesOut == mFrameCount && mChannelCount == mReqChannelCount) { 4668 readInto = buffer.raw; 4669 framesOut = 0; 4670 } else { 4671 readInto = mRsmpInBuffer; 4672 mRsmpInIndex = 0; 4673 } 4674 mBytesRead = mInput->stream->read(mInput->stream, readInto, mBufferSize); 4675 if (mBytesRead <= 0) { 4676 // TODO: verify that it's benign to use a stale track state 4677 if ((mBytesRead < 0) && (activeTrackState == TrackBase::ACTIVE)) 4678 { 4679 ALOGE("Error reading audio input"); 4680 // Force input into standby so that it tries to 4681 // recover at next read attempt 4682 inputStandBy(); 4683 doSleep = true; 4684 } 4685 mRsmpInIndex = mFrameCount; 4686 framesOut = 0; 4687 buffer.frameCount = 0; 4688 } 4689#ifdef TEE_SINK 4690 else if (mTeeSink != 0) { 4691 (void) mTeeSink->write(readInto, 4692 mBytesRead >> Format_frameBitShift(mTeeSink->format())); 4693 } 4694#endif 4695 } 4696 } 4697 } else { 4698 // resampling 4699 4700 // avoid busy-waiting if client doesn't keep up 4701 bool madeProgress = false; 4702 4703 // keep mRsmpInBuffer full so resampler always has sufficient input 4704 for (;;) { 4705 int32_t rear = mRsmpInRear; 4706 ssize_t filled = rear - mRsmpInFront; 4707 ALOG_ASSERT(0 <= filled && (size_t) filled <= mRsmpInFramesP2); 4708 // exit once there is enough data in buffer for resampler 4709 if ((size_t) filled >= mRsmpInFrames) { 4710 break; 4711 } 4712 size_t avail = mRsmpInFramesP2 - filled; 4713 // Only try to read full HAL buffers. 4714 // But if the HAL read returns a partial buffer, use it. 4715 if (avail < mFrameCount) { 4716 ALOGE("insufficient space to read: avail %d < mFrameCount %d", 4717 avail, mFrameCount); 4718 break; 4719 } 4720 // If 'avail' is non-contiguous, first read past the nominal end of buffer, then 4721 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated. 4722 rear &= mRsmpInFramesP2 - 1; 4723 mBytesRead = mInput->stream->read(mInput->stream, 4724 &mRsmpInBuffer[rear * mChannelCount], mBufferSize); 4725 if (mBytesRead <= 0) { 4726 ALOGE("read failed: mBytesRead=%d < %u", mBytesRead, mBufferSize); 4727 break; 4728 } 4729 ALOG_ASSERT((size_t) mBytesRead <= mBufferSize); 4730 size_t framesRead = mBytesRead / mFrameSize; 4731 ALOG_ASSERT(framesRead > 0); 4732 madeProgress = true; 4733 // If 'avail' was non-contiguous, we now correct for reading past end of buffer. 4734 size_t part1 = mRsmpInFramesP2 - rear; 4735 if (framesRead > part1) { 4736 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount], 4737 (framesRead - part1) * mFrameSize); 4738 } 4739 mRsmpInRear += framesRead; 4740 } 4741 4742 if (!madeProgress) { 4743 ALOGV("Did not make progress"); 4744 usleep(((mFrameCount * 1000) / mSampleRate) * 1000); 4745 } 4746 4747 // resampler accumulates, but we only have one source track 4748 memset(mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t)); 4749 mResampler->resample(mRsmpOutBuffer, framesOut, 4750 this /* AudioBufferProvider* */); 4751 // ditherAndClamp() works as long as all buffers returned by 4752 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true. 4753 if (mReqChannelCount == 1) { 4754 // temporarily type pun mRsmpOutBuffer from Q19.12 to int16_t 4755 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut); 4756 // the resampler always outputs stereo samples: 4757 // do post stereo to mono conversion 4758 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer, 4759 framesOut); 4760 } else { 4761 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut); 4762 } 4763 // now done with mRsmpOutBuffer 4764 4765 } 4766 if (mFramestoDrop == 0) { 4767 activeTrack->releaseBuffer(&buffer); 4768 } else { 4769 if (mFramestoDrop > 0) { 4770 mFramestoDrop -= buffer.frameCount; 4771 if (mFramestoDrop <= 0) { 4772 clearSyncStartEvent(); 4773 } 4774 } else { 4775 mFramestoDrop += buffer.frameCount; 4776 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 || 4777 mSyncStartEvent->isCancelled()) { 4778 ALOGW("Synced record %s, session %d, trigger session %d", 4779 (mFramestoDrop >= 0) ? "timed out" : "cancelled", 4780 activeTrack->sessionId(), 4781 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0); 4782 clearSyncStartEvent(); 4783 } 4784 } 4785 } 4786 activeTrack->clearOverflow(); 4787 } 4788 // client isn't retrieving buffers fast enough 4789 else { 4790 if (!activeTrack->setOverflow()) { 4791 nsecs_t now = systemTime(); 4792 if ((now - lastWarning) > kWarningThrottleNs) { 4793 ALOGW("RecordThread: buffer overflow"); 4794 lastWarning = now; 4795 } 4796 } 4797 // Release the processor for a while before asking for a new buffer. 4798 // This will give the application more chance to read from the buffer and 4799 // clear the overflow. 4800 doSleep = true; 4801 } 4802 4803 // enable changes in effect chain 4804 unlockEffectChains(effectChains); 4805 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end 4806 } 4807 4808 standbyIfNotAlreadyInStandby(); 4809 4810 { 4811 Mutex::Autolock _l(mLock); 4812 for (size_t i = 0; i < mTracks.size(); i++) { 4813 sp<RecordTrack> track = mTracks[i]; 4814 track->invalidate(); 4815 } 4816 mActiveTracks.clear(); 4817 mActiveTracksGen++; 4818 mStartStopCond.broadcast(); 4819 } 4820 4821 releaseWakeLock(); 4822 4823 ALOGV("RecordThread %p exiting", this); 4824 return false; 4825} 4826 4827void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby() 4828{ 4829 if (!mStandby) { 4830 inputStandBy(); 4831 mStandby = true; 4832 } 4833} 4834 4835void AudioFlinger::RecordThread::inputStandBy() 4836{ 4837 mInput->stream->common.standby(&mInput->stream->common); 4838} 4839 4840sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l( 4841 const sp<AudioFlinger::Client>& client, 4842 uint32_t sampleRate, 4843 audio_format_t format, 4844 audio_channel_mask_t channelMask, 4845 size_t *pFrameCount, 4846 int sessionId, 4847 int uid, 4848 IAudioFlinger::track_flags_t *flags, 4849 pid_t tid, 4850 status_t *status) 4851{ 4852 size_t frameCount = *pFrameCount; 4853 sp<RecordTrack> track; 4854 status_t lStatus; 4855 4856 lStatus = initCheck(); 4857 if (lStatus != NO_ERROR) { 4858 ALOGE("createRecordTrack_l() audio driver not initialized"); 4859 goto Exit; 4860 } 4861 4862 // client expresses a preference for FAST, but we get the final say 4863 if (*flags & IAudioFlinger::TRACK_FAST) { 4864 if ( 4865 // use case: callback handler and frame count is default or at least as large as HAL 4866 ( 4867 (tid != -1) && 4868 ((frameCount == 0) || 4869 (frameCount >= mFrameCount)) 4870 ) && 4871 // FIXME when record supports non-PCM data, also check for audio_is_linear_pcm(format) 4872 // mono or stereo 4873 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) || 4874 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) && 4875 // hardware sample rate 4876 (sampleRate == mSampleRate) && 4877 // record thread has an associated fast recorder 4878 hasFastRecorder() 4879 // FIXME test that RecordThread for this fast track has a capable output HAL 4880 // FIXME add a permission test also? 4881 ) { 4882 // if frameCount not specified, then it defaults to fast recorder (HAL) frame count 4883 if (frameCount == 0) { 4884 frameCount = mFrameCount * kFastTrackMultiplier; 4885 } 4886 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d", 4887 frameCount, mFrameCount); 4888 } else { 4889 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%d " 4890 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u " 4891 "hasFastRecorder=%d tid=%d", 4892 frameCount, mFrameCount, format, 4893 audio_is_linear_pcm(format), 4894 channelMask, sampleRate, mSampleRate, hasFastRecorder(), tid); 4895 *flags &= ~IAudioFlinger::TRACK_FAST; 4896 // For compatibility with AudioRecord calculation, buffer depth is forced 4897 // to be at least 2 x the record thread frame count and cover audio hardware latency. 4898 // This is probably too conservative, but legacy application code may depend on it. 4899 // If you change this calculation, also review the start threshold which is related. 4900 uint32_t latencyMs = 50; // FIXME mInput->stream->get_latency(mInput->stream); 4901 size_t mNormalFrameCount = 2048; // FIXME 4902 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate); 4903 if (minBufCount < 2) { 4904 minBufCount = 2; 4905 } 4906 size_t minFrameCount = mNormalFrameCount * minBufCount; 4907 if (frameCount < minFrameCount) { 4908 frameCount = minFrameCount; 4909 } 4910 } 4911 } 4912 *pFrameCount = frameCount; 4913 4914 // FIXME use flags and tid similar to createTrack_l() 4915 4916 { // scope for mLock 4917 Mutex::Autolock _l(mLock); 4918 4919 track = new RecordTrack(this, client, sampleRate, 4920 format, channelMask, frameCount, sessionId, uid); 4921 4922 lStatus = track->initCheck(); 4923 if (lStatus != NO_ERROR) { 4924 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus); 4925 // track must be cleared from the caller as the caller has the AF lock 4926 goto Exit; 4927 } 4928 mTracks.add(track); 4929 4930 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 4931 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 4932 mAudioFlinger->btNrecIsOff(); 4933 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId); 4934 setEffectSuspended_l(FX_IID_NS, suspend, sessionId); 4935 4936 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) { 4937 pid_t callingPid = IPCThreadState::self()->getCallingPid(); 4938 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful, 4939 // so ask activity manager to do this on our behalf 4940 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp); 4941 } 4942 } 4943 lStatus = NO_ERROR; 4944 4945Exit: 4946 *status = lStatus; 4947 return track; 4948} 4949 4950status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, 4951 AudioSystem::sync_event_t event, 4952 int triggerSession) 4953{ 4954 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession); 4955 sp<ThreadBase> strongMe = this; 4956 status_t status = NO_ERROR; 4957 4958 if (event == AudioSystem::SYNC_EVENT_NONE) { 4959 clearSyncStartEvent(); 4960 } else if (event != AudioSystem::SYNC_EVENT_SAME) { 4961 mSyncStartEvent = mAudioFlinger->createSyncEvent(event, 4962 triggerSession, 4963 recordTrack->sessionId(), 4964 syncStartEventCallback, 4965 this); 4966 // Sync event can be cancelled by the trigger session if the track is not in a 4967 // compatible state in which case we start record immediately 4968 if (mSyncStartEvent->isCancelled()) { 4969 clearSyncStartEvent(); 4970 } else { 4971 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs 4972 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000); 4973 } 4974 } 4975 4976 { 4977 // This section is a rendezvous between binder thread executing start() and RecordThread 4978 AutoMutex lock(mLock); 4979 if (mActiveTracks.size() > 0) { 4980 // FIXME does not work for multiple active tracks 4981 if (mActiveTracks.indexOf(recordTrack) != 0) { 4982 status = -EBUSY; 4983 } else if (recordTrack->mState == TrackBase::PAUSING) { 4984 recordTrack->mState = TrackBase::ACTIVE; 4985 } 4986 return status; 4987 } 4988 4989 // FIXME why? already set in constructor, 'STARTING_1' would be more accurate 4990 recordTrack->mState = TrackBase::IDLE; 4991 mActiveTracks.add(recordTrack); 4992 mActiveTracksGen++; 4993 mLock.unlock(); 4994 status_t status = AudioSystem::startInput(mId); 4995 mLock.lock(); 4996 // FIXME should verify that mActiveTrack is still == recordTrack 4997 if (status != NO_ERROR) { 4998 mActiveTracks.remove(recordTrack); 4999 mActiveTracksGen++; 5000 clearSyncStartEvent(); 5001 return status; 5002 } 5003 // FIXME LEGACY 5004 mRsmpInIndex = mFrameCount; 5005 mRsmpInFront = 0; 5006 mRsmpInRear = 0; 5007 mRsmpInUnrel = 0; 5008 mBytesRead = 0; 5009 if (mResampler != NULL) { 5010 mResampler->reset(); 5011 } 5012 // FIXME hijacking a playback track state name which was intended for start after pause; 5013 // here 'STARTING_2' would be more accurate 5014 recordTrack->mState = TrackBase::RESUMING; 5015 // signal thread to start 5016 ALOGV("Signal record thread"); 5017 mWaitWorkCV.broadcast(); 5018 // do not wait for mStartStopCond if exiting 5019 if (exitPending()) { 5020 mActiveTracks.remove(recordTrack); 5021 mActiveTracksGen++; 5022 status = INVALID_OPERATION; 5023 goto startError; 5024 } 5025 // FIXME incorrect usage of wait: no explicit predicate or loop 5026 mStartStopCond.wait(mLock); 5027 if (mActiveTracks.indexOf(recordTrack) < 0) { 5028 ALOGV("Record failed to start"); 5029 status = BAD_VALUE; 5030 goto startError; 5031 } 5032 ALOGV("Record started OK"); 5033 return status; 5034 } 5035 5036startError: 5037 AudioSystem::stopInput(mId); 5038 clearSyncStartEvent(); 5039 return status; 5040} 5041 5042void AudioFlinger::RecordThread::clearSyncStartEvent() 5043{ 5044 if (mSyncStartEvent != 0) { 5045 mSyncStartEvent->cancel(); 5046 } 5047 mSyncStartEvent.clear(); 5048 mFramestoDrop = 0; 5049} 5050 5051void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event) 5052{ 5053 sp<SyncEvent> strongEvent = event.promote(); 5054 5055 if (strongEvent != 0) { 5056 RecordThread *me = (RecordThread *)strongEvent->cookie(); 5057 me->handleSyncStartEvent(strongEvent); 5058 } 5059} 5060 5061void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event) 5062{ 5063 if (event == mSyncStartEvent) { 5064 // TODO: use actual buffer filling status instead of 2 buffers when info is available 5065 // from audio HAL 5066 mFramestoDrop = mFrameCount * 2; 5067 } 5068} 5069 5070bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) { 5071 ALOGV("RecordThread::stop"); 5072 AutoMutex _l(mLock); 5073 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) { 5074 return false; 5075 } 5076 // note that threadLoop may still be processing the track at this point [without lock] 5077 recordTrack->mState = TrackBase::PAUSING; 5078 // do not wait for mStartStopCond if exiting 5079 if (exitPending()) { 5080 return true; 5081 } 5082 // FIXME incorrect usage of wait: no explicit predicate or loop 5083 mStartStopCond.wait(mLock); 5084 // if we have been restarted, recordTrack is in mActiveTracks here 5085 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) { 5086 ALOGV("Record stopped OK"); 5087 return true; 5088 } 5089 return false; 5090} 5091 5092bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const 5093{ 5094 return false; 5095} 5096 5097status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused) 5098{ 5099#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future 5100 if (!isValidSyncEvent(event)) { 5101 return BAD_VALUE; 5102 } 5103 5104 int eventSession = event->triggerSession(); 5105 status_t ret = NAME_NOT_FOUND; 5106 5107 Mutex::Autolock _l(mLock); 5108 5109 for (size_t i = 0; i < mTracks.size(); i++) { 5110 sp<RecordTrack> track = mTracks[i]; 5111 if (eventSession == track->sessionId()) { 5112 (void) track->setSyncEvent(event); 5113 ret = NO_ERROR; 5114 } 5115 } 5116 return ret; 5117#else 5118 return BAD_VALUE; 5119#endif 5120} 5121 5122// destroyTrack_l() must be called with ThreadBase::mLock held 5123void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track) 5124{ 5125 track->terminate(); 5126 track->mState = TrackBase::STOPPED; 5127 // active tracks are removed by threadLoop() 5128 if (mActiveTracks.indexOf(track) < 0) { 5129 removeTrack_l(track); 5130 } 5131} 5132 5133void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track) 5134{ 5135 mTracks.remove(track); 5136 // need anything related to effects here? 5137} 5138 5139void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args) 5140{ 5141 dumpInternals(fd, args); 5142 dumpTracks(fd, args); 5143 dumpEffectChains(fd, args); 5144} 5145 5146void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args) 5147{ 5148 fdprintf(fd, "\nInput thread %p:\n", this); 5149 5150 if (mActiveTracks.size() > 0) { 5151 fdprintf(fd, " In index: %d\n", mRsmpInIndex); 5152 fdprintf(fd, " Buffer size: %u bytes\n", mBufferSize); 5153 fdprintf(fd, " Resampling: %d\n", (mResampler != NULL)); 5154 fdprintf(fd, " Out channel count: %u\n", mReqChannelCount); 5155 fdprintf(fd, " Out sample rate: %u\n", mReqSampleRate); 5156 } else { 5157 fdprintf(fd, " No active record client\n"); 5158 } 5159 5160 dumpBase(fd, args); 5161} 5162 5163void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused) 5164{ 5165 const size_t SIZE = 256; 5166 char buffer[SIZE]; 5167 String8 result; 5168 5169 size_t numtracks = mTracks.size(); 5170 size_t numactive = mActiveTracks.size(); 5171 size_t numactiveseen = 0; 5172 fdprintf(fd, " %d Tracks", numtracks); 5173 if (numtracks) { 5174 fdprintf(fd, " of which %d are active\n", numactive); 5175 RecordTrack::appendDumpHeader(result); 5176 for (size_t i = 0; i < numtracks ; ++i) { 5177 sp<RecordTrack> track = mTracks[i]; 5178 if (track != 0) { 5179 bool active = mActiveTracks.indexOf(track) >= 0; 5180 if (active) { 5181 numactiveseen++; 5182 } 5183 track->dump(buffer, SIZE, active); 5184 result.append(buffer); 5185 } 5186 } 5187 } else { 5188 fdprintf(fd, "\n"); 5189 } 5190 5191 if (numactiveseen != numactive) { 5192 snprintf(buffer, SIZE, " The following tracks are in the active list but" 5193 " not in the track list\n"); 5194 result.append(buffer); 5195 RecordTrack::appendDumpHeader(result); 5196 for (size_t i = 0; i < numactive; ++i) { 5197 sp<RecordTrack> track = mActiveTracks[i]; 5198 if (mTracks.indexOf(track) < 0) { 5199 track->dump(buffer, SIZE, true); 5200 result.append(buffer); 5201 } 5202 } 5203 5204 } 5205 write(fd, result.string(), result.size()); 5206} 5207 5208// AudioBufferProvider interface 5209status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts __unused) 5210{ 5211 int32_t rear = mRsmpInRear; 5212 int32_t front = mRsmpInFront; 5213 ssize_t filled = rear - front; 5214 ALOG_ASSERT(0 <= filled && (size_t) filled <= mRsmpInFramesP2); 5215 // 'filled' may be non-contiguous, so return only the first contiguous chunk 5216 front &= mRsmpInFramesP2 - 1; 5217 size_t part1 = mRsmpInFramesP2 - front; 5218 if (part1 > (size_t) filled) { 5219 part1 = filled; 5220 } 5221 size_t ask = buffer->frameCount; 5222 ALOG_ASSERT(ask > 0); 5223 if (part1 > ask) { 5224 part1 = ask; 5225 } 5226 if (part1 == 0) { 5227 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty 5228 ALOGE("RecordThread::getNextBuffer() starved"); 5229 buffer->raw = NULL; 5230 buffer->frameCount = 0; 5231 mRsmpInUnrel = 0; 5232 return NOT_ENOUGH_DATA; 5233 } 5234 5235 buffer->raw = mRsmpInBuffer + front * mChannelCount; 5236 buffer->frameCount = part1; 5237 mRsmpInUnrel = part1; 5238 return NO_ERROR; 5239} 5240 5241// AudioBufferProvider interface 5242void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer) 5243{ 5244 size_t stepCount = buffer->frameCount; 5245 if (stepCount == 0) { 5246 return; 5247 } 5248 ALOG_ASSERT(stepCount <= mRsmpInUnrel); 5249 mRsmpInUnrel -= stepCount; 5250 mRsmpInFront += stepCount; 5251 buffer->raw = NULL; 5252 buffer->frameCount = 0; 5253} 5254 5255bool AudioFlinger::RecordThread::checkForNewParameters_l() 5256{ 5257 bool reconfig = false; 5258 5259 while (!mNewParameters.isEmpty()) { 5260 status_t status = NO_ERROR; 5261 String8 keyValuePair = mNewParameters[0]; 5262 AudioParameter param = AudioParameter(keyValuePair); 5263 int value; 5264 audio_format_t reqFormat = mFormat; 5265 uint32_t reqSamplingRate = mReqSampleRate; 5266 audio_channel_mask_t reqChannelMask = audio_channel_in_mask_from_count(mReqChannelCount); 5267 5268 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { 5269 reqSamplingRate = value; 5270 reconfig = true; 5271 } 5272 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { 5273 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) { 5274 status = BAD_VALUE; 5275 } else { 5276 reqFormat = (audio_format_t) value; 5277 reconfig = true; 5278 } 5279 } 5280 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { 5281 audio_channel_mask_t mask = (audio_channel_mask_t) value; 5282 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) { 5283 status = BAD_VALUE; 5284 } else { 5285 reqChannelMask = mask; 5286 reconfig = true; 5287 } 5288 } 5289 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 5290 // do not accept frame count changes if tracks are open as the track buffer 5291 // size depends on frame count and correct behavior would not be guaranteed 5292 // if frame count is changed after track creation 5293 if (mActiveTracks.size() > 0) { 5294 status = INVALID_OPERATION; 5295 } else { 5296 reconfig = true; 5297 } 5298 } 5299 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 5300 // forward device change to effects that have requested to be 5301 // aware of attached audio device. 5302 for (size_t i = 0; i < mEffectChains.size(); i++) { 5303 mEffectChains[i]->setDevice_l(value); 5304 } 5305 5306 // store input device and output device but do not forward output device to audio HAL. 5307 // Note that status is ignored by the caller for output device 5308 // (see AudioFlinger::setParameters() 5309 if (audio_is_output_devices(value)) { 5310 mOutDevice = value; 5311 status = BAD_VALUE; 5312 } else { 5313 mInDevice = value; 5314 // disable AEC and NS if the device is a BT SCO headset supporting those 5315 // pre processings 5316 if (mTracks.size() > 0) { 5317 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 5318 mAudioFlinger->btNrecIsOff(); 5319 for (size_t i = 0; i < mTracks.size(); i++) { 5320 sp<RecordTrack> track = mTracks[i]; 5321 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId()); 5322 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId()); 5323 } 5324 } 5325 } 5326 } 5327 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR && 5328 mAudioSource != (audio_source_t)value) { 5329 // forward device change to effects that have requested to be 5330 // aware of attached audio device. 5331 for (size_t i = 0; i < mEffectChains.size(); i++) { 5332 mEffectChains[i]->setAudioSource_l((audio_source_t)value); 5333 } 5334 mAudioSource = (audio_source_t)value; 5335 } 5336 5337 if (status == NO_ERROR) { 5338 status = mInput->stream->common.set_parameters(&mInput->stream->common, 5339 keyValuePair.string()); 5340 if (status == INVALID_OPERATION) { 5341 inputStandBy(); 5342 status = mInput->stream->common.set_parameters(&mInput->stream->common, 5343 keyValuePair.string()); 5344 } 5345 if (reconfig) { 5346 if (status == BAD_VALUE && 5347 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) && 5348 reqFormat == AUDIO_FORMAT_PCM_16_BIT && 5349 (mInput->stream->common.get_sample_rate(&mInput->stream->common) 5350 <= (2 * reqSamplingRate)) && 5351 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) 5352 <= FCC_2 && 5353 (reqChannelMask == AUDIO_CHANNEL_IN_MONO || 5354 reqChannelMask == AUDIO_CHANNEL_IN_STEREO)) { 5355 status = NO_ERROR; 5356 } 5357 if (status == NO_ERROR) { 5358 readInputParameters(); 5359 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED); 5360 } 5361 } 5362 } 5363 5364 mNewParameters.removeAt(0); 5365 5366 mParamStatus = status; 5367 mParamCond.signal(); 5368 // wait for condition with time out in case the thread calling ThreadBase::setParameters() 5369 // already timed out waiting for the status and will never signal the condition. 5370 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs); 5371 } 5372 return reconfig; 5373} 5374 5375String8 AudioFlinger::RecordThread::getParameters(const String8& keys) 5376{ 5377 Mutex::Autolock _l(mLock); 5378 if (initCheck() != NO_ERROR) { 5379 return String8(); 5380 } 5381 5382 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string()); 5383 const String8 out_s8(s); 5384 free(s); 5385 return out_s8; 5386} 5387 5388void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param __unused) { 5389 AudioSystem::OutputDescriptor desc; 5390 const void *param2 = NULL; 5391 5392 switch (event) { 5393 case AudioSystem::INPUT_OPENED: 5394 case AudioSystem::INPUT_CONFIG_CHANGED: 5395 desc.channelMask = mChannelMask; 5396 desc.samplingRate = mSampleRate; 5397 desc.format = mFormat; 5398 desc.frameCount = mFrameCount; 5399 desc.latency = 0; 5400 param2 = &desc; 5401 break; 5402 5403 case AudioSystem::INPUT_CLOSED: 5404 default: 5405 break; 5406 } 5407 mAudioFlinger->audioConfigChanged_l(event, mId, param2); 5408} 5409 5410void AudioFlinger::RecordThread::readInputParameters() 5411{ 5412 delete[] mRsmpInBuffer; 5413 // mRsmpInBuffer is always assigned a new[] below 5414 delete[] mRsmpOutBuffer; 5415 mRsmpOutBuffer = NULL; 5416 delete mResampler; 5417 mResampler = NULL; 5418 5419 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common); 5420 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common); 5421 mChannelCount = popcount(mChannelMask); 5422 mFormat = mInput->stream->common.get_format(&mInput->stream->common); 5423 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) { 5424 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat); 5425 } 5426 mFrameSize = audio_stream_frame_size(&mInput->stream->common); 5427 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common); 5428 mFrameCount = mBufferSize / mFrameSize; 5429 // With 3 HAL buffers, we can guarantee ability to down-sample the input by ratio of 2:1 to 5430 // 1 full output buffer, regardless of the alignment of the available input. 5431 mRsmpInFrames = mFrameCount * 3; 5432 mRsmpInFramesP2 = roundup(mRsmpInFrames); 5433 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer 5434 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount]; 5435 mRsmpInFront = 0; 5436 mRsmpInRear = 0; 5437 mRsmpInUnrel = 0; 5438 5439 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2) { 5440 mResampler = AudioResampler::create(16, (int) mChannelCount, mReqSampleRate); 5441 mResampler->setSampleRate(mSampleRate); 5442 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN); 5443 // resampler always outputs stereo 5444 mRsmpOutBuffer = new int32_t[mFrameCount * FCC_2]; 5445 } 5446 mRsmpInIndex = mFrameCount; 5447} 5448 5449uint32_t AudioFlinger::RecordThread::getInputFramesLost() 5450{ 5451 Mutex::Autolock _l(mLock); 5452 if (initCheck() != NO_ERROR) { 5453 return 0; 5454 } 5455 5456 return mInput->stream->get_input_frames_lost(mInput->stream); 5457} 5458 5459uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const 5460{ 5461 Mutex::Autolock _l(mLock); 5462 uint32_t result = 0; 5463 if (getEffectChain_l(sessionId) != 0) { 5464 result = EFFECT_SESSION; 5465 } 5466 5467 for (size_t i = 0; i < mTracks.size(); ++i) { 5468 if (sessionId == mTracks[i]->sessionId()) { 5469 result |= TRACK_SESSION; 5470 break; 5471 } 5472 } 5473 5474 return result; 5475} 5476 5477KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const 5478{ 5479 KeyedVector<int, bool> ids; 5480 Mutex::Autolock _l(mLock); 5481 for (size_t j = 0; j < mTracks.size(); ++j) { 5482 sp<RecordThread::RecordTrack> track = mTracks[j]; 5483 int sessionId = track->sessionId(); 5484 if (ids.indexOfKey(sessionId) < 0) { 5485 ids.add(sessionId, true); 5486 } 5487 } 5488 return ids; 5489} 5490 5491AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput() 5492{ 5493 Mutex::Autolock _l(mLock); 5494 AudioStreamIn *input = mInput; 5495 mInput = NULL; 5496 return input; 5497} 5498 5499// this method must always be called either with ThreadBase mLock held or inside the thread loop 5500audio_stream_t* AudioFlinger::RecordThread::stream() const 5501{ 5502 if (mInput == NULL) { 5503 return NULL; 5504 } 5505 return &mInput->stream->common; 5506} 5507 5508status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain) 5509{ 5510 // only one chain per input thread 5511 if (mEffectChains.size() != 0) { 5512 return INVALID_OPERATION; 5513 } 5514 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this); 5515 5516 chain->setInBuffer(NULL); 5517 chain->setOutBuffer(NULL); 5518 5519 checkSuspendOnAddEffectChain_l(chain); 5520 5521 mEffectChains.add(chain); 5522 5523 return NO_ERROR; 5524} 5525 5526size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain) 5527{ 5528 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this); 5529 ALOGW_IF(mEffectChains.size() != 1, 5530 "removeEffectChain_l() %p invalid chain size %d on thread %p", 5531 chain.get(), mEffectChains.size(), this); 5532 if (mEffectChains.size() == 1) { 5533 mEffectChains.removeAt(0); 5534 } 5535 return 0; 5536} 5537 5538}; // namespace android 5539