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