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