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