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