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 <linux/futex.h> 27 #include <sys/stat.h> 28 #include <sys/syscall.h> 29 #include <cutils/properties.h> 30 #include <media/AudioParameter.h> 31 #include <media/AudioResamplerPublic.h> 32 #include <media/RecordBufferConverter.h> 33 #include <media/TypeConverter.h> 34 #include <utils/Log.h> 35 #include <utils/Trace.h> 36 37 #include <private/media/AudioTrackShared.h> 38 #include <private/android_filesystem_config.h> 39 #include <audio_utils/mono_blend.h> 40 #include <audio_utils/primitives.h> 41 #include <audio_utils/format.h> 42 #include <audio_utils/minifloat.h> 43 #include <system/audio_effects/effect_ns.h> 44 #include <system/audio_effects/effect_aec.h> 45 #include <system/audio.h> 46 47 // NBAIO implementations 48 #include <media/nbaio/AudioStreamInSource.h> 49 #include <media/nbaio/AudioStreamOutSink.h> 50 #include <media/nbaio/MonoPipe.h> 51 #include <media/nbaio/MonoPipeReader.h> 52 #include <media/nbaio/Pipe.h> 53 #include <media/nbaio/PipeReader.h> 54 #include <media/nbaio/SourceAudioBufferProvider.h> 55 #include <mediautils/BatteryNotifier.h> 56 57 #include <powermanager/PowerManager.h> 58 59 #include "AudioFlinger.h" 60 #include "FastMixer.h" 61 #include "FastCapture.h" 62 #include "ServiceUtilities.h" 63 #include "mediautils/SchedulingPolicyService.h" 64 65 #ifdef ADD_BATTERY_DATA 66 #include <media/IMediaPlayerService.h> 67 #include <media/IMediaDeathNotifier.h> 68 #endif 69 70 #ifdef DEBUG_CPU_USAGE 71 #include <cpustats/CentralTendencyStatistics.h> 72 #include <cpustats/ThreadCpuUsage.h> 73 #endif 74 75 #include "AutoPark.h" 76 77 #include <pthread.h> 78 #include "TypedLogger.h" 79 80 // ---------------------------------------------------------------------------- 81 82 // Note: the following macro is used for extremely verbose logging message. In 83 // order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to 84 // 0; but one side effect of this is to turn all LOGV's as well. Some messages 85 // are so verbose that we want to suppress them even when we have ALOG_ASSERT 86 // turned on. Do not uncomment the #def below unless you really know what you 87 // are doing and want to see all of the extremely verbose messages. 88 //#define VERY_VERY_VERBOSE_LOGGING 89 #ifdef VERY_VERY_VERBOSE_LOGGING 90 #define ALOGVV ALOGV 91 #else 92 #define ALOGVV(a...) do { } while(0) 93 #endif 94 95 // TODO: Move these macro/inlines to a header file. 96 #define max(a, b) ((a) > (b) ? (a) : (b)) 97 template <typename T> 98 static inline T min(const T& a, const T& b) 99 { 100 return a < b ? a : b; 101 } 102 103 #ifndef ARRAY_SIZE 104 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) 105 #endif 106 107 namespace android { 108 109 // retry counts for buffer fill timeout 110 // 50 * ~20msecs = 1 second 111 static const int8_t kMaxTrackRetries = 50; 112 static const int8_t kMaxTrackStartupRetries = 50; 113 // allow less retry attempts on direct output thread. 114 // direct outputs can be a scarce resource in audio hardware and should 115 // be released as quickly as possible. 116 static const int8_t kMaxTrackRetriesDirect = 2; 117 118 119 120 // don't warn about blocked writes or record buffer overflows more often than this 121 static const nsecs_t kWarningThrottleNs = seconds(5); 122 123 // RecordThread loop sleep time upon application overrun or audio HAL read error 124 static const int kRecordThreadSleepUs = 5000; 125 126 // maximum time to wait in sendConfigEvent_l() for a status to be received 127 static const nsecs_t kConfigEventTimeoutNs = seconds(2); 128 129 // minimum sleep time for the mixer thread loop when tracks are active but in underrun 130 static const uint32_t kMinThreadSleepTimeUs = 5000; 131 // maximum divider applied to the active sleep time in the mixer thread loop 132 static const uint32_t kMaxThreadSleepTimeShift = 2; 133 134 // minimum normal sink buffer size, expressed in milliseconds rather than frames 135 // FIXME This should be based on experimentally observed scheduling jitter 136 static const uint32_t kMinNormalSinkBufferSizeMs = 20; 137 // maximum normal sink buffer size 138 static const uint32_t kMaxNormalSinkBufferSizeMs = 24; 139 140 // minimum capture buffer size in milliseconds to _not_ need a fast capture thread 141 // FIXME This should be based on experimentally observed scheduling jitter 142 static const uint32_t kMinNormalCaptureBufferSizeMs = 12; 143 144 // Offloaded output thread standby delay: allows track transition without going to standby 145 static const nsecs_t kOffloadStandbyDelayNs = seconds(1); 146 147 // Direct output thread minimum sleep time in idle or active(underrun) state 148 static const nsecs_t kDirectMinSleepTimeUs = 10000; 149 150 // The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good 151 // balance between power consumption and latency, and allows threads to be scheduled reliably 152 // by the CFS scheduler. 153 // FIXME Express other hardcoded references to 20ms with references to this constant and move 154 // it appropriately. 155 #define FMS_20 20 156 157 // Whether to use fast mixer 158 static const enum { 159 FastMixer_Never, // never initialize or use: for debugging only 160 FastMixer_Always, // always initialize and use, even if not needed: for debugging only 161 // normal mixer multiplier is 1 162 FastMixer_Static, // initialize if needed, then use all the time if initialized, 163 // multiplier is calculated based on min & max normal mixer buffer size 164 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load, 165 // multiplier is calculated based on min & max normal mixer buffer size 166 // FIXME for FastMixer_Dynamic: 167 // Supporting this option will require fixing HALs that can't handle large writes. 168 // For example, one HAL implementation returns an error from a large write, 169 // and another HAL implementation corrupts memory, possibly in the sample rate converter. 170 // We could either fix the HAL implementations, or provide a wrapper that breaks 171 // up large writes into smaller ones, and the wrapper would need to deal with scheduler. 172 } kUseFastMixer = FastMixer_Static; 173 174 // Whether to use fast capture 175 static const enum { 176 FastCapture_Never, // never initialize or use: for debugging only 177 FastCapture_Always, // always initialize and use, even if not needed: for debugging only 178 FastCapture_Static, // initialize if needed, then use all the time if initialized 179 } kUseFastCapture = FastCapture_Static; 180 181 // Priorities for requestPriority 182 static const int kPriorityAudioApp = 2; 183 static const int kPriorityFastMixer = 3; 184 static const int kPriorityFastCapture = 3; 185 186 // IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the 187 // track buffer in shared memory. Zero on input means to use a default value. For fast tracks, 188 // AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'. 189 190 // This is the default value, if not specified by property. 191 static const int kFastTrackMultiplier = 2; 192 193 // The minimum and maximum allowed values 194 static const int kFastTrackMultiplierMin = 1; 195 static const int kFastTrackMultiplierMax = 2; 196 197 // The actual value to use, which can be specified per-device via property af.fast_track_multiplier. 198 static int sFastTrackMultiplier = kFastTrackMultiplier; 199 200 // See Thread::readOnlyHeap(). 201 // Initially this heap is used to allocate client buffers for "fast" AudioRecord. 202 // Eventually it will be the single buffer that FastCapture writes into via HAL read(), 203 // and that all "fast" AudioRecord clients read from. In either case, the size can be small. 204 static const size_t kRecordThreadReadOnlyHeapSize = 0x2000; 205 206 // ---------------------------------------------------------------------------- 207 208 static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT; 209 210 static void sFastTrackMultiplierInit() 211 { 212 char value[PROPERTY_VALUE_MAX]; 213 if (property_get("af.fast_track_multiplier", value, NULL) > 0) { 214 char *endptr; 215 unsigned long ul = strtoul(value, &endptr, 0); 216 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) { 217 sFastTrackMultiplier = (int) ul; 218 } 219 } 220 } 221 222 // ---------------------------------------------------------------------------- 223 224 #ifdef ADD_BATTERY_DATA 225 // To collect the amplifier usage 226 static void addBatteryData(uint32_t params) { 227 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService(); 228 if (service == NULL) { 229 // it already logged 230 return; 231 } 232 233 service->addBatteryData(params); 234 } 235 #endif 236 237 // Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset 238 struct { 239 // call when you acquire a partial wakelock 240 void acquire(const sp<IBinder> &wakeLockToken) { 241 pthread_mutex_lock(&mLock); 242 if (wakeLockToken.get() == nullptr) { 243 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME); 244 } else { 245 if (mCount == 0) { 246 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME); 247 } 248 ++mCount; 249 } 250 pthread_mutex_unlock(&mLock); 251 } 252 253 // call when you release a partial wakelock. 254 void release(const sp<IBinder> &wakeLockToken) { 255 if (wakeLockToken.get() == nullptr) { 256 return; 257 } 258 pthread_mutex_lock(&mLock); 259 if (--mCount < 0) { 260 ALOGE("negative wakelock count"); 261 mCount = 0; 262 } 263 pthread_mutex_unlock(&mLock); 264 } 265 266 // retrieves the boottime timebase offset from monotonic. 267 int64_t getBoottimeOffset() { 268 pthread_mutex_lock(&mLock); 269 int64_t boottimeOffset = mBoottimeOffset; 270 pthread_mutex_unlock(&mLock); 271 return boottimeOffset; 272 } 273 274 // Adjusts the timebase offset between TIMEBASE_MONOTONIC 275 // and the selected timebase. 276 // Currently only TIMEBASE_BOOTTIME is allowed. 277 // 278 // This only needs to be called upon acquiring the first partial wakelock 279 // after all other partial wakelocks are released. 280 // 281 // We do an empirical measurement of the offset rather than parsing 282 // /proc/timer_list since the latter is not a formal kernel ABI. 283 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) { 284 int clockbase; 285 switch (timebase) { 286 case ExtendedTimestamp::TIMEBASE_BOOTTIME: 287 clockbase = SYSTEM_TIME_BOOTTIME; 288 break; 289 default: 290 LOG_ALWAYS_FATAL("invalid timebase %d", timebase); 291 break; 292 } 293 // try three times to get the clock offset, choose the one 294 // with the minimum gap in measurements. 295 const int tries = 3; 296 nsecs_t bestGap, measured; 297 for (int i = 0; i < tries; ++i) { 298 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC); 299 const nsecs_t tbase = systemTime(clockbase); 300 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC); 301 const nsecs_t gap = tmono2 - tmono; 302 if (i == 0 || gap < bestGap) { 303 bestGap = gap; 304 measured = tbase - ((tmono + tmono2) >> 1); 305 } 306 } 307 308 // to avoid micro-adjusting, we don't change the timebase 309 // unless it is significantly different. 310 // 311 // Assumption: It probably takes more than toleranceNs to 312 // suspend and resume the device. 313 static int64_t toleranceNs = 10000; // 10 us 314 if (llabs(*offset - measured) > toleranceNs) { 315 ALOGV("Adjusting timebase offset old: %lld new: %lld", 316 (long long)*offset, (long long)measured); 317 *offset = measured; 318 } 319 } 320 321 pthread_mutex_t mLock; 322 int32_t mCount; 323 int64_t mBoottimeOffset; 324 } gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization 325 326 // ---------------------------------------------------------------------------- 327 // CPU Stats 328 // ---------------------------------------------------------------------------- 329 330 class CpuStats { 331 public: 332 CpuStats(); 333 void sample(const String8 &title); 334 #ifdef DEBUG_CPU_USAGE 335 private: 336 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns 337 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns 338 339 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles 340 341 int mCpuNum; // thread's current CPU number 342 int mCpukHz; // frequency of thread's current CPU in kHz 343 #endif 344 }; 345 346 CpuStats::CpuStats() 347 #ifdef DEBUG_CPU_USAGE 348 : mCpuNum(-1), mCpukHz(-1) 349 #endif 350 { 351 } 352 353 void CpuStats::sample(const String8 &title 354 #ifndef DEBUG_CPU_USAGE 355 __unused 356 #endif 357 ) { 358 #ifdef DEBUG_CPU_USAGE 359 // get current thread's delta CPU time in wall clock ns 360 double wcNs; 361 bool valid = mCpuUsage.sampleAndEnable(wcNs); 362 363 // record sample for wall clock statistics 364 if (valid) { 365 mWcStats.sample(wcNs); 366 } 367 368 // get the current CPU number 369 int cpuNum = sched_getcpu(); 370 371 // get the current CPU frequency in kHz 372 int cpukHz = mCpuUsage.getCpukHz(cpuNum); 373 374 // check if either CPU number or frequency changed 375 if (cpuNum != mCpuNum || cpukHz != mCpukHz) { 376 mCpuNum = cpuNum; 377 mCpukHz = cpukHz; 378 // ignore sample for purposes of cycles 379 valid = false; 380 } 381 382 // if no change in CPU number or frequency, then record sample for cycle statistics 383 if (valid && mCpukHz > 0) { 384 double cycles = wcNs * cpukHz * 0.000001; 385 mHzStats.sample(cycles); 386 } 387 388 unsigned n = mWcStats.n(); 389 // mCpuUsage.elapsed() is expensive, so don't call it every loop 390 if ((n & 127) == 1) { 391 long long elapsed = mCpuUsage.elapsed(); 392 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) { 393 double perLoop = elapsed / (double) n; 394 double perLoop100 = perLoop * 0.01; 395 double perLoop1k = perLoop * 0.001; 396 double mean = mWcStats.mean(); 397 double stddev = mWcStats.stddev(); 398 double minimum = mWcStats.minimum(); 399 double maximum = mWcStats.maximum(); 400 double meanCycles = mHzStats.mean(); 401 double stddevCycles = mHzStats.stddev(); 402 double minCycles = mHzStats.minimum(); 403 double maxCycles = mHzStats.maximum(); 404 mCpuUsage.resetElapsed(); 405 mWcStats.reset(); 406 mHzStats.reset(); 407 ALOGD("CPU usage for %s over past %.1f secs\n" 408 " (%u mixer loops at %.1f mean ms per loop):\n" 409 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n" 410 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n" 411 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f", 412 title.string(), 413 elapsed * .000000001, n, perLoop * .000001, 414 mean * .001, 415 stddev * .001, 416 minimum * .001, 417 maximum * .001, 418 mean / perLoop100, 419 stddev / perLoop100, 420 minimum / perLoop100, 421 maximum / perLoop100, 422 meanCycles / perLoop1k, 423 stddevCycles / perLoop1k, 424 minCycles / perLoop1k, 425 maxCycles / perLoop1k); 426 427 } 428 } 429 #endif 430 }; 431 432 // ---------------------------------------------------------------------------- 433 // ThreadBase 434 // ---------------------------------------------------------------------------- 435 436 // static 437 const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type) 438 { 439 switch (type) { 440 case MIXER: 441 return "MIXER"; 442 case DIRECT: 443 return "DIRECT"; 444 case DUPLICATING: 445 return "DUPLICATING"; 446 case RECORD: 447 return "RECORD"; 448 case OFFLOAD: 449 return "OFFLOAD"; 450 case MMAP: 451 return "MMAP"; 452 default: 453 return "unknown"; 454 } 455 } 456 457 std::string devicesToString(audio_devices_t devices) 458 { 459 std::string result; 460 if (devices & AUDIO_DEVICE_BIT_IN) { 461 InputDeviceConverter::maskToString(devices, result); 462 } else { 463 OutputDeviceConverter::maskToString(devices, result); 464 } 465 return result; 466 } 467 468 std::string inputFlagsToString(audio_input_flags_t flags) 469 { 470 std::string result; 471 InputFlagConverter::maskToString(flags, result); 472 return result; 473 } 474 475 std::string outputFlagsToString(audio_output_flags_t flags) 476 { 477 std::string result; 478 OutputFlagConverter::maskToString(flags, result); 479 return result; 480 } 481 482 const char *sourceToString(audio_source_t source) 483 { 484 switch (source) { 485 case AUDIO_SOURCE_DEFAULT: return "default"; 486 case AUDIO_SOURCE_MIC: return "mic"; 487 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink"; 488 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink"; 489 case AUDIO_SOURCE_VOICE_CALL: return "voice call"; 490 case AUDIO_SOURCE_CAMCORDER: return "camcorder"; 491 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition"; 492 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication"; 493 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix"; 494 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed"; 495 case AUDIO_SOURCE_FM_TUNER: return "FM tuner"; 496 case AUDIO_SOURCE_HOTWORD: return "hotword"; 497 default: return "unknown"; 498 } 499 } 500 501 AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id, 502 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady) 503 : Thread(false /*canCallJava*/), 504 mType(type), 505 mAudioFlinger(audioFlinger), 506 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize 507 // are set by PlaybackThread::readOutputParameters_l() or 508 // RecordThread::readInputParameters_l() 509 //FIXME: mStandby should be true here. Is this some kind of hack? 510 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice), 511 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE), 512 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id), 513 // mName will be set by concrete (non-virtual) subclass 514 mDeathRecipient(new PMDeathRecipient(this)), 515 mSystemReady(systemReady), 516 mSignalPending(false) 517 { 518 memset(&mPatch, 0, sizeof(struct audio_patch)); 519 } 520 521 AudioFlinger::ThreadBase::~ThreadBase() 522 { 523 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns 524 mConfigEvents.clear(); 525 526 // do not lock the mutex in destructor 527 releaseWakeLock_l(); 528 if (mPowerManager != 0) { 529 sp<IBinder> binder = IInterface::asBinder(mPowerManager); 530 binder->unlinkToDeath(mDeathRecipient); 531 } 532 } 533 534 status_t AudioFlinger::ThreadBase::readyToRun() 535 { 536 status_t status = initCheck(); 537 if (status == NO_ERROR) { 538 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid()); 539 } else { 540 ALOGE("No working audio driver found."); 541 } 542 return status; 543 } 544 545 void AudioFlinger::ThreadBase::exit() 546 { 547 ALOGV("ThreadBase::exit"); 548 // do any cleanup required for exit to succeed 549 preExit(); 550 { 551 // This lock prevents the following race in thread (uniprocessor for illustration): 552 // if (!exitPending()) { 553 // // context switch from here to exit() 554 // // exit() calls requestExit(), what exitPending() observes 555 // // exit() calls signal(), which is dropped since no waiters 556 // // context switch back from exit() to here 557 // mWaitWorkCV.wait(...); 558 // // now thread is hung 559 // } 560 AutoMutex lock(mLock); 561 requestExit(); 562 mWaitWorkCV.broadcast(); 563 } 564 // When Thread::requestExitAndWait is made virtual and this method is renamed to 565 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();" 566 requestExitAndWait(); 567 } 568 569 status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs) 570 { 571 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string()); 572 Mutex::Autolock _l(mLock); 573 574 return sendSetParameterConfigEvent_l(keyValuePairs); 575 } 576 577 // sendConfigEvent_l() must be called with ThreadBase::mLock held 578 // Can temporarily release the lock if waiting for a reply from processConfigEvents_l(). 579 status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event) 580 { 581 status_t status = NO_ERROR; 582 583 if (event->mRequiresSystemReady && !mSystemReady) { 584 event->mWaitStatus = false; 585 mPendingConfigEvents.add(event); 586 return status; 587 } 588 mConfigEvents.add(event); 589 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType); 590 mWaitWorkCV.signal(); 591 mLock.unlock(); 592 { 593 Mutex::Autolock _l(event->mLock); 594 while (event->mWaitStatus) { 595 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) { 596 event->mStatus = TIMED_OUT; 597 event->mWaitStatus = false; 598 } 599 } 600 status = event->mStatus; 601 } 602 mLock.lock(); 603 return status; 604 } 605 606 void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid) 607 { 608 Mutex::Autolock _l(mLock); 609 sendIoConfigEvent_l(event, pid); 610 } 611 612 // sendIoConfigEvent_l() must be called with ThreadBase::mLock held 613 void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid) 614 { 615 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid); 616 sendConfigEvent_l(configEvent); 617 } 618 619 void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp) 620 { 621 Mutex::Autolock _l(mLock); 622 sendPrioConfigEvent_l(pid, tid, prio, forApp); 623 } 624 625 // sendPrioConfigEvent_l() must be called with ThreadBase::mLock held 626 void AudioFlinger::ThreadBase::sendPrioConfigEvent_l( 627 pid_t pid, pid_t tid, int32_t prio, bool forApp) 628 { 629 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp); 630 sendConfigEvent_l(configEvent); 631 } 632 633 // sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held 634 status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair) 635 { 636 sp<ConfigEvent> configEvent; 637 AudioParameter param(keyValuePair); 638 int value; 639 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) { 640 setMasterMono_l(value != 0); 641 if (param.size() == 1) { 642 return NO_ERROR; // should be a solo parameter - we don't pass down 643 } 644 param.remove(String8(AudioParameter::keyMonoOutput)); 645 configEvent = new SetParameterConfigEvent(param.toString()); 646 } else { 647 configEvent = new SetParameterConfigEvent(keyValuePair); 648 } 649 return sendConfigEvent_l(configEvent); 650 } 651 652 status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent( 653 const struct audio_patch *patch, 654 audio_patch_handle_t *handle) 655 { 656 Mutex::Autolock _l(mLock); 657 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle); 658 status_t status = sendConfigEvent_l(configEvent); 659 if (status == NO_ERROR) { 660 CreateAudioPatchConfigEventData *data = 661 (CreateAudioPatchConfigEventData *)configEvent->mData.get(); 662 *handle = data->mHandle; 663 } 664 return status; 665 } 666 667 status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent( 668 const audio_patch_handle_t handle) 669 { 670 Mutex::Autolock _l(mLock); 671 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle); 672 return sendConfigEvent_l(configEvent); 673 } 674 675 676 // post condition: mConfigEvents.isEmpty() 677 void AudioFlinger::ThreadBase::processConfigEvents_l() 678 { 679 bool configChanged = false; 680 681 while (!mConfigEvents.isEmpty()) { 682 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size()); 683 sp<ConfigEvent> event = mConfigEvents[0]; 684 mConfigEvents.removeAt(0); 685 switch (event->mType) { 686 case CFG_EVENT_PRIO: { 687 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get(); 688 // FIXME Need to understand why this has to be done asynchronously 689 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp, 690 true /*asynchronous*/); 691 if (err != 0) { 692 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d", 693 data->mPrio, data->mPid, data->mTid, err); 694 } 695 } break; 696 case CFG_EVENT_IO: { 697 IoConfigEventData *data = (IoConfigEventData *)event->mData.get(); 698 ioConfigChanged(data->mEvent, data->mPid); 699 } break; 700 case CFG_EVENT_SET_PARAMETER: { 701 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get(); 702 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) { 703 configChanged = true; 704 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed", 705 data->mKeyValuePairs.string()); 706 } 707 } break; 708 case CFG_EVENT_CREATE_AUDIO_PATCH: { 709 const audio_devices_t oldDevice = getDevice(); 710 CreateAudioPatchConfigEventData *data = 711 (CreateAudioPatchConfigEventData *)event->mData.get(); 712 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle); 713 const audio_devices_t newDevice = getDevice(); 714 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)", 715 (unsigned)oldDevice, devicesToString(oldDevice).c_str(), 716 (unsigned)newDevice, devicesToString(newDevice).c_str()); 717 } break; 718 case CFG_EVENT_RELEASE_AUDIO_PATCH: { 719 const audio_devices_t oldDevice = getDevice(); 720 ReleaseAudioPatchConfigEventData *data = 721 (ReleaseAudioPatchConfigEventData *)event->mData.get(); 722 event->mStatus = releaseAudioPatch_l(data->mHandle); 723 const audio_devices_t newDevice = getDevice(); 724 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)", 725 (unsigned)oldDevice, devicesToString(oldDevice).c_str(), 726 (unsigned)newDevice, devicesToString(newDevice).c_str()); 727 } break; 728 default: 729 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType); 730 break; 731 } 732 { 733 Mutex::Autolock _l(event->mLock); 734 if (event->mWaitStatus) { 735 event->mWaitStatus = false; 736 event->mCond.signal(); 737 } 738 } 739 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this); 740 } 741 742 if (configChanged) { 743 cacheParameters_l(); 744 } 745 } 746 747 String8 channelMaskToString(audio_channel_mask_t mask, bool output) { 748 String8 s; 749 const audio_channel_representation_t representation = 750 audio_channel_mask_get_representation(mask); 751 752 switch (representation) { 753 case AUDIO_CHANNEL_REPRESENTATION_POSITION: { 754 if (output) { 755 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, "); 756 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, "); 757 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, "); 758 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, "); 759 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, "); 760 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, "); 761 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, "); 762 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, "); 763 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, "); 764 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, "); 765 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, "); 766 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,"); 767 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, "); 768 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, "); 769 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, "); 770 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, "); 771 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " ); 772 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " ); 773 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, "); 774 } else { 775 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, "); 776 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, "); 777 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, "); 778 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, "); 779 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, "); 780 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, "); 781 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, "); 782 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, "); 783 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, "); 784 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, "); 785 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, "); 786 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, "); 787 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, "); 788 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, "); 789 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, "); 790 } 791 const int len = s.length(); 792 if (len > 2) { 793 (void) s.lockBuffer(len); // needed? 794 s.unlockBuffer(len - 2); // remove trailing ", " 795 } 796 return s; 797 } 798 case AUDIO_CHANNEL_REPRESENTATION_INDEX: 799 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask)); 800 return s; 801 default: 802 s.appendFormat("unknown mask, representation:%d bits:%#x", 803 representation, audio_channel_mask_get_bits(mask)); 804 return s; 805 } 806 } 807 808 void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused) 809 { 810 const size_t SIZE = 256; 811 char buffer[SIZE]; 812 String8 result; 813 814 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input", 815 this, mThreadName, getTid(), type(), threadTypeToString(type())); 816 817 bool locked = AudioFlinger::dumpTryLock(mLock); 818 if (!locked) { 819 dprintf(fd, " Thread may be deadlocked\n"); 820 } 821 822 dprintf(fd, " I/O handle: %d\n", mId); 823 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no"); 824 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate); 825 dprintf(fd, " HAL frame count: %zu\n", mFrameCount); 826 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str()); 827 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize); 828 dprintf(fd, " Channel count: %u\n", mChannelCount); 829 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask, 830 channelMaskToString(mChannelMask, mType != RECORD).string()); 831 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str()); 832 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize); 833 dprintf(fd, " Pending config events:"); 834 size_t numConfig = mConfigEvents.size(); 835 if (numConfig) { 836 for (size_t i = 0; i < numConfig; i++) { 837 mConfigEvents[i]->dump(buffer, SIZE); 838 dprintf(fd, "\n %s", buffer); 839 } 840 dprintf(fd, "\n"); 841 } else { 842 dprintf(fd, " none\n"); 843 } 844 // Note: output device may be used by capture threads for effects such as AEC. 845 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str()); 846 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str()); 847 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource)); 848 849 if (locked) { 850 mLock.unlock(); 851 } 852 } 853 854 void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args) 855 { 856 const size_t SIZE = 256; 857 char buffer[SIZE]; 858 String8 result; 859 860 size_t numEffectChains = mEffectChains.size(); 861 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains); 862 write(fd, buffer, strlen(buffer)); 863 864 for (size_t i = 0; i < numEffectChains; ++i) { 865 sp<EffectChain> chain = mEffectChains[i]; 866 if (chain != 0) { 867 chain->dump(fd, args); 868 } 869 } 870 } 871 872 void AudioFlinger::ThreadBase::acquireWakeLock() 873 { 874 Mutex::Autolock _l(mLock); 875 acquireWakeLock_l(); 876 } 877 878 String16 AudioFlinger::ThreadBase::getWakeLockTag() 879 { 880 switch (mType) { 881 case MIXER: 882 return String16("AudioMix"); 883 case DIRECT: 884 return String16("AudioDirectOut"); 885 case DUPLICATING: 886 return String16("AudioDup"); 887 case RECORD: 888 return String16("AudioIn"); 889 case OFFLOAD: 890 return String16("AudioOffload"); 891 case MMAP: 892 return String16("Mmap"); 893 default: 894 ALOG_ASSERT(false); 895 return String16("AudioUnknown"); 896 } 897 } 898 899 void AudioFlinger::ThreadBase::acquireWakeLock_l() 900 { 901 getPowerManager_l(); 902 if (mPowerManager != 0) { 903 sp<IBinder> binder = new BBinder(); 904 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids. 905 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK, 906 binder, 907 getWakeLockTag(), 908 String16("audioserver"), 909 true /* FIXME force oneway contrary to .aidl */); 910 if (status == NO_ERROR) { 911 mWakeLockToken = binder; 912 } 913 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status); 914 } 915 916 gBoottime.acquire(mWakeLockToken); 917 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] = 918 gBoottime.getBoottimeOffset(); 919 } 920 921 void AudioFlinger::ThreadBase::releaseWakeLock() 922 { 923 Mutex::Autolock _l(mLock); 924 releaseWakeLock_l(); 925 } 926 927 void AudioFlinger::ThreadBase::releaseWakeLock_l() 928 { 929 gBoottime.release(mWakeLockToken); 930 if (mWakeLockToken != 0) { 931 ALOGV("releaseWakeLock_l() %s", mThreadName); 932 if (mPowerManager != 0) { 933 mPowerManager->releaseWakeLock(mWakeLockToken, 0, 934 true /* FIXME force oneway contrary to .aidl */); 935 } 936 mWakeLockToken.clear(); 937 } 938 } 939 940 void AudioFlinger::ThreadBase::getPowerManager_l() { 941 if (mSystemReady && mPowerManager == 0) { 942 // use checkService() to avoid blocking if power service is not up yet 943 sp<IBinder> binder = 944 defaultServiceManager()->checkService(String16("power")); 945 if (binder == 0) { 946 ALOGW("Thread %s cannot connect to the power manager service", mThreadName); 947 } else { 948 mPowerManager = interface_cast<IPowerManager>(binder); 949 binder->linkToDeath(mDeathRecipient); 950 } 951 } 952 } 953 954 void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) { 955 getPowerManager_l(); 956 957 #if !LOG_NDEBUG 958 std::stringstream s; 959 for (uid_t uid : uids) { 960 s << uid << " "; 961 } 962 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str()); 963 #endif 964 965 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called. 966 if (mSystemReady) { 967 ALOGE("no wake lock to update, but system ready!"); 968 } else { 969 ALOGW("no wake lock to update, system not ready yet"); 970 } 971 return; 972 } 973 if (mPowerManager != 0) { 974 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints 975 status_t status = mPowerManager->updateWakeLockUids( 976 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(), 977 true /* FIXME force oneway contrary to .aidl */); 978 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status); 979 } 980 } 981 982 void AudioFlinger::ThreadBase::clearPowerManager() 983 { 984 Mutex::Autolock _l(mLock); 985 releaseWakeLock_l(); 986 mPowerManager.clear(); 987 } 988 989 void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused) 990 { 991 sp<ThreadBase> thread = mThread.promote(); 992 if (thread != 0) { 993 thread->clearPowerManager(); 994 } 995 ALOGW("power manager service died !!!"); 996 } 997 998 void AudioFlinger::ThreadBase::setEffectSuspended( 999 const effect_uuid_t *type, bool suspend, audio_session_t sessionId) 1000 { 1001 Mutex::Autolock _l(mLock); 1002 setEffectSuspended_l(type, suspend, sessionId); 1003 } 1004 1005 void AudioFlinger::ThreadBase::setEffectSuspended_l( 1006 const effect_uuid_t *type, bool suspend, audio_session_t sessionId) 1007 { 1008 sp<EffectChain> chain = getEffectChain_l(sessionId); 1009 if (chain != 0) { 1010 if (type != NULL) { 1011 chain->setEffectSuspended_l(type, suspend); 1012 } else { 1013 chain->setEffectSuspendedAll_l(suspend); 1014 } 1015 } 1016 1017 updateSuspendedSessions_l(type, suspend, sessionId); 1018 } 1019 1020 void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain) 1021 { 1022 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId()); 1023 if (index < 0) { 1024 return; 1025 } 1026 1027 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects = 1028 mSuspendedSessions.valueAt(index); 1029 1030 for (size_t i = 0; i < sessionEffects.size(); i++) { 1031 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i); 1032 for (int j = 0; j < desc->mRefCount; j++) { 1033 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) { 1034 chain->setEffectSuspendedAll_l(true); 1035 } else { 1036 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x", 1037 desc->mType.timeLow); 1038 chain->setEffectSuspended_l(&desc->mType, true); 1039 } 1040 } 1041 } 1042 } 1043 1044 void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type, 1045 bool suspend, 1046 audio_session_t sessionId) 1047 { 1048 ssize_t index = mSuspendedSessions.indexOfKey(sessionId); 1049 1050 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects; 1051 1052 if (suspend) { 1053 if (index >= 0) { 1054 sessionEffects = mSuspendedSessions.valueAt(index); 1055 } else { 1056 mSuspendedSessions.add(sessionId, sessionEffects); 1057 } 1058 } else { 1059 if (index < 0) { 1060 return; 1061 } 1062 sessionEffects = mSuspendedSessions.valueAt(index); 1063 } 1064 1065 1066 int key = EffectChain::kKeyForSuspendAll; 1067 if (type != NULL) { 1068 key = type->timeLow; 1069 } 1070 index = sessionEffects.indexOfKey(key); 1071 1072 sp<SuspendedSessionDesc> desc; 1073 if (suspend) { 1074 if (index >= 0) { 1075 desc = sessionEffects.valueAt(index); 1076 } else { 1077 desc = new SuspendedSessionDesc(); 1078 if (type != NULL) { 1079 desc->mType = *type; 1080 } 1081 sessionEffects.add(key, desc); 1082 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key); 1083 } 1084 desc->mRefCount++; 1085 } else { 1086 if (index < 0) { 1087 return; 1088 } 1089 desc = sessionEffects.valueAt(index); 1090 if (--desc->mRefCount == 0) { 1091 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key); 1092 sessionEffects.removeItemsAt(index); 1093 if (sessionEffects.isEmpty()) { 1094 ALOGV("updateSuspendedSessions_l() restore removing session %d", 1095 sessionId); 1096 mSuspendedSessions.removeItem(sessionId); 1097 } 1098 } 1099 } 1100 if (!sessionEffects.isEmpty()) { 1101 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects); 1102 } 1103 } 1104 1105 void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect, 1106 bool enabled, 1107 audio_session_t sessionId) 1108 { 1109 Mutex::Autolock _l(mLock); 1110 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId); 1111 } 1112 1113 void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect, 1114 bool enabled, 1115 audio_session_t sessionId) 1116 { 1117 if (mType != RECORD) { 1118 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on 1119 // another session. This gives the priority to well behaved effect control panels 1120 // and applications not using global effects. 1121 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect 1122 // global effects 1123 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) { 1124 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX); 1125 } 1126 } 1127 1128 sp<EffectChain> chain = getEffectChain_l(sessionId); 1129 if (chain != 0) { 1130 chain->checkSuspendOnEffectEnabled(effect, enabled); 1131 } 1132 } 1133 1134 // checkEffectCompatibility_l() must be called with ThreadBase::mLock held 1135 status_t AudioFlinger::RecordThread::checkEffectCompatibility_l( 1136 const effect_descriptor_t *desc, audio_session_t sessionId) 1137 { 1138 // No global effect sessions on record threads 1139 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) { 1140 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s", 1141 desc->name, mThreadName); 1142 return BAD_VALUE; 1143 } 1144 // only pre processing effects on record thread 1145 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) { 1146 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s", 1147 desc->name, mThreadName); 1148 return BAD_VALUE; 1149 } 1150 1151 // always allow effects without processing load or latency 1152 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) { 1153 return NO_ERROR; 1154 } 1155 1156 audio_input_flags_t flags = mInput->flags; 1157 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) { 1158 if (flags & AUDIO_INPUT_FLAG_RAW) { 1159 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode", 1160 desc->name, mThreadName); 1161 return BAD_VALUE; 1162 } 1163 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) { 1164 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode", 1165 desc->name, mThreadName); 1166 return BAD_VALUE; 1167 } 1168 } 1169 return NO_ERROR; 1170 } 1171 1172 // checkEffectCompatibility_l() must be called with ThreadBase::mLock held 1173 status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l( 1174 const effect_descriptor_t *desc, audio_session_t sessionId) 1175 { 1176 // no preprocessing on playback threads 1177 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) { 1178 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback" 1179 " thread %s", desc->name, mThreadName); 1180 return BAD_VALUE; 1181 } 1182 1183 switch (mType) { 1184 case MIXER: { 1185 // Reject any effect on mixer multichannel sinks. 1186 // TODO: fix both format and multichannel issues with effects. 1187 if (mChannelCount != FCC_2) { 1188 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER" 1189 " thread %s", desc->name, mChannelCount, mThreadName); 1190 return BAD_VALUE; 1191 } 1192 audio_output_flags_t flags = mOutput->flags; 1193 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) { 1194 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) { 1195 // global effects are applied only to non fast tracks if they are SW 1196 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) { 1197 break; 1198 } 1199 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) { 1200 // only post processing on output stage session 1201 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) { 1202 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed" 1203 " on output stage session", desc->name); 1204 return BAD_VALUE; 1205 } 1206 } else { 1207 // no restriction on effects applied on non fast tracks 1208 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) { 1209 break; 1210 } 1211 } 1212 1213 // always allow effects without processing load or latency 1214 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) { 1215 break; 1216 } 1217 if (flags & AUDIO_OUTPUT_FLAG_RAW) { 1218 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode", 1219 desc->name); 1220 return BAD_VALUE; 1221 } 1222 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) { 1223 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread" 1224 " in fast mode", desc->name); 1225 return BAD_VALUE; 1226 } 1227 } 1228 } break; 1229 case OFFLOAD: 1230 // nothing actionable on offload threads, if the effect: 1231 // - is offloadable: the effect can be created 1232 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable() 1233 // will take care of invalidating the tracks of the thread 1234 break; 1235 case DIRECT: 1236 // Reject any effect on Direct output threads for now, since the format of 1237 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo). 1238 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s", 1239 desc->name, mThreadName); 1240 return BAD_VALUE; 1241 case DUPLICATING: 1242 // Reject any effect on mixer multichannel sinks. 1243 // TODO: fix both format and multichannel issues with effects. 1244 if (mChannelCount != FCC_2) { 1245 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)" 1246 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName); 1247 return BAD_VALUE; 1248 } 1249 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) { 1250 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING" 1251 " thread %s", desc->name, mThreadName); 1252 return BAD_VALUE; 1253 } 1254 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) { 1255 ALOGW("checkEffectCompatibility_l(): post processing effect %s on" 1256 " DUPLICATING thread %s", desc->name, mThreadName); 1257 return BAD_VALUE; 1258 } 1259 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) { 1260 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on" 1261 " DUPLICATING thread %s", desc->name, mThreadName); 1262 return BAD_VALUE; 1263 } 1264 break; 1265 default: 1266 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType); 1267 } 1268 1269 return NO_ERROR; 1270 } 1271 1272 // ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held 1273 sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l( 1274 const sp<AudioFlinger::Client>& client, 1275 const sp<IEffectClient>& effectClient, 1276 int32_t priority, 1277 audio_session_t sessionId, 1278 effect_descriptor_t *desc, 1279 int *enabled, 1280 status_t *status, 1281 bool pinned) 1282 { 1283 sp<EffectModule> effect; 1284 sp<EffectHandle> handle; 1285 status_t lStatus; 1286 sp<EffectChain> chain; 1287 bool chainCreated = false; 1288 bool effectCreated = false; 1289 bool effectRegistered = false; 1290 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; 1291 1292 lStatus = initCheck(); 1293 if (lStatus != NO_ERROR) { 1294 ALOGW("createEffect_l() Audio driver not initialized."); 1295 goto Exit; 1296 } 1297 1298 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId); 1299 1300 { // scope for mLock 1301 Mutex::Autolock _l(mLock); 1302 1303 lStatus = checkEffectCompatibility_l(desc, sessionId); 1304 if (lStatus != NO_ERROR) { 1305 goto Exit; 1306 } 1307 1308 // check for existing effect chain with the requested audio session 1309 chain = getEffectChain_l(sessionId); 1310 if (chain == 0) { 1311 // create a new chain for this session 1312 ALOGV("createEffect_l() new effect chain for session %d", sessionId); 1313 chain = new EffectChain(this, sessionId); 1314 addEffectChain_l(chain); 1315 chain->setStrategy(getStrategyForSession_l(sessionId)); 1316 chainCreated = true; 1317 } else { 1318 effect = chain->getEffectFromDesc_l(desc); 1319 } 1320 1321 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get()); 1322 1323 if (effect == 0) { 1324 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT); 1325 // Check CPU and memory usage 1326 lStatus = AudioSystem::registerEffect( 1327 desc, mId, chain->strategy(), sessionId, effectId); 1328 if (lStatus != NO_ERROR) { 1329 goto Exit; 1330 } 1331 effectRegistered = true; 1332 // create a new effect module if none present in the chain 1333 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned); 1334 if (lStatus != NO_ERROR) { 1335 goto Exit; 1336 } 1337 effectCreated = true; 1338 1339 effect->setDevice(mOutDevice); 1340 effect->setDevice(mInDevice); 1341 effect->setMode(mAudioFlinger->getMode()); 1342 effect->setAudioSource(mAudioSource); 1343 } 1344 // create effect handle and connect it to effect module 1345 handle = new EffectHandle(effect, client, effectClient, priority); 1346 lStatus = handle->initCheck(); 1347 if (lStatus == OK) { 1348 lStatus = effect->addHandle(handle.get()); 1349 } 1350 if (enabled != NULL) { 1351 *enabled = (int)effect->isEnabled(); 1352 } 1353 } 1354 1355 Exit: 1356 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) { 1357 Mutex::Autolock _l(mLock); 1358 if (effectCreated) { 1359 chain->removeEffect_l(effect); 1360 } 1361 if (effectRegistered) { 1362 AudioSystem::unregisterEffect(effectId); 1363 } 1364 if (chainCreated) { 1365 removeEffectChain_l(chain); 1366 } 1367 handle.clear(); 1368 } 1369 1370 *status = lStatus; 1371 return handle; 1372 } 1373 1374 void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle, 1375 bool unpinIfLast) 1376 { 1377 bool remove = false; 1378 sp<EffectModule> effect; 1379 { 1380 Mutex::Autolock _l(mLock); 1381 1382 effect = handle->effect().promote(); 1383 if (effect == 0) { 1384 return; 1385 } 1386 // restore suspended effects if the disconnected handle was enabled and the last one. 1387 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast); 1388 if (remove) { 1389 removeEffect_l(effect, true); 1390 } 1391 } 1392 if (remove) { 1393 mAudioFlinger->updateOrphanEffectChains(effect); 1394 AudioSystem::unregisterEffect(effect->id()); 1395 if (handle->enabled()) { 1396 checkSuspendOnEffectEnabled(effect, false, effect->sessionId()); 1397 } 1398 } 1399 } 1400 1401 sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId, 1402 int effectId) 1403 { 1404 Mutex::Autolock _l(mLock); 1405 return getEffect_l(sessionId, effectId); 1406 } 1407 1408 sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId, 1409 int effectId) 1410 { 1411 sp<EffectChain> chain = getEffectChain_l(sessionId); 1412 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0; 1413 } 1414 1415 // PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and 1416 // PlaybackThread::mLock held 1417 status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect) 1418 { 1419 // check for existing effect chain with the requested audio session 1420 audio_session_t sessionId = effect->sessionId(); 1421 sp<EffectChain> chain = getEffectChain_l(sessionId); 1422 bool chainCreated = false; 1423 1424 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(), 1425 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x", 1426 this, effect->desc().name, effect->desc().flags); 1427 1428 if (chain == 0) { 1429 // create a new chain for this session 1430 ALOGV("addEffect_l() new effect chain for session %d", sessionId); 1431 chain = new EffectChain(this, sessionId); 1432 addEffectChain_l(chain); 1433 chain->setStrategy(getStrategyForSession_l(sessionId)); 1434 chainCreated = true; 1435 } 1436 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get()); 1437 1438 if (chain->getEffectFromId_l(effect->id()) != 0) { 1439 ALOGW("addEffect_l() %p effect %s already present in chain %p", 1440 this, effect->desc().name, chain.get()); 1441 return BAD_VALUE; 1442 } 1443 1444 effect->setOffloaded(mType == OFFLOAD, mId); 1445 1446 status_t status = chain->addEffect_l(effect); 1447 if (status != NO_ERROR) { 1448 if (chainCreated) { 1449 removeEffectChain_l(chain); 1450 } 1451 return status; 1452 } 1453 1454 effect->setDevice(mOutDevice); 1455 effect->setDevice(mInDevice); 1456 effect->setMode(mAudioFlinger->getMode()); 1457 effect->setAudioSource(mAudioSource); 1458 return NO_ERROR; 1459 } 1460 1461 void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) { 1462 1463 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get()); 1464 effect_descriptor_t desc = effect->desc(); 1465 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 1466 detachAuxEffect_l(effect->id()); 1467 } 1468 1469 sp<EffectChain> chain = effect->chain().promote(); 1470 if (chain != 0) { 1471 // remove effect chain if removing last effect 1472 if (chain->removeEffect_l(effect, release) == 0) { 1473 removeEffectChain_l(chain); 1474 } 1475 } else { 1476 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get()); 1477 } 1478 } 1479 1480 void AudioFlinger::ThreadBase::lockEffectChains_l( 1481 Vector< sp<AudioFlinger::EffectChain> >& effectChains) 1482 { 1483 effectChains = mEffectChains; 1484 for (size_t i = 0; i < mEffectChains.size(); i++) { 1485 mEffectChains[i]->lock(); 1486 } 1487 } 1488 1489 void AudioFlinger::ThreadBase::unlockEffectChains( 1490 const Vector< sp<AudioFlinger::EffectChain> >& effectChains) 1491 { 1492 for (size_t i = 0; i < effectChains.size(); i++) { 1493 effectChains[i]->unlock(); 1494 } 1495 } 1496 1497 sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId) 1498 { 1499 Mutex::Autolock _l(mLock); 1500 return getEffectChain_l(sessionId); 1501 } 1502 1503 sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId) 1504 const 1505 { 1506 size_t size = mEffectChains.size(); 1507 for (size_t i = 0; i < size; i++) { 1508 if (mEffectChains[i]->sessionId() == sessionId) { 1509 return mEffectChains[i]; 1510 } 1511 } 1512 return 0; 1513 } 1514 1515 void AudioFlinger::ThreadBase::setMode(audio_mode_t mode) 1516 { 1517 Mutex::Autolock _l(mLock); 1518 size_t size = mEffectChains.size(); 1519 for (size_t i = 0; i < size; i++) { 1520 mEffectChains[i]->setMode_l(mode); 1521 } 1522 } 1523 1524 void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config) 1525 { 1526 config->type = AUDIO_PORT_TYPE_MIX; 1527 config->ext.mix.handle = mId; 1528 config->sample_rate = mSampleRate; 1529 config->format = mFormat; 1530 config->channel_mask = mChannelMask; 1531 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK| 1532 AUDIO_PORT_CONFIG_FORMAT; 1533 } 1534 1535 void AudioFlinger::ThreadBase::systemReady() 1536 { 1537 Mutex::Autolock _l(mLock); 1538 if (mSystemReady) { 1539 return; 1540 } 1541 mSystemReady = true; 1542 1543 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) { 1544 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i)); 1545 } 1546 mPendingConfigEvents.clear(); 1547 } 1548 1549 template <typename T> 1550 ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) { 1551 ssize_t index = mActiveTracks.indexOf(track); 1552 if (index >= 0) { 1553 ALOGW("ActiveTracks<T>::add track %p already there", track.get()); 1554 return index; 1555 } 1556 mActiveTracksGeneration++; 1557 mLatestActiveTrack = track; 1558 ++mBatteryCounter[track->uid()].second; 1559 return mActiveTracks.add(track); 1560 } 1561 1562 template <typename T> 1563 ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) { 1564 ssize_t index = mActiveTracks.remove(track); 1565 if (index < 0) { 1566 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get()); 1567 return index; 1568 } 1569 mActiveTracksGeneration++; 1570 --mBatteryCounter[track->uid()].second; 1571 // mLatestActiveTrack is not cleared even if is the same as track. 1572 return index; 1573 } 1574 1575 template <typename T> 1576 void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() { 1577 for (const sp<T> &track : mActiveTracks) { 1578 BatteryNotifier::getInstance().noteStopAudio(track->uid()); 1579 } 1580 mLastActiveTracksGeneration = mActiveTracksGeneration; 1581 mActiveTracks.clear(); 1582 mLatestActiveTrack.clear(); 1583 mBatteryCounter.clear(); 1584 } 1585 1586 template <typename T> 1587 void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState( 1588 sp<ThreadBase> thread, bool force) { 1589 // Updates ActiveTracks client uids to the thread wakelock. 1590 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) { 1591 thread->updateWakeLockUids_l(getWakeLockUids()); 1592 mLastActiveTracksGeneration = mActiveTracksGeneration; 1593 } 1594 1595 // Updates BatteryNotifier uids 1596 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) { 1597 const uid_t uid = it->first; 1598 ssize_t &previous = it->second.first; 1599 ssize_t ¤t = it->second.second; 1600 if (current > 0) { 1601 if (previous == 0) { 1602 BatteryNotifier::getInstance().noteStartAudio(uid); 1603 } 1604 previous = current; 1605 ++it; 1606 } else if (current == 0) { 1607 if (previous > 0) { 1608 BatteryNotifier::getInstance().noteStopAudio(uid); 1609 } 1610 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase. 1611 } else /* (current < 0) */ { 1612 LOG_ALWAYS_FATAL("negative battery count %zd", current); 1613 } 1614 } 1615 } 1616 1617 void AudioFlinger::ThreadBase::broadcast_l() 1618 { 1619 // Thread could be blocked waiting for async 1620 // so signal it to handle state changes immediately 1621 // If threadLoop is currently unlocked a signal of mWaitWorkCV will 1622 // be lost so we also flag to prevent it blocking on mWaitWorkCV 1623 mSignalPending = true; 1624 mWaitWorkCV.broadcast(); 1625 } 1626 1627 // ---------------------------------------------------------------------------- 1628 // Playback 1629 // ---------------------------------------------------------------------------- 1630 1631 AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, 1632 AudioStreamOut* output, 1633 audio_io_handle_t id, 1634 audio_devices_t device, 1635 type_t type, 1636 bool systemReady) 1637 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady), 1638 mNormalFrameCount(0), mSinkBuffer(NULL), 1639 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision), 1640 mMixerBuffer(NULL), 1641 mMixerBufferSize(0), 1642 mMixerBufferFormat(AUDIO_FORMAT_INVALID), 1643 mMixerBufferValid(false), 1644 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision), 1645 mEffectBuffer(NULL), 1646 mEffectBufferSize(0), 1647 mEffectBufferFormat(AUDIO_FORMAT_INVALID), 1648 mEffectBufferValid(false), 1649 mSuspended(0), mBytesWritten(0), 1650 mFramesWritten(0), 1651 mSuspendedFrames(0), 1652 // mStreamTypes[] initialized in constructor body 1653 mOutput(output), 1654 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false), 1655 mMixerStatus(MIXER_IDLE), 1656 mMixerStatusIgnoringFastTracks(MIXER_IDLE), 1657 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs), 1658 mBytesRemaining(0), 1659 mCurrentWriteLength(0), 1660 mUseAsyncWrite(false), 1661 mWriteAckSequence(0), 1662 mDrainSequence(0), 1663 mScreenState(AudioFlinger::mScreenState), 1664 // index 0 is reserved for normal mixer's submix 1665 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1), 1666 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false) 1667 { 1668 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id); 1669 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName); 1670 1671 // Assumes constructor is called by AudioFlinger with it's mLock held, but 1672 // it would be safer to explicitly pass initial masterVolume/masterMute as 1673 // parameter. 1674 // 1675 // If the HAL we are using has support for master volume or master mute, 1676 // then do not attenuate or mute during mixing (just leave the volume at 1.0 1677 // and the mute set to false). 1678 mMasterVolume = audioFlinger->masterVolume_l(); 1679 mMasterMute = audioFlinger->masterMute_l(); 1680 if (mOutput && mOutput->audioHwDev) { 1681 if (mOutput->audioHwDev->canSetMasterVolume()) { 1682 mMasterVolume = 1.0; 1683 } 1684 1685 if (mOutput->audioHwDev->canSetMasterMute()) { 1686 mMasterMute = false; 1687 } 1688 } 1689 1690 readOutputParameters_l(); 1691 1692 // ++ operator does not compile 1693 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT; 1694 stream = (audio_stream_type_t) (stream + 1)) { 1695 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream); 1696 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream); 1697 } 1698 } 1699 1700 AudioFlinger::PlaybackThread::~PlaybackThread() 1701 { 1702 mAudioFlinger->unregisterWriter(mNBLogWriter); 1703 free(mSinkBuffer); 1704 free(mMixerBuffer); 1705 free(mEffectBuffer); 1706 } 1707 1708 void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args) 1709 { 1710 dumpInternals(fd, args); 1711 dumpTracks(fd, args); 1712 dumpEffectChains(fd, args); 1713 dprintf(fd, " Local log:\n"); 1714 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */); 1715 } 1716 1717 void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused) 1718 { 1719 const size_t SIZE = 256; 1720 char buffer[SIZE]; 1721 String8 result; 1722 1723 result.appendFormat(" Stream volumes in dB: "); 1724 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) { 1725 const stream_type_t *st = &mStreamTypes[i]; 1726 if (i > 0) { 1727 result.appendFormat(", "); 1728 } 1729 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume)); 1730 if (st->mute) { 1731 result.append("M"); 1732 } 1733 } 1734 result.append("\n"); 1735 write(fd, result.string(), result.length()); 1736 result.clear(); 1737 1738 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way. 1739 FastTrackUnderruns underruns = getFastTrackUnderruns(0); 1740 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n", 1741 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty); 1742 1743 size_t numtracks = mTracks.size(); 1744 size_t numactive = mActiveTracks.size(); 1745 dprintf(fd, " %zu Tracks", numtracks); 1746 size_t numactiveseen = 0; 1747 if (numtracks) { 1748 dprintf(fd, " of which %zu are active\n", numactive); 1749 Track::appendDumpHeader(result); 1750 for (size_t i = 0; i < numtracks; ++i) { 1751 sp<Track> track = mTracks[i]; 1752 if (track != 0) { 1753 bool active = mActiveTracks.indexOf(track) >= 0; 1754 if (active) { 1755 numactiveseen++; 1756 } 1757 track->dump(buffer, SIZE, active); 1758 result.append(buffer); 1759 } 1760 } 1761 } else { 1762 result.append("\n"); 1763 } 1764 if (numactiveseen != numactive) { 1765 // some tracks in the active list were not in the tracks list 1766 snprintf(buffer, SIZE, " The following tracks are in the active list but" 1767 " not in the track list\n"); 1768 result.append(buffer); 1769 Track::appendDumpHeader(result); 1770 for (size_t i = 0; i < numactive; ++i) { 1771 sp<Track> track = mActiveTracks[i]; 1772 if (mTracks.indexOf(track) < 0) { 1773 track->dump(buffer, SIZE, true); 1774 result.append(buffer); 1775 } 1776 } 1777 } 1778 1779 write(fd, result.string(), result.size()); 1780 } 1781 1782 void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args) 1783 { 1784 dumpBase(fd, args); 1785 1786 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount); 1787 dprintf(fd, " Last write occurred (msecs): %llu\n", 1788 (unsigned long long) ns2ms(systemTime() - mLastWriteTime)); 1789 dprintf(fd, " Total writes: %d\n", mNumWrites); 1790 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites); 1791 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no"); 1792 dprintf(fd, " Suspend count: %d\n", mSuspended); 1793 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer); 1794 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer); 1795 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer); 1796 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask); 1797 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs); 1798 AudioStreamOut *output = mOutput; 1799 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE; 1800 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", 1801 output, flags, outputFlagsToString(flags).c_str()); 1802 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten); 1803 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames); 1804 if (mPipeSink.get() != nullptr) { 1805 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten()); 1806 } 1807 if (output != nullptr) { 1808 dprintf(fd, " Hal stream dump:\n"); 1809 (void)output->stream->dump(fd); 1810 } 1811 } 1812 1813 // Thread virtuals 1814 1815 void AudioFlinger::PlaybackThread::onFirstRef() 1816 { 1817 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO); 1818 } 1819 1820 // ThreadBase virtuals 1821 void AudioFlinger::PlaybackThread::preExit() 1822 { 1823 ALOGV(" preExit()"); 1824 // FIXME this is using hard-coded strings but in the future, this functionality will be 1825 // converted to use audio HAL extensions required to support tunneling 1826 status_t result = mOutput->stream->setParameters(String8("exiting=1")); 1827 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result); 1828 } 1829 1830 // PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held 1831 sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l( 1832 const sp<AudioFlinger::Client>& client, 1833 audio_stream_type_t streamType, 1834 uint32_t sampleRate, 1835 audio_format_t format, 1836 audio_channel_mask_t channelMask, 1837 size_t *pFrameCount, 1838 const sp<IMemory>& sharedBuffer, 1839 audio_session_t sessionId, 1840 audio_output_flags_t *flags, 1841 pid_t tid, 1842 uid_t uid, 1843 status_t *status, 1844 audio_port_handle_t portId) 1845 { 1846 size_t frameCount = *pFrameCount; 1847 sp<Track> track; 1848 status_t lStatus; 1849 audio_output_flags_t outputFlags = mOutput->flags; 1850 1851 // special case for FAST flag considered OK if fast mixer is present 1852 if (hasFastMixer()) { 1853 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST); 1854 } 1855 1856 // Check if requested flags are compatible with output stream flags 1857 if ((*flags & outputFlags) != *flags) { 1858 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)", 1859 *flags, outputFlags); 1860 *flags = (audio_output_flags_t)(*flags & outputFlags); 1861 } 1862 1863 // client expresses a preference for FAST, but we get the final say 1864 if (*flags & AUDIO_OUTPUT_FLAG_FAST) { 1865 if ( 1866 // PCM data 1867 audio_is_linear_pcm(format) && 1868 // TODO: extract as a data library function that checks that a computationally 1869 // expensive downmixer is not required: isFastOutputChannelConversion() 1870 (channelMask == mChannelMask || 1871 mChannelMask != AUDIO_CHANNEL_OUT_STEREO || 1872 (channelMask == AUDIO_CHANNEL_OUT_MONO 1873 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) && 1874 // hardware sample rate 1875 (sampleRate == mSampleRate) && 1876 // normal mixer has an associated fast mixer 1877 hasFastMixer() && 1878 // there are sufficient fast track slots available 1879 (mFastTrackAvailMask != 0) 1880 // FIXME test that MixerThread for this fast track has a capable output HAL 1881 // FIXME add a permission test also? 1882 ) { 1883 // static tracks can have any nonzero framecount, streaming tracks check against minimum. 1884 if (sharedBuffer == 0) { 1885 // read the fast track multiplier property the first time it is needed 1886 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit); 1887 if (ok != 0) { 1888 ALOGE("%s pthread_once failed: %d", __func__, ok); 1889 } 1890 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0 1891 } 1892 1893 // check compatibility with audio effects. 1894 { // scope for mLock 1895 Mutex::Autolock _l(mLock); 1896 for (audio_session_t session : { 1897 AUDIO_SESSION_OUTPUT_STAGE, 1898 AUDIO_SESSION_OUTPUT_MIX, 1899 sessionId, 1900 }) { 1901 sp<EffectChain> chain = getEffectChain_l(session); 1902 if (chain.get() != nullptr) { 1903 audio_output_flags_t old = *flags; 1904 chain->checkOutputFlagCompatibility(flags); 1905 if (old != *flags) { 1906 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x", 1907 (int)session, (int)old, (int)*flags); 1908 } 1909 } 1910 } 1911 } 1912 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0, 1913 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu", 1914 frameCount, mFrameCount); 1915 } else { 1916 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu " 1917 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x " 1918 "sampleRate=%u mSampleRate=%u " 1919 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x", 1920 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat, 1921 audio_is_linear_pcm(format), 1922 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask); 1923 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST); 1924 } 1925 } 1926 // For normal PCM streaming tracks, update minimum frame count. 1927 // For compatibility with AudioTrack calculation, buffer depth is forced 1928 // to be at least 2 x the normal mixer frame count and cover audio hardware latency. 1929 // This is probably too conservative, but legacy application code may depend on it. 1930 // If you change this calculation, also review the start threshold which is related. 1931 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST) 1932 && audio_has_proportional_frames(format) && sharedBuffer == 0) { 1933 // this must match AudioTrack.cpp calculateMinFrameCount(). 1934 // TODO: Move to a common library 1935 uint32_t latencyMs = 0; 1936 lStatus = mOutput->stream->getLatency(&latencyMs); 1937 if (lStatus != OK) { 1938 ALOGE("Error when retrieving output stream latency: %d", lStatus); 1939 goto Exit; 1940 } 1941 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate); 1942 if (minBufCount < 2) { 1943 minBufCount = 2; 1944 } 1945 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack 1946 // or the client should compute and pass in a larger buffer request. 1947 size_t minFrameCount = 1948 minBufCount * sourceFramesNeededWithTimestretch( 1949 sampleRate, mNormalFrameCount, 1950 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/); 1951 if (frameCount < minFrameCount) { // including frameCount == 0 1952 frameCount = minFrameCount; 1953 } 1954 } 1955 *pFrameCount = frameCount; 1956 1957 switch (mType) { 1958 1959 case DIRECT: 1960 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()? 1961 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) { 1962 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x " 1963 "for output %p with format %#x", 1964 sampleRate, format, channelMask, mOutput, mFormat); 1965 lStatus = BAD_VALUE; 1966 goto Exit; 1967 } 1968 } 1969 break; 1970 1971 case OFFLOAD: 1972 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) { 1973 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \"" 1974 "for output %p with format %#x", 1975 sampleRate, format, channelMask, mOutput, mFormat); 1976 lStatus = BAD_VALUE; 1977 goto Exit; 1978 } 1979 break; 1980 1981 default: 1982 if (!audio_is_linear_pcm(format)) { 1983 ALOGE("createTrack_l() Bad parameter: format %#x \"" 1984 "for output %p with format %#x", 1985 format, mOutput, mFormat); 1986 lStatus = BAD_VALUE; 1987 goto Exit; 1988 } 1989 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) { 1990 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate); 1991 lStatus = BAD_VALUE; 1992 goto Exit; 1993 } 1994 break; 1995 1996 } 1997 1998 lStatus = initCheck(); 1999 if (lStatus != NO_ERROR) { 2000 ALOGE("createTrack_l() audio driver not initialized"); 2001 goto Exit; 2002 } 2003 2004 { // scope for mLock 2005 Mutex::Autolock _l(mLock); 2006 2007 // all tracks in same audio session must share the same routing strategy otherwise 2008 // conflicts will happen when tracks are moved from one output to another by audio policy 2009 // manager 2010 uint32_t strategy = AudioSystem::getStrategyForStream(streamType); 2011 for (size_t i = 0; i < mTracks.size(); ++i) { 2012 sp<Track> t = mTracks[i]; 2013 if (t != 0 && t->isExternalTrack()) { 2014 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType()); 2015 if (sessionId == t->sessionId() && strategy != actual) { 2016 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u", 2017 strategy, actual); 2018 lStatus = BAD_VALUE; 2019 goto Exit; 2020 } 2021 } 2022 } 2023 2024 track = new Track(this, client, streamType, sampleRate, format, 2025 channelMask, frameCount, NULL, sharedBuffer, 2026 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId); 2027 2028 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY; 2029 if (lStatus != NO_ERROR) { 2030 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus); 2031 // track must be cleared from the caller as the caller has the AF lock 2032 goto Exit; 2033 } 2034 mTracks.add(track); 2035 2036 sp<EffectChain> chain = getEffectChain_l(sessionId); 2037 if (chain != 0) { 2038 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer()); 2039 track->setMainBuffer(chain->inBuffer()); 2040 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType())); 2041 chain->incTrackCnt(); 2042 } 2043 2044 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) { 2045 pid_t callingPid = IPCThreadState::self()->getCallingPid(); 2046 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful, 2047 // so ask activity manager to do this on our behalf 2048 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*isForApp*/); 2049 } 2050 } 2051 2052 lStatus = NO_ERROR; 2053 2054 Exit: 2055 *status = lStatus; 2056 return track; 2057 } 2058 2059 uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const 2060 { 2061 return latency; 2062 } 2063 2064 uint32_t AudioFlinger::PlaybackThread::latency() const 2065 { 2066 Mutex::Autolock _l(mLock); 2067 return latency_l(); 2068 } 2069 uint32_t AudioFlinger::PlaybackThread::latency_l() const 2070 { 2071 uint32_t latency; 2072 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) { 2073 return correctLatency_l(latency); 2074 } 2075 return 0; 2076 } 2077 2078 void AudioFlinger::PlaybackThread::setMasterVolume(float value) 2079 { 2080 Mutex::Autolock _l(mLock); 2081 // Don't apply master volume in SW if our HAL can do it for us. 2082 if (mOutput && mOutput->audioHwDev && 2083 mOutput->audioHwDev->canSetMasterVolume()) { 2084 mMasterVolume = 1.0; 2085 } else { 2086 mMasterVolume = value; 2087 } 2088 } 2089 2090 void AudioFlinger::PlaybackThread::setMasterMute(bool muted) 2091 { 2092 if (isDuplicating()) { 2093 return; 2094 } 2095 Mutex::Autolock _l(mLock); 2096 // Don't apply master mute in SW if our HAL can do it for us. 2097 if (mOutput && mOutput->audioHwDev && 2098 mOutput->audioHwDev->canSetMasterMute()) { 2099 mMasterMute = false; 2100 } else { 2101 mMasterMute = muted; 2102 } 2103 } 2104 2105 void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value) 2106 { 2107 Mutex::Autolock _l(mLock); 2108 mStreamTypes[stream].volume = value; 2109 broadcast_l(); 2110 } 2111 2112 void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted) 2113 { 2114 Mutex::Autolock _l(mLock); 2115 mStreamTypes[stream].mute = muted; 2116 broadcast_l(); 2117 } 2118 2119 float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const 2120 { 2121 Mutex::Autolock _l(mLock); 2122 return mStreamTypes[stream].volume; 2123 } 2124 2125 // addTrack_l() must be called with ThreadBase::mLock held 2126 status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track) 2127 { 2128 status_t status = ALREADY_EXISTS; 2129 2130 if (mActiveTracks.indexOf(track) < 0) { 2131 // the track is newly added, make sure it fills up all its 2132 // buffers before playing. This is to ensure the client will 2133 // effectively get the latency it requested. 2134 if (track->isExternalTrack()) { 2135 TrackBase::track_state state = track->mState; 2136 mLock.unlock(); 2137 status = AudioSystem::startOutput(mId, track->streamType(), 2138 track->sessionId()); 2139 mLock.lock(); 2140 // abort track was stopped/paused while we released the lock 2141 if (state != track->mState) { 2142 if (status == NO_ERROR) { 2143 mLock.unlock(); 2144 AudioSystem::stopOutput(mId, track->streamType(), 2145 track->sessionId()); 2146 mLock.lock(); 2147 } 2148 return INVALID_OPERATION; 2149 } 2150 // abort if start is rejected by audio policy manager 2151 if (status != NO_ERROR) { 2152 return PERMISSION_DENIED; 2153 } 2154 #ifdef ADD_BATTERY_DATA 2155 // to track the speaker usage 2156 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart); 2157 #endif 2158 } 2159 2160 // set retry count for buffer fill 2161 if (track->isOffloaded()) { 2162 if (track->isStopping_1()) { 2163 track->mRetryCount = kMaxTrackStopRetriesOffload; 2164 } else { 2165 track->mRetryCount = kMaxTrackStartupRetriesOffload; 2166 } 2167 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED; 2168 } else { 2169 track->mRetryCount = kMaxTrackStartupRetries; 2170 track->mFillingUpStatus = 2171 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING; 2172 } 2173 2174 track->mResetDone = false; 2175 track->mPresentationCompleteFrames = 0; 2176 mActiveTracks.add(track); 2177 sp<EffectChain> chain = getEffectChain_l(track->sessionId()); 2178 if (chain != 0) { 2179 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), 2180 track->sessionId()); 2181 chain->incActiveTrackCnt(); 2182 } 2183 2184 char buffer[256]; 2185 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */); 2186 mLocalLog.log("addTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis 2187 2188 status = NO_ERROR; 2189 } 2190 2191 onAddNewTrack_l(); 2192 return status; 2193 } 2194 2195 bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track) 2196 { 2197 track->terminate(); 2198 // active tracks are removed by threadLoop() 2199 bool trackActive = (mActiveTracks.indexOf(track) >= 0); 2200 track->mState = TrackBase::STOPPED; 2201 if (!trackActive) { 2202 removeTrack_l(track); 2203 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) { 2204 track->mState = TrackBase::STOPPING_1; 2205 } 2206 2207 return trackActive; 2208 } 2209 2210 void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track) 2211 { 2212 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE); 2213 2214 char buffer[256]; 2215 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */); 2216 mLocalLog.log("removeTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis 2217 2218 mTracks.remove(track); 2219 deleteTrackName_l(track->name()); 2220 // redundant as track is about to be destroyed, for dumpsys only 2221 track->mName = -1; 2222 if (track->isFastTrack()) { 2223 int index = track->mFastIndex; 2224 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks); 2225 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index))); 2226 mFastTrackAvailMask |= 1 << index; 2227 // redundant as track is about to be destroyed, for dumpsys only 2228 track->mFastIndex = -1; 2229 } 2230 sp<EffectChain> chain = getEffectChain_l(track->sessionId()); 2231 if (chain != 0) { 2232 chain->decTrackCnt(); 2233 } 2234 } 2235 2236 String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys) 2237 { 2238 Mutex::Autolock _l(mLock); 2239 String8 out_s8; 2240 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) { 2241 return out_s8; 2242 } 2243 return String8(); 2244 } 2245 2246 void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) { 2247 sp<AudioIoDescriptor> desc = new AudioIoDescriptor(); 2248 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event); 2249 2250 desc->mIoHandle = mId; 2251 2252 switch (event) { 2253 case AUDIO_OUTPUT_OPENED: 2254 case AUDIO_OUTPUT_CONFIG_CHANGED: 2255 desc->mPatch = mPatch; 2256 desc->mChannelMask = mChannelMask; 2257 desc->mSamplingRate = mSampleRate; 2258 desc->mFormat = mFormat; 2259 desc->mFrameCount = mNormalFrameCount; // FIXME see 2260 // AudioFlinger::frameCount(audio_io_handle_t) 2261 desc->mFrameCountHAL = mFrameCount; 2262 desc->mLatency = latency_l(); 2263 break; 2264 2265 case AUDIO_OUTPUT_CLOSED: 2266 default: 2267 break; 2268 } 2269 mAudioFlinger->ioConfigChanged(event, desc, pid); 2270 } 2271 2272 void AudioFlinger::PlaybackThread::onWriteReady() 2273 { 2274 mCallbackThread->resetWriteBlocked(); 2275 } 2276 2277 void AudioFlinger::PlaybackThread::onDrainReady() 2278 { 2279 mCallbackThread->resetDraining(); 2280 } 2281 2282 void AudioFlinger::PlaybackThread::onError() 2283 { 2284 mCallbackThread->setAsyncError(); 2285 } 2286 2287 void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence) 2288 { 2289 Mutex::Autolock _l(mLock); 2290 // reject out of sequence requests 2291 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) { 2292 mWriteAckSequence &= ~1; 2293 mWaitWorkCV.signal(); 2294 } 2295 } 2296 2297 void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence) 2298 { 2299 Mutex::Autolock _l(mLock); 2300 // reject out of sequence requests 2301 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) { 2302 mDrainSequence &= ~1; 2303 mWaitWorkCV.signal(); 2304 } 2305 } 2306 2307 void AudioFlinger::PlaybackThread::readOutputParameters_l() 2308 { 2309 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL 2310 mSampleRate = mOutput->getSampleRate(); 2311 mChannelMask = mOutput->getChannelMask(); 2312 if (!audio_is_output_channel(mChannelMask)) { 2313 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask); 2314 } 2315 if ((mType == MIXER || mType == DUPLICATING) 2316 && !isValidPcmSinkChannelMask(mChannelMask)) { 2317 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output", 2318 mChannelMask); 2319 } 2320 mChannelCount = audio_channel_count_from_out_mask(mChannelMask); 2321 2322 // Get actual HAL format. 2323 status_t result = mOutput->stream->getFormat(&mHALFormat); 2324 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result); 2325 // Get format from the shim, which will be different than the HAL format 2326 // if playing compressed audio over HDMI passthrough. 2327 mFormat = mOutput->getFormat(); 2328 if (!audio_is_valid_format(mFormat)) { 2329 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat); 2330 } 2331 if ((mType == MIXER || mType == DUPLICATING) 2332 && !isValidPcmSinkFormat(mFormat)) { 2333 LOG_FATAL("HAL format %#x not supported for mixed output", 2334 mFormat); 2335 } 2336 mFrameSize = mOutput->getFrameSize(); 2337 result = mOutput->stream->getBufferSize(&mBufferSize); 2338 LOG_ALWAYS_FATAL_IF(result != OK, 2339 "Error when retrieving output stream buffer size: %d", result); 2340 mFrameCount = mBufferSize / mFrameSize; 2341 if (mFrameCount & 15) { 2342 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames", 2343 mFrameCount); 2344 } 2345 2346 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) { 2347 if (mOutput->stream->setCallback(this) == OK) { 2348 mUseAsyncWrite = true; 2349 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this); 2350 } 2351 } 2352 2353 mHwSupportsPause = false; 2354 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) { 2355 bool supportsPause = false, supportsResume = false; 2356 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) { 2357 if (supportsPause && supportsResume) { 2358 mHwSupportsPause = true; 2359 } else if (supportsPause) { 2360 ALOGW("direct output implements pause but not resume"); 2361 } else if (supportsResume) { 2362 ALOGW("direct output implements resume but not pause"); 2363 } 2364 } 2365 } 2366 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) { 2367 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume"); 2368 } 2369 2370 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) { 2371 // For best precision, we use float instead of the associated output 2372 // device format (typically PCM 16 bit). 2373 2374 mFormat = AUDIO_FORMAT_PCM_FLOAT; 2375 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat); 2376 mBufferSize = mFrameSize * mFrameCount; 2377 2378 // TODO: We currently use the associated output device channel mask and sample rate. 2379 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads 2380 // (if a valid mask) to avoid premature downmix. 2381 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads 2382 // instead of the output device sample rate to avoid loss of high frequency information. 2383 // This may need to be updated as MixerThread/OutputTracks are added and not here. 2384 } 2385 2386 // Calculate size of normal sink buffer relative to the HAL output buffer size 2387 double multiplier = 1.0; 2388 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || 2389 kUseFastMixer == FastMixer_Dynamic)) { 2390 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000; 2391 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000; 2392 2393 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer 2394 minNormalFrameCount = (minNormalFrameCount + 15) & ~15; 2395 maxNormalFrameCount = maxNormalFrameCount & ~15; 2396 if (maxNormalFrameCount < minNormalFrameCount) { 2397 maxNormalFrameCount = minNormalFrameCount; 2398 } 2399 multiplier = (double) minNormalFrameCount / (double) mFrameCount; 2400 if (multiplier <= 1.0) { 2401 multiplier = 1.0; 2402 } else if (multiplier <= 2.0) { 2403 if (2 * mFrameCount <= maxNormalFrameCount) { 2404 multiplier = 2.0; 2405 } else { 2406 multiplier = (double) maxNormalFrameCount / (double) mFrameCount; 2407 } 2408 } else { 2409 multiplier = floor(multiplier); 2410 } 2411 } 2412 mNormalFrameCount = multiplier * mFrameCount; 2413 // round up to nearest 16 frames to satisfy AudioMixer 2414 if (mType == MIXER || mType == DUPLICATING) { 2415 mNormalFrameCount = (mNormalFrameCount + 15) & ~15; 2416 } 2417 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount, 2418 mNormalFrameCount); 2419 2420 // Check if we want to throttle the processing to no more than 2x normal rate 2421 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */); 2422 mThreadThrottleTimeMs = 0; 2423 mThreadThrottleEndMs = 0; 2424 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate); 2425 2426 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames. 2427 // Originally this was int16_t[] array, need to remove legacy implications. 2428 free(mSinkBuffer); 2429 mSinkBuffer = NULL; 2430 // For sink buffer size, we use the frame size from the downstream sink to avoid problems 2431 // with non PCM formats for compressed music, e.g. AAC, and Offload threads. 2432 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize; 2433 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize); 2434 2435 // We resize the mMixerBuffer according to the requirements of the sink buffer which 2436 // drives the output. 2437 free(mMixerBuffer); 2438 mMixerBuffer = NULL; 2439 if (mMixerBufferEnabled) { 2440 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT. 2441 mMixerBufferSize = mNormalFrameCount * mChannelCount 2442 * audio_bytes_per_sample(mMixerBufferFormat); 2443 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize); 2444 } 2445 free(mEffectBuffer); 2446 mEffectBuffer = NULL; 2447 if (mEffectBufferEnabled) { 2448 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only 2449 mEffectBufferSize = mNormalFrameCount * mChannelCount 2450 * audio_bytes_per_sample(mEffectBufferFormat); 2451 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize); 2452 } 2453 2454 // force reconfiguration of effect chains and engines to take new buffer size and audio 2455 // parameters into account 2456 // Note that mLock is not held when readOutputParameters_l() is called from the constructor 2457 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't 2458 // matter. 2459 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains 2460 Vector< sp<EffectChain> > effectChains = mEffectChains; 2461 for (size_t i = 0; i < effectChains.size(); i ++) { 2462 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false); 2463 } 2464 } 2465 2466 2467 status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames) 2468 { 2469 if (halFrames == NULL || dspFrames == NULL) { 2470 return BAD_VALUE; 2471 } 2472 Mutex::Autolock _l(mLock); 2473 if (initCheck() != NO_ERROR) { 2474 return INVALID_OPERATION; 2475 } 2476 int64_t framesWritten = mBytesWritten / mFrameSize; 2477 *halFrames = framesWritten; 2478 2479 if (isSuspended()) { 2480 // return an estimation of rendered frames when the output is suspended 2481 size_t latencyFrames = (latency_l() * mSampleRate) / 1000; 2482 *dspFrames = (uint32_t) 2483 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0); 2484 return NO_ERROR; 2485 } else { 2486 status_t status; 2487 uint32_t frames; 2488 status = mOutput->getRenderPosition(&frames); 2489 *dspFrames = (size_t)frames; 2490 return status; 2491 } 2492 } 2493 2494 // hasAudioSession_l() must be called with ThreadBase::mLock held 2495 uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const 2496 { 2497 uint32_t result = 0; 2498 if (getEffectChain_l(sessionId) != 0) { 2499 result = EFFECT_SESSION; 2500 } 2501 2502 for (size_t i = 0; i < mTracks.size(); ++i) { 2503 sp<Track> track = mTracks[i]; 2504 if (sessionId == track->sessionId() && !track->isInvalid()) { 2505 result |= TRACK_SESSION; 2506 if (track->isFastTrack()) { 2507 result |= FAST_SESSION; 2508 } 2509 break; 2510 } 2511 } 2512 2513 return result; 2514 } 2515 2516 uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) 2517 { 2518 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that 2519 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected 2520 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) { 2521 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); 2522 } 2523 for (size_t i = 0; i < mTracks.size(); i++) { 2524 sp<Track> track = mTracks[i]; 2525 if (sessionId == track->sessionId() && !track->isInvalid()) { 2526 return AudioSystem::getStrategyForStream(track->streamType()); 2527 } 2528 } 2529 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); 2530 } 2531 2532 2533 AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const 2534 { 2535 Mutex::Autolock _l(mLock); 2536 return mOutput; 2537 } 2538 2539 AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput() 2540 { 2541 Mutex::Autolock _l(mLock); 2542 AudioStreamOut *output = mOutput; 2543 mOutput = NULL; 2544 // FIXME FastMixer might also have a raw ptr to mOutputSink; 2545 // must push a NULL and wait for ack 2546 mOutputSink.clear(); 2547 mPipeSink.clear(); 2548 mNormalSink.clear(); 2549 return output; 2550 } 2551 2552 // this method must always be called either with ThreadBase mLock held or inside the thread loop 2553 sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const 2554 { 2555 if (mOutput == NULL) { 2556 return NULL; 2557 } 2558 return mOutput->stream; 2559 } 2560 2561 uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const 2562 { 2563 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000); 2564 } 2565 2566 status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event) 2567 { 2568 if (!isValidSyncEvent(event)) { 2569 return BAD_VALUE; 2570 } 2571 2572 Mutex::Autolock _l(mLock); 2573 2574 for (size_t i = 0; i < mTracks.size(); ++i) { 2575 sp<Track> track = mTracks[i]; 2576 if (event->triggerSession() == track->sessionId()) { 2577 (void) track->setSyncEvent(event); 2578 return NO_ERROR; 2579 } 2580 } 2581 2582 return NAME_NOT_FOUND; 2583 } 2584 2585 bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const 2586 { 2587 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE; 2588 } 2589 2590 void AudioFlinger::PlaybackThread::threadLoop_removeTracks( 2591 const Vector< sp<Track> >& tracksToRemove) 2592 { 2593 size_t count = tracksToRemove.size(); 2594 if (count > 0) { 2595 for (size_t i = 0 ; i < count ; i++) { 2596 const sp<Track>& track = tracksToRemove.itemAt(i); 2597 if (track->isExternalTrack()) { 2598 AudioSystem::stopOutput(mId, track->streamType(), 2599 track->sessionId()); 2600 #ifdef ADD_BATTERY_DATA 2601 // to track the speaker usage 2602 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop); 2603 #endif 2604 if (track->isTerminated()) { 2605 AudioSystem::releaseOutput(mId, track->streamType(), 2606 track->sessionId()); 2607 } 2608 } 2609 } 2610 } 2611 } 2612 2613 void AudioFlinger::PlaybackThread::checkSilentMode_l() 2614 { 2615 if (!mMasterMute) { 2616 char value[PROPERTY_VALUE_MAX]; 2617 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) { 2618 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX"); 2619 return; 2620 } 2621 if (property_get("ro.audio.silent", value, "0") > 0) { 2622 char *endptr; 2623 unsigned long ul = strtoul(value, &endptr, 0); 2624 if (*endptr == '\0' && ul != 0) { 2625 ALOGD("Silence is golden"); 2626 // The setprop command will not allow a property to be changed after 2627 // the first time it is set, so we don't have to worry about un-muting. 2628 setMasterMute_l(true); 2629 } 2630 } 2631 } 2632 } 2633 2634 // shared by MIXER and DIRECT, overridden by DUPLICATING 2635 ssize_t AudioFlinger::PlaybackThread::threadLoop_write() 2636 { 2637 mInWrite = true; 2638 ssize_t bytesWritten; 2639 const size_t offset = mCurrentWriteLength - mBytesRemaining; 2640 2641 // If an NBAIO sink is present, use it to write the normal mixer's submix 2642 if (mNormalSink != 0) { 2643 2644 const size_t count = mBytesRemaining / mFrameSize; 2645 2646 ATRACE_BEGIN("write"); 2647 // update the setpoint when AudioFlinger::mScreenState changes 2648 uint32_t screenState = AudioFlinger::mScreenState; 2649 if (screenState != mScreenState) { 2650 mScreenState = screenState; 2651 MonoPipe *pipe = (MonoPipe *)mPipeSink.get(); 2652 if (pipe != NULL) { 2653 pipe->setAvgFrames((mScreenState & 1) ? 2654 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2); 2655 } 2656 } 2657 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count); 2658 ATRACE_END(); 2659 if (framesWritten > 0) { 2660 bytesWritten = framesWritten * mFrameSize; 2661 } else { 2662 bytesWritten = framesWritten; 2663 } 2664 // otherwise use the HAL / AudioStreamOut directly 2665 } else { 2666 // Direct output and offload threads 2667 2668 if (mUseAsyncWrite) { 2669 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request"); 2670 mWriteAckSequence += 2; 2671 mWriteAckSequence |= 1; 2672 ALOG_ASSERT(mCallbackThread != 0); 2673 mCallbackThread->setWriteBlocked(mWriteAckSequence); 2674 } 2675 // FIXME We should have an implementation of timestamps for direct output threads. 2676 // They are used e.g for multichannel PCM playback over HDMI. 2677 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining); 2678 2679 if (mUseAsyncWrite && 2680 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) { 2681 // do not wait for async callback in case of error of full write 2682 mWriteAckSequence &= ~1; 2683 ALOG_ASSERT(mCallbackThread != 0); 2684 mCallbackThread->setWriteBlocked(mWriteAckSequence); 2685 } 2686 } 2687 2688 mNumWrites++; 2689 mInWrite = false; 2690 mStandby = false; 2691 return bytesWritten; 2692 } 2693 2694 void AudioFlinger::PlaybackThread::threadLoop_drain() 2695 { 2696 bool supportsDrain = false; 2697 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) { 2698 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full"); 2699 if (mUseAsyncWrite) { 2700 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request"); 2701 mDrainSequence |= 1; 2702 ALOG_ASSERT(mCallbackThread != 0); 2703 mCallbackThread->setDraining(mDrainSequence); 2704 } 2705 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK); 2706 ALOGE_IF(result != OK, "Error when draining stream: %d", result); 2707 } 2708 } 2709 2710 void AudioFlinger::PlaybackThread::threadLoop_exit() 2711 { 2712 { 2713 Mutex::Autolock _l(mLock); 2714 for (size_t i = 0; i < mTracks.size(); i++) { 2715 sp<Track> track = mTracks[i]; 2716 track->invalidate(); 2717 } 2718 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain. 2719 // After we exit there are no more track changes sent to BatteryNotifier 2720 // because that requires an active threadLoop. 2721 // TODO: should we decActiveTrackCnt() of the cleared track effect chain? 2722 mActiveTracks.clear(); 2723 } 2724 } 2725 2726 /* 2727 The derived values that are cached: 2728 - mSinkBufferSize from frame count * frame size 2729 - mActiveSleepTimeUs from activeSleepTimeUs() 2730 - mIdleSleepTimeUs from idleSleepTimeUs() 2731 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least 2732 kDefaultStandbyTimeInNsecs when connected to an A2DP device. 2733 - maxPeriod from frame count and sample rate (MIXER only) 2734 2735 The parameters that affect these derived values are: 2736 - frame count 2737 - frame size 2738 - sample rate 2739 - device type: A2DP or not 2740 - device latency 2741 - format: PCM or not 2742 - active sleep time 2743 - idle sleep time 2744 */ 2745 2746 void AudioFlinger::PlaybackThread::cacheParameters_l() 2747 { 2748 mSinkBufferSize = mNormalFrameCount * mFrameSize; 2749 mActiveSleepTimeUs = activeSleepTimeUs(); 2750 mIdleSleepTimeUs = idleSleepTimeUs(); 2751 2752 // make sure standby delay is not too short when connected to an A2DP sink to avoid 2753 // truncating audio when going to standby. 2754 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs; 2755 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) { 2756 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) { 2757 mStandbyDelayNs = kDefaultStandbyTimeInNsecs; 2758 } 2759 } 2760 } 2761 2762 bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType) 2763 { 2764 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu", 2765 this, streamType, mTracks.size()); 2766 bool trackMatch = false; 2767 size_t size = mTracks.size(); 2768 for (size_t i = 0; i < size; i++) { 2769 sp<Track> t = mTracks[i]; 2770 if (t->streamType() == streamType && t->isExternalTrack()) { 2771 t->invalidate(); 2772 trackMatch = true; 2773 } 2774 } 2775 return trackMatch; 2776 } 2777 2778 void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType) 2779 { 2780 Mutex::Autolock _l(mLock); 2781 invalidateTracks_l(streamType); 2782 } 2783 2784 status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain) 2785 { 2786 audio_session_t session = chain->sessionId(); 2787 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer; 2788 status_t result = EffectBufferHalInterface::mirror( 2789 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer, 2790 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize, 2791 &halInBuffer); 2792 if (result != OK) return result; 2793 halOutBuffer = halInBuffer; 2794 int16_t *buffer = reinterpret_cast<int16_t*>(halInBuffer->externalData()); 2795 2796 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session); 2797 if (session > AUDIO_SESSION_OUTPUT_MIX) { 2798 // Only one effect chain can be present in direct output thread and it uses 2799 // the sink buffer as input 2800 if (mType != DIRECT) { 2801 size_t numSamples = mNormalFrameCount * mChannelCount; 2802 status_t result = EffectBufferHalInterface::allocate( 2803 numSamples * sizeof(int16_t), 2804 &halInBuffer); 2805 if (result != OK) return result; 2806 buffer = halInBuffer->audioBuffer()->s16; 2807 ALOGV("addEffectChain_l() creating new input buffer %p session %d", 2808 buffer, session); 2809 } 2810 2811 // Attach all tracks with same session ID to this chain. 2812 for (size_t i = 0; i < mTracks.size(); ++i) { 2813 sp<Track> track = mTracks[i]; 2814 if (session == track->sessionId()) { 2815 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), 2816 buffer); 2817 track->setMainBuffer(buffer); 2818 chain->incTrackCnt(); 2819 } 2820 } 2821 2822 // indicate all active tracks in the chain 2823 for (const sp<Track> &track : mActiveTracks) { 2824 if (session == track->sessionId()) { 2825 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session); 2826 chain->incActiveTrackCnt(); 2827 } 2828 } 2829 } 2830 chain->setThread(this); 2831 chain->setInBuffer(halInBuffer); 2832 chain->setOutBuffer(halOutBuffer); 2833 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect 2834 // chains list in order to be processed last as it contains output stage effects. 2835 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before 2836 // session AUDIO_SESSION_OUTPUT_STAGE to be processed 2837 // after track specific effects and before output stage. 2838 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and 2839 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX. 2840 // Effect chain for other sessions are inserted at beginning of effect 2841 // chains list to be processed before output mix effects. Relative order between other 2842 // sessions is not important. 2843 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 && 2844 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX, 2845 "audio_session_t constants misdefined"); 2846 size_t size = mEffectChains.size(); 2847 size_t i = 0; 2848 for (i = 0; i < size; i++) { 2849 if (mEffectChains[i]->sessionId() < session) { 2850 break; 2851 } 2852 } 2853 mEffectChains.insertAt(chain, i); 2854 checkSuspendOnAddEffectChain_l(chain); 2855 2856 return NO_ERROR; 2857 } 2858 2859 size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain) 2860 { 2861 audio_session_t session = chain->sessionId(); 2862 2863 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session); 2864 2865 for (size_t i = 0; i < mEffectChains.size(); i++) { 2866 if (chain == mEffectChains[i]) { 2867 mEffectChains.removeAt(i); 2868 // detach all active tracks from the chain 2869 for (const sp<Track> &track : mActiveTracks) { 2870 if (session == track->sessionId()) { 2871 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d", 2872 chain.get(), session); 2873 chain->decActiveTrackCnt(); 2874 } 2875 } 2876 2877 // detach all tracks with same session ID from this chain 2878 for (size_t i = 0; i < mTracks.size(); ++i) { 2879 sp<Track> track = mTracks[i]; 2880 if (session == track->sessionId()) { 2881 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer)); 2882 chain->decTrackCnt(); 2883 } 2884 } 2885 break; 2886 } 2887 } 2888 return mEffectChains.size(); 2889 } 2890 2891 status_t AudioFlinger::PlaybackThread::attachAuxEffect( 2892 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId) 2893 { 2894 Mutex::Autolock _l(mLock); 2895 return attachAuxEffect_l(track, EffectId); 2896 } 2897 2898 status_t AudioFlinger::PlaybackThread::attachAuxEffect_l( 2899 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId) 2900 { 2901 status_t status = NO_ERROR; 2902 2903 if (EffectId == 0) { 2904 track->setAuxBuffer(0, NULL); 2905 } else { 2906 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX 2907 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId); 2908 if (effect != 0) { 2909 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 2910 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer()); 2911 } else { 2912 status = INVALID_OPERATION; 2913 } 2914 } else { 2915 status = BAD_VALUE; 2916 } 2917 } 2918 return status; 2919 } 2920 2921 void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId) 2922 { 2923 for (size_t i = 0; i < mTracks.size(); ++i) { 2924 sp<Track> track = mTracks[i]; 2925 if (track->auxEffectId() == effectId) { 2926 attachAuxEffect_l(track, 0); 2927 } 2928 } 2929 } 2930 2931 bool AudioFlinger::PlaybackThread::threadLoop() 2932 { 2933 logWriterTLS = mNBLogWriter.get(); 2934 2935 Vector< sp<Track> > tracksToRemove; 2936 2937 mStandbyTimeNs = systemTime(); 2938 nsecs_t lastWriteFinished = -1; // time last server write completed 2939 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written 2940 2941 // MIXER 2942 nsecs_t lastWarning = 0; 2943 2944 // DUPLICATING 2945 // FIXME could this be made local to while loop? 2946 writeFrames = 0; 2947 2948 cacheParameters_l(); 2949 mSleepTimeUs = mIdleSleepTimeUs; 2950 2951 if (mType == MIXER) { 2952 sleepTimeShift = 0; 2953 } 2954 2955 CpuStats cpuStats; 2956 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid())); 2957 2958 acquireWakeLock(); 2959 2960 // mNBLogWriter->log can only be called while thread mutex mLock is held. 2961 // So if you need to log when mutex is unlocked, set logString to a non-NULL string, 2962 // and then that string will be logged at the next convenient opportunity. 2963 const char *logString = NULL; 2964 2965 // Estimated time for next buffer to be written to hal. This is used only on 2966 // suspended mode (for now) to help schedule the wait time until next iteration. 2967 nsecs_t timeLoopNextNs = 0; 2968 2969 checkSilentMode_l(); 2970 #if 0 2971 int z = 0; // used in logFormat example 2972 #endif 2973 while (!exitPending()) 2974 { 2975 // Log merge requests are performed during AudioFlinger binder transactions, but 2976 // that does not cover audio playback. It's requested here for that reason. 2977 mAudioFlinger->requestLogMerge(); 2978 2979 cpuStats.sample(myName); 2980 2981 Vector< sp<EffectChain> > effectChains; 2982 2983 { // scope for mLock 2984 2985 Mutex::Autolock _l(mLock); 2986 2987 processConfigEvents_l(); 2988 2989 if (logString != NULL) { 2990 mNBLogWriter->logTimestamp(); 2991 mNBLogWriter->log(logString); 2992 logString = NULL; 2993 } 2994 2995 // Gather the framesReleased counters for all active tracks, 2996 // and associate with the sink frames written out. We need 2997 // this to convert the sink timestamp to the track timestamp. 2998 bool kernelLocationUpdate = false; 2999 if (mNormalSink != 0) { 3000 // Note: The DuplicatingThread may not have a mNormalSink. 3001 // We always fetch the timestamp here because often the downstream 3002 // sink will block while writing. 3003 ExtendedTimestamp timestamp; // use private copy to fetch 3004 (void) mNormalSink->getTimestamp(timestamp); 3005 3006 // We keep track of the last valid kernel position in case we are in underrun 3007 // and the normal mixer period is the same as the fast mixer period, or there 3008 // is some error from the HAL. 3009 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) { 3010 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] = 3011 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]; 3012 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] = 3013 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]; 3014 3015 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] = 3016 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER]; 3017 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] = 3018 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER]; 3019 } 3020 3021 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) { 3022 kernelLocationUpdate = true; 3023 } else { 3024 ALOGVV("getTimestamp error - no valid kernel position"); 3025 } 3026 3027 // copy over kernel info 3028 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = 3029 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] 3030 + mSuspendedFrames; // add frames discarded when suspended 3031 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = 3032 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]; 3033 } 3034 // mFramesWritten for non-offloaded tracks are contiguous 3035 // even after standby() is called. This is useful for the track frame 3036 // to sink frame mapping. 3037 bool serverLocationUpdate = false; 3038 if (mFramesWritten != lastFramesWritten) { 3039 serverLocationUpdate = true; 3040 lastFramesWritten = mFramesWritten; 3041 } 3042 // Only update timestamps if there is a meaningful change. 3043 // Either the kernel timestamp must be valid or we have written something. 3044 if (kernelLocationUpdate || serverLocationUpdate) { 3045 if (serverLocationUpdate) { 3046 // use the time before we called the HAL write - it is a bit more accurate 3047 // to when the server last read data than the current time here. 3048 // 3049 // If we haven't written anything, mLastWriteTime will be -1 3050 // and we use systemTime(). 3051 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten; 3052 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1 3053 ? systemTime() : mLastWriteTime; 3054 } 3055 3056 for (const sp<Track> &t : mActiveTracks) { 3057 if (!t->isFastTrack()) { 3058 t->updateTrackFrameInfo( 3059 t->mAudioTrackServerProxy->framesReleased(), 3060 mFramesWritten, 3061 mTimestamp); 3062 } 3063 } 3064 } 3065 #if 0 3066 // logFormat example 3067 if (z % 100 == 0) { 3068 timespec ts; 3069 clock_gettime(CLOCK_MONOTONIC, &ts); 3070 LOGT("This is an integer %d, this is a float %f, this is my " 3071 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts); 3072 LOGT("A deceptive null-terminated string %\0"); 3073 } 3074 ++z; 3075 #endif 3076 saveOutputTracks(); 3077 if (mSignalPending) { 3078 // A signal was raised while we were unlocked 3079 mSignalPending = false; 3080 } else if (waitingAsyncCallback_l()) { 3081 if (exitPending()) { 3082 break; 3083 } 3084 bool released = false; 3085 if (!keepWakeLock()) { 3086 releaseWakeLock_l(); 3087 released = true; 3088 } 3089 3090 const int64_t waitNs = computeWaitTimeNs_l(); 3091 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs); 3092 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs); 3093 if (status == TIMED_OUT) { 3094 mSignalPending = true; // if timeout recheck everything 3095 } 3096 ALOGV("async completion/wake"); 3097 if (released) { 3098 acquireWakeLock_l(); 3099 } 3100 mStandbyTimeNs = systemTime() + mStandbyDelayNs; 3101 mSleepTimeUs = 0; 3102 3103 continue; 3104 } 3105 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) || 3106 isSuspended()) { 3107 // put audio hardware into standby after short delay 3108 if (shouldStandby_l()) { 3109 3110 threadLoop_standby(); 3111 3112 mStandby = true; 3113 } 3114 3115 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) { 3116 // we're about to wait, flush the binder command buffer 3117 IPCThreadState::self()->flushCommands(); 3118 3119 clearOutputTracks(); 3120 3121 if (exitPending()) { 3122 break; 3123 } 3124 3125 releaseWakeLock_l(); 3126 // wait until we have something to do... 3127 ALOGV("%s going to sleep", myName.string()); 3128 mWaitWorkCV.wait(mLock); 3129 ALOGV("%s waking up", myName.string()); 3130 acquireWakeLock_l(); 3131 3132 mMixerStatus = MIXER_IDLE; 3133 mMixerStatusIgnoringFastTracks = MIXER_IDLE; 3134 mBytesWritten = 0; 3135 mBytesRemaining = 0; 3136 checkSilentMode_l(); 3137 3138 mStandbyTimeNs = systemTime() + mStandbyDelayNs; 3139 mSleepTimeUs = mIdleSleepTimeUs; 3140 if (mType == MIXER) { 3141 sleepTimeShift = 0; 3142 } 3143 3144 continue; 3145 } 3146 } 3147 // mMixerStatusIgnoringFastTracks is also updated internally 3148 mMixerStatus = prepareTracks_l(&tracksToRemove); 3149 3150 mActiveTracks.updatePowerState(this); 3151 3152 // prevent any changes in effect chain list and in each effect chain 3153 // during mixing and effect process as the audio buffers could be deleted 3154 // or modified if an effect is created or deleted 3155 lockEffectChains_l(effectChains); 3156 } // mLock scope ends 3157 3158 if (mBytesRemaining == 0) { 3159 mCurrentWriteLength = 0; 3160 if (mMixerStatus == MIXER_TRACKS_READY) { 3161 // threadLoop_mix() sets mCurrentWriteLength 3162 threadLoop_mix(); 3163 } else if ((mMixerStatus != MIXER_DRAIN_TRACK) 3164 && (mMixerStatus != MIXER_DRAIN_ALL)) { 3165 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data 3166 // must be written to HAL 3167 threadLoop_sleepTime(); 3168 if (mSleepTimeUs == 0) { 3169 mCurrentWriteLength = mSinkBufferSize; 3170 } 3171 } 3172 // Either threadLoop_mix() or threadLoop_sleepTime() should have set 3173 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0. 3174 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid) 3175 // or mSinkBuffer (if there are no effects). 3176 // 3177 // This is done pre-effects computation; if effects change to 3178 // support higher precision, this needs to move. 3179 // 3180 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l(). 3181 // TODO use mSleepTimeUs == 0 as an additional condition. 3182 if (mMixerBufferValid) { 3183 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer; 3184 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat; 3185 3186 // mono blend occurs for mixer threads only (not direct or offloaded) 3187 // and is handled here if we're going directly to the sink. 3188 if (requireMonoBlend() && !mEffectBufferValid) { 3189 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount, 3190 true /*limit*/); 3191 } 3192 3193 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat, 3194 mNormalFrameCount * mChannelCount); 3195 } 3196 3197 mBytesRemaining = mCurrentWriteLength; 3198 if (isSuspended()) { 3199 // Simulate write to HAL when suspended (e.g. BT SCO phone call). 3200 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer. 3201 const size_t framesRemaining = mBytesRemaining / mFrameSize; 3202 mBytesWritten += mBytesRemaining; 3203 mFramesWritten += framesRemaining; 3204 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position 3205 mBytesRemaining = 0; 3206 } 3207 3208 // only process effects if we're going to write 3209 if (mSleepTimeUs == 0 && mType != OFFLOAD) { 3210 for (size_t i = 0; i < effectChains.size(); i ++) { 3211 effectChains[i]->process_l(); 3212 } 3213 } 3214 } 3215 // Process effect chains for offloaded thread even if no audio 3216 // was read from audio track: process only updates effect state 3217 // and thus does have to be synchronized with audio writes but may have 3218 // to be called while waiting for async write callback 3219 if (mType == OFFLOAD) { 3220 for (size_t i = 0; i < effectChains.size(); i ++) { 3221 effectChains[i]->process_l(); 3222 } 3223 } 3224 3225 // Only if the Effects buffer is enabled and there is data in the 3226 // Effects buffer (buffer valid), we need to 3227 // copy into the sink buffer. 3228 // TODO use mSleepTimeUs == 0 as an additional condition. 3229 if (mEffectBufferValid) { 3230 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat); 3231 3232 if (requireMonoBlend()) { 3233 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount, 3234 true /*limit*/); 3235 } 3236 3237 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat, 3238 mNormalFrameCount * mChannelCount); 3239 } 3240 3241 // enable changes in effect chain 3242 unlockEffectChains(effectChains); 3243 3244 if (!waitingAsyncCallback()) { 3245 // mSleepTimeUs == 0 means we must write to audio hardware 3246 if (mSleepTimeUs == 0) { 3247 ssize_t ret = 0; 3248 // We save lastWriteFinished here, as previousLastWriteFinished, 3249 // for throttling. On thread start, previousLastWriteFinished will be 3250 // set to -1, which properly results in no throttling after the first write. 3251 nsecs_t previousLastWriteFinished = lastWriteFinished; 3252 nsecs_t delta = 0; 3253 if (mBytesRemaining) { 3254 // FIXME rewrite to reduce number of system calls 3255 mLastWriteTime = systemTime(); // also used for dumpsys 3256 ret = threadLoop_write(); 3257 lastWriteFinished = systemTime(); 3258 delta = lastWriteFinished - mLastWriteTime; 3259 if (ret < 0) { 3260 mBytesRemaining = 0; 3261 } else { 3262 mBytesWritten += ret; 3263 mBytesRemaining -= ret; 3264 mFramesWritten += ret / mFrameSize; 3265 } 3266 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) || 3267 (mMixerStatus == MIXER_DRAIN_ALL)) { 3268 threadLoop_drain(); 3269 } 3270 if (mType == MIXER && !mStandby) { 3271 // write blocked detection 3272 if (delta > maxPeriod) { 3273 mNumDelayedWrites++; 3274 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) { 3275 ATRACE_NAME("underrun"); 3276 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p", 3277 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this); 3278 lastWarning = lastWriteFinished; 3279 } 3280 } 3281 3282 if (mThreadThrottle 3283 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks) 3284 && ret > 0) { // we wrote something 3285 // Limit MixerThread data processing to no more than twice the 3286 // expected processing rate. 3287 // 3288 // This helps prevent underruns with NuPlayer and other applications 3289 // which may set up buffers that are close to the minimum size, or use 3290 // deep buffers, and rely on a double-buffering sleep strategy to fill. 3291 // 3292 // The throttle smooths out sudden large data drains from the device, 3293 // e.g. when it comes out of standby, which often causes problems with 3294 // (1) mixer threads without a fast mixer (which has its own warm-up) 3295 // (2) minimum buffer sized tracks (even if the track is full, 3296 // the app won't fill fast enough to handle the sudden draw). 3297 // 3298 // Total time spent in last processing cycle equals time spent in 3299 // 1. threadLoop_write, as well as time spent in 3300 // 2. threadLoop_mix (significant for heavy mixing, especially 3301 // on low tier processors) 3302 3303 // it's OK if deltaMs is an overestimate. 3304 const int32_t deltaMs = 3305 (lastWriteFinished - previousLastWriteFinished) / 1000000; 3306 const int32_t throttleMs = mHalfBufferMs - deltaMs; 3307 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) { 3308 usleep(throttleMs * 1000); 3309 // notify of throttle start on verbose log 3310 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs, 3311 "mixer(%p) throttle begin:" 3312 " ret(%zd) deltaMs(%d) requires sleep %d ms", 3313 this, ret, deltaMs, throttleMs); 3314 mThreadThrottleTimeMs += throttleMs; 3315 // Throttle must be attributed to the previous mixer loop's write time 3316 // to allow back-to-back throttling. 3317 lastWriteFinished += throttleMs * 1000000; 3318 } else { 3319 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs; 3320 if (diff > 0) { 3321 // notify of throttle end on debug log 3322 // but prevent spamming for bluetooth 3323 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()), 3324 "mixer(%p) throttle end: throttle time(%u)", this, diff); 3325 mThreadThrottleEndMs = mThreadThrottleTimeMs; 3326 } 3327 } 3328 } 3329 } 3330 3331 } else { 3332 ATRACE_BEGIN("sleep"); 3333 Mutex::Autolock _l(mLock); 3334 // suspended requires accurate metering of sleep time. 3335 if (isSuspended()) { 3336 // advance by expected sleepTime 3337 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs); 3338 const nsecs_t nowNs = systemTime(); 3339 3340 // compute expected next time vs current time. 3341 // (negative deltas are treated as delays). 3342 nsecs_t deltaNs = timeLoopNextNs - nowNs; 3343 if (deltaNs < -kMaxNextBufferDelayNs) { 3344 // Delays longer than the max allowed trigger a reset. 3345 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs); 3346 deltaNs = microseconds((nsecs_t)mSleepTimeUs); 3347 timeLoopNextNs = nowNs + deltaNs; 3348 } else if (deltaNs < 0) { 3349 // Delays within the max delay allowed: zero the delta/sleepTime 3350 // to help the system catch up in the next iteration(s) 3351 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs); 3352 deltaNs = 0; 3353 } 3354 // update sleep time (which is >= 0) 3355 mSleepTimeUs = deltaNs / 1000; 3356 } 3357 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) { 3358 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs)); 3359 } 3360 ATRACE_END(); 3361 } 3362 } 3363 3364 // Finally let go of removed track(s), without the lock held 3365 // since we can't guarantee the destructors won't acquire that 3366 // same lock. This will also mutate and push a new fast mixer state. 3367 threadLoop_removeTracks(tracksToRemove); 3368 tracksToRemove.clear(); 3369 3370 // FIXME I don't understand the need for this here; 3371 // it was in the original code but maybe the 3372 // assignment in saveOutputTracks() makes this unnecessary? 3373 clearOutputTracks(); 3374 3375 // Effect chains will be actually deleted here if they were removed from 3376 // mEffectChains list during mixing or effects processing 3377 effectChains.clear(); 3378 3379 // FIXME Note that the above .clear() is no longer necessary since effectChains 3380 // is now local to this block, but will keep it for now (at least until merge done). 3381 } 3382 3383 threadLoop_exit(); 3384 3385 if (!mStandby) { 3386 threadLoop_standby(); 3387 mStandby = true; 3388 } 3389 3390 releaseWakeLock(); 3391 3392 ALOGV("Thread %p type %d exiting", this, mType); 3393 return false; 3394 } 3395 3396 // removeTracks_l() must be called with ThreadBase::mLock held 3397 void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove) 3398 { 3399 size_t count = tracksToRemove.size(); 3400 if (count > 0) { 3401 for (size_t i=0 ; i<count ; i++) { 3402 const sp<Track>& track = tracksToRemove.itemAt(i); 3403 mActiveTracks.remove(track); 3404 ALOGV("removeTracks_l removing track on session %d", track->sessionId()); 3405 sp<EffectChain> chain = getEffectChain_l(track->sessionId()); 3406 if (chain != 0) { 3407 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), 3408 track->sessionId()); 3409 chain->decActiveTrackCnt(); 3410 } 3411 if (track->isTerminated()) { 3412 removeTrack_l(track); 3413 } else { // inactive but not terminated 3414 char buffer[256]; 3415 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */); 3416 mLocalLog.log("removeTracks_l(%p) %s", track.get(), buffer + 4); 3417 } 3418 } 3419 } 3420 3421 } 3422 3423 status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp) 3424 { 3425 if (mNormalSink != 0) { 3426 ExtendedTimestamp ets; 3427 status_t status = mNormalSink->getTimestamp(ets); 3428 if (status == NO_ERROR) { 3429 status = ets.getBestTimestamp(×tamp); 3430 } 3431 return status; 3432 } 3433 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) { 3434 uint64_t position64; 3435 if (mOutput->getPresentationPosition(&position64, ×tamp.mTime) == OK) { 3436 timestamp.mPosition = (uint32_t)position64; 3437 return NO_ERROR; 3438 } 3439 } 3440 return INVALID_OPERATION; 3441 } 3442 3443 status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch, 3444 audio_patch_handle_t *handle) 3445 { 3446 status_t status; 3447 if (property_get_bool("af.patch_park", false /* default_value */)) { 3448 // Park FastMixer to avoid potential DOS issues with writing to the HAL 3449 // or if HAL does not properly lock against access. 3450 AutoPark<FastMixer> park(mFastMixer); 3451 status = PlaybackThread::createAudioPatch_l(patch, handle); 3452 } else { 3453 status = PlaybackThread::createAudioPatch_l(patch, handle); 3454 } 3455 return status; 3456 } 3457 3458 status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch, 3459 audio_patch_handle_t *handle) 3460 { 3461 status_t status = NO_ERROR; 3462 3463 // store new device and send to effects 3464 audio_devices_t type = AUDIO_DEVICE_NONE; 3465 for (unsigned int i = 0; i < patch->num_sinks; i++) { 3466 type |= patch->sinks[i].ext.device.type; 3467 } 3468 3469 #ifdef ADD_BATTERY_DATA 3470 // when changing the audio output device, call addBatteryData to notify 3471 // the change 3472 if (mOutDevice != type) { 3473 uint32_t params = 0; 3474 // check whether speaker is on 3475 if (type & AUDIO_DEVICE_OUT_SPEAKER) { 3476 params |= IMediaPlayerService::kBatteryDataSpeakerOn; 3477 } 3478 3479 audio_devices_t deviceWithoutSpeaker 3480 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER; 3481 // check if any other device (except speaker) is on 3482 if (type & deviceWithoutSpeaker) { 3483 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn; 3484 } 3485 3486 if (params != 0) { 3487 addBatteryData(params); 3488 } 3489 } 3490 #endif 3491 3492 for (size_t i = 0; i < mEffectChains.size(); i++) { 3493 mEffectChains[i]->setDevice_l(type); 3494 } 3495 3496 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when 3497 // the thread is created so that the first patch creation triggers an ioConfigChanged callback 3498 bool configChanged = mPrevOutDevice != type; 3499 mOutDevice = type; 3500 mPatch = *patch; 3501 3502 if (mOutput->audioHwDev->supportsAudioPatches()) { 3503 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice(); 3504 status = hwDevice->createAudioPatch(patch->num_sources, 3505 patch->sources, 3506 patch->num_sinks, 3507 patch->sinks, 3508 handle); 3509 } else { 3510 char *address; 3511 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) { 3512 //FIXME: we only support address on first sink with HAL version < 3.0 3513 address = audio_device_address_to_parameter( 3514 patch->sinks[0].ext.device.type, 3515 patch->sinks[0].ext.device.address); 3516 } else { 3517 address = (char *)calloc(1, 1); 3518 } 3519 AudioParameter param = AudioParameter(String8(address)); 3520 free(address); 3521 param.addInt(String8(AudioParameter::keyRouting), (int)type); 3522 status = mOutput->stream->setParameters(param.toString()); 3523 *handle = AUDIO_PATCH_HANDLE_NONE; 3524 } 3525 if (configChanged) { 3526 mPrevOutDevice = type; 3527 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED); 3528 } 3529 return status; 3530 } 3531 3532 status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle) 3533 { 3534 status_t status; 3535 if (property_get_bool("af.patch_park", false /* default_value */)) { 3536 // Park FastMixer to avoid potential DOS issues with writing to the HAL 3537 // or if HAL does not properly lock against access. 3538 AutoPark<FastMixer> park(mFastMixer); 3539 status = PlaybackThread::releaseAudioPatch_l(handle); 3540 } else { 3541 status = PlaybackThread::releaseAudioPatch_l(handle); 3542 } 3543 return status; 3544 } 3545 3546 status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle) 3547 { 3548 status_t status = NO_ERROR; 3549 3550 mOutDevice = AUDIO_DEVICE_NONE; 3551 3552 if (mOutput->audioHwDev->supportsAudioPatches()) { 3553 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice(); 3554 status = hwDevice->releaseAudioPatch(handle); 3555 } else { 3556 AudioParameter param; 3557 param.addInt(String8(AudioParameter::keyRouting), 0); 3558 status = mOutput->stream->setParameters(param.toString()); 3559 } 3560 return status; 3561 } 3562 3563 void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track) 3564 { 3565 Mutex::Autolock _l(mLock); 3566 mTracks.add(track); 3567 } 3568 3569 void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track) 3570 { 3571 Mutex::Autolock _l(mLock); 3572 destroyTrack_l(track); 3573 } 3574 3575 void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config) 3576 { 3577 ThreadBase::getAudioPortConfig(config); 3578 config->role = AUDIO_PORT_ROLE_SOURCE; 3579 config->ext.mix.hw_module = mOutput->audioHwDev->handle(); 3580 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT; 3581 } 3582 3583 // ---------------------------------------------------------------------------- 3584 3585 AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, 3586 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type) 3587 : PlaybackThread(audioFlinger, output, id, device, type, systemReady), 3588 // mAudioMixer below 3589 // mFastMixer below 3590 mFastMixerFutex(0), 3591 mMasterMono(false) 3592 // mOutputSink below 3593 // mPipeSink below 3594 // mNormalSink below 3595 { 3596 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type); 3597 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, " 3598 "mFrameCount=%zu, mNormalFrameCount=%zu", 3599 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount, 3600 mNormalFrameCount); 3601 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate); 3602 3603 if (type == DUPLICATING) { 3604 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks 3605 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write(). 3606 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink. 3607 return; 3608 } 3609 // create an NBAIO sink for the HAL output stream, and negotiate 3610 mOutputSink = new AudioStreamOutSink(output->stream); 3611 size_t numCounterOffers = 0; 3612 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)}; 3613 #if !LOG_NDEBUG 3614 ssize_t index = 3615 #else 3616 (void) 3617 #endif 3618 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers); 3619 ALOG_ASSERT(index == 0); 3620 3621 // initialize fast mixer depending on configuration 3622 bool initFastMixer; 3623 switch (kUseFastMixer) { 3624 case FastMixer_Never: 3625 initFastMixer = false; 3626 break; 3627 case FastMixer_Always: 3628 initFastMixer = true; 3629 break; 3630 case FastMixer_Static: 3631 case FastMixer_Dynamic: 3632 // FastMixer was designed to operate with a HAL that pulls at a regular rate, 3633 // where the period is less than an experimentally determined threshold that can be 3634 // scheduled reliably with CFS. However, the BT A2DP HAL is 3635 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer. 3636 initFastMixer = mFrameCount < mNormalFrameCount 3637 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0; 3638 break; 3639 } 3640 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount, 3641 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu", 3642 mFrameCount, mNormalFrameCount); 3643 if (initFastMixer) { 3644 audio_format_t fastMixerFormat; 3645 if (mMixerBufferEnabled && mEffectBufferEnabled) { 3646 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT; 3647 } else { 3648 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT; 3649 } 3650 if (mFormat != fastMixerFormat) { 3651 // change our Sink format to accept our intermediate precision 3652 mFormat = fastMixerFormat; 3653 free(mSinkBuffer); 3654 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat); 3655 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize; 3656 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize); 3657 } 3658 3659 // create a MonoPipe to connect our submix to FastMixer 3660 NBAIO_Format format = mOutputSink->format(); 3661 #ifdef TEE_SINK 3662 NBAIO_Format origformat = format; 3663 #endif 3664 // adjust format to match that of the Fast Mixer 3665 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat); 3666 format.mFormat = fastMixerFormat; 3667 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount; 3668 3669 // This pipe depth compensates for scheduling latency of the normal mixer thread. 3670 // When it wakes up after a maximum latency, it runs a few cycles quickly before 3671 // finally blocking. Note the pipe implementation rounds up the request to a power of 2. 3672 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/); 3673 const NBAIO_Format offers[1] = {format}; 3674 size_t numCounterOffers = 0; 3675 #if !LOG_NDEBUG || defined(TEE_SINK) 3676 ssize_t index = 3677 #else 3678 (void) 3679 #endif 3680 monoPipe->negotiate(offers, 1, NULL, numCounterOffers); 3681 ALOG_ASSERT(index == 0); 3682 monoPipe->setAvgFrames((mScreenState & 1) ? 3683 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2); 3684 mPipeSink = monoPipe; 3685 3686 #ifdef TEE_SINK 3687 if (mTeeSinkOutputEnabled) { 3688 // create a Pipe to archive a copy of FastMixer's output for dumpsys 3689 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat); 3690 const NBAIO_Format offers2[1] = {origformat}; 3691 numCounterOffers = 0; 3692 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers); 3693 ALOG_ASSERT(index == 0); 3694 mTeeSink = teeSink; 3695 PipeReader *teeSource = new PipeReader(*teeSink); 3696 numCounterOffers = 0; 3697 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers); 3698 ALOG_ASSERT(index == 0); 3699 mTeeSource = teeSource; 3700 } 3701 #endif 3702 3703 // create fast mixer and configure it initially with just one fast track for our submix 3704 mFastMixer = new FastMixer(); 3705 FastMixerStateQueue *sq = mFastMixer->sq(); 3706 #ifdef STATE_QUEUE_DUMP 3707 sq->setObserverDump(&mStateQueueObserverDump); 3708 sq->setMutatorDump(&mStateQueueMutatorDump); 3709 #endif 3710 FastMixerState *state = sq->begin(); 3711 FastTrack *fastTrack = &state->mFastTracks[0]; 3712 // wrap the source side of the MonoPipe to make it an AudioBufferProvider 3713 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe)); 3714 fastTrack->mVolumeProvider = NULL; 3715 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer 3716 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer 3717 fastTrack->mGeneration++; 3718 state->mFastTracksGen++; 3719 state->mTrackMask = 1; 3720 // fast mixer will use the HAL output sink 3721 state->mOutputSink = mOutputSink.get(); 3722 state->mOutputSinkGen++; 3723 state->mFrameCount = mFrameCount; 3724 state->mCommand = FastMixerState::COLD_IDLE; 3725 // already done in constructor initialization list 3726 //mFastMixerFutex = 0; 3727 state->mColdFutexAddr = &mFastMixerFutex; 3728 state->mColdGen++; 3729 state->mDumpState = &mFastMixerDumpState; 3730 #ifdef TEE_SINK 3731 state->mTeeSink = mTeeSink.get(); 3732 #endif 3733 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer"); 3734 state->mNBLogWriter = mFastMixerNBLogWriter.get(); 3735 sq->end(); 3736 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 3737 3738 // start the fast mixer 3739 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO); 3740 pid_t tid = mFastMixer->getTid(); 3741 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false); 3742 stream()->setHalThreadPriority(kPriorityFastMixer); 3743 3744 #ifdef AUDIO_WATCHDOG 3745 // create and start the watchdog 3746 mAudioWatchdog = new AudioWatchdog(); 3747 mAudioWatchdog->setDump(&mAudioWatchdogDump); 3748 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO); 3749 tid = mAudioWatchdog->getTid(); 3750 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer); 3751 #endif 3752 3753 } 3754 3755 switch (kUseFastMixer) { 3756 case FastMixer_Never: 3757 case FastMixer_Dynamic: 3758 mNormalSink = mOutputSink; 3759 break; 3760 case FastMixer_Always: 3761 mNormalSink = mPipeSink; 3762 break; 3763 case FastMixer_Static: 3764 mNormalSink = initFastMixer ? mPipeSink : mOutputSink; 3765 break; 3766 } 3767 } 3768 3769 AudioFlinger::MixerThread::~MixerThread() 3770 { 3771 if (mFastMixer != 0) { 3772 FastMixerStateQueue *sq = mFastMixer->sq(); 3773 FastMixerState *state = sq->begin(); 3774 if (state->mCommand == FastMixerState::COLD_IDLE) { 3775 int32_t old = android_atomic_inc(&mFastMixerFutex); 3776 if (old == -1) { 3777 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1); 3778 } 3779 } 3780 state->mCommand = FastMixerState::EXIT; 3781 sq->end(); 3782 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 3783 mFastMixer->join(); 3784 // Though the fast mixer thread has exited, it's state queue is still valid. 3785 // We'll use that extract the final state which contains one remaining fast track 3786 // corresponding to our sub-mix. 3787 state = sq->begin(); 3788 ALOG_ASSERT(state->mTrackMask == 1); 3789 FastTrack *fastTrack = &state->mFastTracks[0]; 3790 ALOG_ASSERT(fastTrack->mBufferProvider != NULL); 3791 delete fastTrack->mBufferProvider; 3792 sq->end(false /*didModify*/); 3793 mFastMixer.clear(); 3794 #ifdef AUDIO_WATCHDOG 3795 if (mAudioWatchdog != 0) { 3796 mAudioWatchdog->requestExit(); 3797 mAudioWatchdog->requestExitAndWait(); 3798 mAudioWatchdog.clear(); 3799 } 3800 #endif 3801 } 3802 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter); 3803 delete mAudioMixer; 3804 } 3805 3806 3807 uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const 3808 { 3809 if (mFastMixer != 0) { 3810 MonoPipe *pipe = (MonoPipe *)mPipeSink.get(); 3811 latency += (pipe->getAvgFrames() * 1000) / mSampleRate; 3812 } 3813 return latency; 3814 } 3815 3816 3817 void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove) 3818 { 3819 PlaybackThread::threadLoop_removeTracks(tracksToRemove); 3820 } 3821 3822 ssize_t AudioFlinger::MixerThread::threadLoop_write() 3823 { 3824 // FIXME we should only do one push per cycle; confirm this is true 3825 // Start the fast mixer if it's not already running 3826 if (mFastMixer != 0) { 3827 FastMixerStateQueue *sq = mFastMixer->sq(); 3828 FastMixerState *state = sq->begin(); 3829 if (state->mCommand != FastMixerState::MIX_WRITE && 3830 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) { 3831 if (state->mCommand == FastMixerState::COLD_IDLE) { 3832 3833 // FIXME workaround for first HAL write being CPU bound on some devices 3834 ATRACE_BEGIN("write"); 3835 mOutput->write((char *)mSinkBuffer, 0); 3836 ATRACE_END(); 3837 3838 int32_t old = android_atomic_inc(&mFastMixerFutex); 3839 if (old == -1) { 3840 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1); 3841 } 3842 #ifdef AUDIO_WATCHDOG 3843 if (mAudioWatchdog != 0) { 3844 mAudioWatchdog->resume(); 3845 } 3846 #endif 3847 } 3848 state->mCommand = FastMixerState::MIX_WRITE; 3849 #ifdef FAST_THREAD_STATISTICS 3850 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ? 3851 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN); 3852 #endif 3853 sq->end(); 3854 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED); 3855 if (kUseFastMixer == FastMixer_Dynamic) { 3856 mNormalSink = mPipeSink; 3857 } 3858 } else { 3859 sq->end(false /*didModify*/); 3860 } 3861 } 3862 return PlaybackThread::threadLoop_write(); 3863 } 3864 3865 void AudioFlinger::MixerThread::threadLoop_standby() 3866 { 3867 // Idle the fast mixer if it's currently running 3868 if (mFastMixer != 0) { 3869 FastMixerStateQueue *sq = mFastMixer->sq(); 3870 FastMixerState *state = sq->begin(); 3871 if (!(state->mCommand & FastMixerState::IDLE)) { 3872 // Report any frames trapped in the Monopipe 3873 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get(); 3874 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite(); 3875 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld " 3876 "monoPipeWritten:%lld monoPipeLeft:%lld", 3877 (long long)mFramesWritten, (long long)mSuspendedFrames, 3878 (long long)mPipeSink->framesWritten(), pipeFrames); 3879 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str()); 3880 3881 state->mCommand = FastMixerState::COLD_IDLE; 3882 state->mColdFutexAddr = &mFastMixerFutex; 3883 state->mColdGen++; 3884 mFastMixerFutex = 0; 3885 sq->end(); 3886 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now 3887 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED); 3888 if (kUseFastMixer == FastMixer_Dynamic) { 3889 mNormalSink = mOutputSink; 3890 } 3891 #ifdef AUDIO_WATCHDOG 3892 if (mAudioWatchdog != 0) { 3893 mAudioWatchdog->pause(); 3894 } 3895 #endif 3896 } else { 3897 sq->end(false /*didModify*/); 3898 } 3899 } 3900 PlaybackThread::threadLoop_standby(); 3901 } 3902 3903 bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l() 3904 { 3905 return false; 3906 } 3907 3908 bool AudioFlinger::PlaybackThread::shouldStandby_l() 3909 { 3910 return !mStandby; 3911 } 3912 3913 bool AudioFlinger::PlaybackThread::waitingAsyncCallback() 3914 { 3915 Mutex::Autolock _l(mLock); 3916 return waitingAsyncCallback_l(); 3917 } 3918 3919 // shared by MIXER and DIRECT, overridden by DUPLICATING 3920 void AudioFlinger::PlaybackThread::threadLoop_standby() 3921 { 3922 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended); 3923 mOutput->standby(); 3924 if (mUseAsyncWrite != 0) { 3925 // discard any pending drain or write ack by incrementing sequence 3926 mWriteAckSequence = (mWriteAckSequence + 2) & ~1; 3927 mDrainSequence = (mDrainSequence + 2) & ~1; 3928 ALOG_ASSERT(mCallbackThread != 0); 3929 mCallbackThread->setWriteBlocked(mWriteAckSequence); 3930 mCallbackThread->setDraining(mDrainSequence); 3931 } 3932 mHwPaused = false; 3933 } 3934 3935 void AudioFlinger::PlaybackThread::onAddNewTrack_l() 3936 { 3937 ALOGV("signal playback thread"); 3938 broadcast_l(); 3939 } 3940 3941 void AudioFlinger::PlaybackThread::onAsyncError() 3942 { 3943 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) { 3944 invalidateTracks((audio_stream_type_t)i); 3945 } 3946 } 3947 3948 void AudioFlinger::MixerThread::threadLoop_mix() 3949 { 3950 // mix buffers... 3951 mAudioMixer->process(); 3952 mCurrentWriteLength = mSinkBufferSize; 3953 // increase sleep time progressively when application underrun condition clears. 3954 // Only increase sleep time if the mixer is ready for two consecutive times to avoid 3955 // that a steady state of alternating ready/not ready conditions keeps the sleep time 3956 // such that we would underrun the audio HAL. 3957 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) { 3958 sleepTimeShift--; 3959 } 3960 mSleepTimeUs = 0; 3961 mStandbyTimeNs = systemTime() + mStandbyDelayNs; 3962 //TODO: delay standby when effects have a tail 3963 3964 } 3965 3966 void AudioFlinger::MixerThread::threadLoop_sleepTime() 3967 { 3968 // If no tracks are ready, sleep once for the duration of an output 3969 // buffer size, then write 0s to the output 3970 if (mSleepTimeUs == 0) { 3971 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 3972 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift; 3973 if (mSleepTimeUs < kMinThreadSleepTimeUs) { 3974 mSleepTimeUs = kMinThreadSleepTimeUs; 3975 } 3976 // reduce sleep time in case of consecutive application underruns to avoid 3977 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer 3978 // duration we would end up writing less data than needed by the audio HAL if 3979 // the condition persists. 3980 if (sleepTimeShift < kMaxThreadSleepTimeShift) { 3981 sleepTimeShift++; 3982 } 3983 } else { 3984 mSleepTimeUs = mIdleSleepTimeUs; 3985 } 3986 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) { 3987 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared 3988 // before effects processing or output. 3989 if (mMixerBufferValid) { 3990 memset(mMixerBuffer, 0, mMixerBufferSize); 3991 } else { 3992 memset(mSinkBuffer, 0, mSinkBufferSize); 3993 } 3994 mSleepTimeUs = 0; 3995 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED), 3996 "anticipated start"); 3997 } 3998 // TODO add standby time extension fct of effect tail 3999 } 4000 4001 // prepareTracks_l() must be called with ThreadBase::mLock held 4002 AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l( 4003 Vector< sp<Track> > *tracksToRemove) 4004 { 4005 4006 mixer_state mixerStatus = MIXER_IDLE; 4007 // find out which tracks need to be processed 4008 size_t count = mActiveTracks.size(); 4009 size_t mixedTracks = 0; 4010 size_t tracksWithEffect = 0; 4011 // counts only _active_ fast tracks 4012 size_t fastTracks = 0; 4013 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset 4014 4015 float masterVolume = mMasterVolume; 4016 bool masterMute = mMasterMute; 4017 4018 if (masterMute) { 4019 masterVolume = 0; 4020 } 4021 // Delegate master volume control to effect in output mix effect chain if needed 4022 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); 4023 if (chain != 0) { 4024 uint32_t v = (uint32_t)(masterVolume * (1 << 24)); 4025 chain->setVolume_l(&v, &v); 4026 masterVolume = (float)((v + (1 << 23)) >> 24); 4027 chain.clear(); 4028 } 4029 4030 // prepare a new state to push 4031 FastMixerStateQueue *sq = NULL; 4032 FastMixerState *state = NULL; 4033 bool didModify = false; 4034 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED; 4035 bool coldIdle = false; 4036 if (mFastMixer != 0) { 4037 sq = mFastMixer->sq(); 4038 state = sq->begin(); 4039 coldIdle = state->mCommand == FastMixerState::COLD_IDLE; 4040 } 4041 4042 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found. 4043 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found. 4044 4045 for (size_t i=0 ; i<count ; i++) { 4046 const sp<Track> t = mActiveTracks[i]; 4047 4048 // this const just means the local variable doesn't change 4049 Track* const track = t.get(); 4050 4051 // process fast tracks 4052 if (track->isFastTrack()) { 4053 4054 // It's theoretically possible (though unlikely) for a fast track to be created 4055 // and then removed within the same normal mix cycle. This is not a problem, as 4056 // the track never becomes active so it's fast mixer slot is never touched. 4057 // The converse, of removing an (active) track and then creating a new track 4058 // at the identical fast mixer slot within the same normal mix cycle, 4059 // is impossible because the slot isn't marked available until the end of each cycle. 4060 int j = track->mFastIndex; 4061 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks); 4062 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j))); 4063 FastTrack *fastTrack = &state->mFastTracks[j]; 4064 4065 // Determine whether the track is currently in underrun condition, 4066 // and whether it had a recent underrun. 4067 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j]; 4068 FastTrackUnderruns underruns = ftDump->mUnderruns; 4069 uint32_t recentFull = (underruns.mBitFields.mFull - 4070 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK; 4071 uint32_t recentPartial = (underruns.mBitFields.mPartial - 4072 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK; 4073 uint32_t recentEmpty = (underruns.mBitFields.mEmpty - 4074 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK; 4075 uint32_t recentUnderruns = recentPartial + recentEmpty; 4076 track->mObservedUnderruns = underruns; 4077 // don't count underruns that occur while stopping or pausing 4078 // or stopped which can occur when flush() is called while active 4079 if (!(track->isStopping() || track->isPausing() || track->isStopped()) && 4080 recentUnderruns > 0) { 4081 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun 4082 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount); 4083 } else { 4084 track->mAudioTrackServerProxy->tallyUnderrunFrames(0); 4085 } 4086 4087 // This is similar to the state machine for normal tracks, 4088 // with a few modifications for fast tracks. 4089 bool isActive = true; 4090 switch (track->mState) { 4091 case TrackBase::STOPPING_1: 4092 // track stays active in STOPPING_1 state until first underrun 4093 if (recentUnderruns > 0 || track->isTerminated()) { 4094 track->mState = TrackBase::STOPPING_2; 4095 } 4096 break; 4097 case TrackBase::PAUSING: 4098 // ramp down is not yet implemented 4099 track->setPaused(); 4100 break; 4101 case TrackBase::RESUMING: 4102 // ramp up is not yet implemented 4103 track->mState = TrackBase::ACTIVE; 4104 break; 4105 case TrackBase::ACTIVE: 4106 if (recentFull > 0 || recentPartial > 0) { 4107 // track has provided at least some frames recently: reset retry count 4108 track->mRetryCount = kMaxTrackRetries; 4109 } 4110 if (recentUnderruns == 0) { 4111 // no recent underruns: stay active 4112 break; 4113 } 4114 // there has recently been an underrun of some kind 4115 if (track->sharedBuffer() == 0) { 4116 // were any of the recent underruns "empty" (no frames available)? 4117 if (recentEmpty == 0) { 4118 // no, then ignore the partial underruns as they are allowed indefinitely 4119 break; 4120 } 4121 // there has recently been an "empty" underrun: decrement the retry counter 4122 if (--(track->mRetryCount) > 0) { 4123 break; 4124 } 4125 // indicate to client process that the track was disabled because of underrun; 4126 // it will then automatically call start() when data is available 4127 track->disable(); 4128 // remove from active list, but state remains ACTIVE [confusing but true] 4129 isActive = false; 4130 break; 4131 } 4132 // fall through 4133 case TrackBase::STOPPING_2: 4134 case TrackBase::PAUSED: 4135 case TrackBase::STOPPED: 4136 case TrackBase::FLUSHED: // flush() while active 4137 // Check for presentation complete if track is inactive 4138 // We have consumed all the buffers of this track. 4139 // This would be incomplete if we auto-paused on underrun 4140 { 4141 uint32_t latency = 0; 4142 status_t result = mOutput->stream->getLatency(&latency); 4143 ALOGE_IF(result != OK, 4144 "Error when retrieving output stream latency: %d", result); 4145 size_t audioHALFrames = (latency * mSampleRate) / 1000; 4146 int64_t framesWritten = mBytesWritten / mFrameSize; 4147 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) { 4148 // track stays in active list until presentation is complete 4149 break; 4150 } 4151 } 4152 if (track->isStopping_2()) { 4153 track->mState = TrackBase::STOPPED; 4154 } 4155 if (track->isStopped()) { 4156 // Can't reset directly, as fast mixer is still polling this track 4157 // track->reset(); 4158 // So instead mark this track as needing to be reset after push with ack 4159 resetMask |= 1 << i; 4160 } 4161 isActive = false; 4162 break; 4163 case TrackBase::IDLE: 4164 default: 4165 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState); 4166 } 4167 4168 if (isActive) { 4169 // was it previously inactive? 4170 if (!(state->mTrackMask & (1 << j))) { 4171 ExtendedAudioBufferProvider *eabp = track; 4172 VolumeProvider *vp = track; 4173 fastTrack->mBufferProvider = eabp; 4174 fastTrack->mVolumeProvider = vp; 4175 fastTrack->mChannelMask = track->mChannelMask; 4176 fastTrack->mFormat = track->mFormat; 4177 fastTrack->mGeneration++; 4178 state->mTrackMask |= 1 << j; 4179 didModify = true; 4180 // no acknowledgement required for newly active tracks 4181 } 4182 // cache the combined master volume and stream type volume for fast mixer; this 4183 // lacks any synchronization or barrier so VolumeProvider may read a stale value 4184 const float vh = track->getVolumeHandler()->getVolume( 4185 track->mAudioTrackServerProxy->framesReleased()).first; 4186 track->mCachedVolume = masterVolume 4187 * mStreamTypes[track->streamType()].volume 4188 * vh; 4189 ++fastTracks; 4190 } else { 4191 // was it previously active? 4192 if (state->mTrackMask & (1 << j)) { 4193 fastTrack->mBufferProvider = NULL; 4194 fastTrack->mGeneration++; 4195 state->mTrackMask &= ~(1 << j); 4196 didModify = true; 4197 // If any fast tracks were removed, we must wait for acknowledgement 4198 // because we're about to decrement the last sp<> on those tracks. 4199 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED; 4200 } else { 4201 LOG_ALWAYS_FATAL("fast track %d should have been active; " 4202 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d", 4203 j, track->mState, state->mTrackMask, recentUnderruns, 4204 track->sharedBuffer() != 0); 4205 } 4206 tracksToRemove->add(track); 4207 // Avoids a misleading display in dumpsys 4208 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL; 4209 } 4210 continue; 4211 } 4212 4213 { // local variable scope to avoid goto warning 4214 4215 audio_track_cblk_t* cblk = track->cblk(); 4216 4217 // The first time a track is added we wait 4218 // for all its buffers to be filled before processing it 4219 int name = track->name(); 4220 // make sure that we have enough frames to mix one full buffer. 4221 // enforce this condition only once to enable draining the buffer in case the client 4222 // app does not call stop() and relies on underrun to stop: 4223 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed 4224 // during last round 4225 size_t desiredFrames; 4226 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate(); 4227 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate(); 4228 4229 desiredFrames = sourceFramesNeededWithTimestretch( 4230 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed); 4231 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed. 4232 // add frames already consumed but not yet released by the resampler 4233 // because mAudioTrackServerProxy->framesReady() will include these frames 4234 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name()); 4235 4236 uint32_t minFrames = 1; 4237 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() && 4238 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) { 4239 minFrames = desiredFrames; 4240 } 4241 4242 size_t framesReady = track->framesReady(); 4243 if (ATRACE_ENABLED()) { 4244 // I wish we had formatted trace names 4245 char traceName[16]; 4246 strcpy(traceName, "nRdy"); 4247 int name = track->name(); 4248 if (AudioMixer::TRACK0 <= name && 4249 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) { 4250 name -= AudioMixer::TRACK0; 4251 traceName[4] = (name / 10) + '0'; 4252 traceName[5] = (name % 10) + '0'; 4253 } else { 4254 traceName[4] = '?'; 4255 traceName[5] = '?'; 4256 } 4257 traceName[6] = '\0'; 4258 ATRACE_INT(traceName, framesReady); 4259 } 4260 if ((framesReady >= minFrames) && track->isReady() && 4261 !track->isPaused() && !track->isTerminated()) 4262 { 4263 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this); 4264 4265 mixedTracks++; 4266 4267 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means 4268 // there is an effect chain connected to the track 4269 chain.clear(); 4270 if (track->mainBuffer() != mSinkBuffer && 4271 track->mainBuffer() != mMixerBuffer) { 4272 if (mEffectBufferEnabled) { 4273 mEffectBufferValid = true; // Later can set directly. 4274 } 4275 chain = getEffectChain_l(track->sessionId()); 4276 // Delegate volume control to effect in track effect chain if needed 4277 if (chain != 0) { 4278 tracksWithEffect++; 4279 } else { 4280 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on " 4281 "session %d", 4282 name, track->sessionId()); 4283 } 4284 } 4285 4286 4287 int param = AudioMixer::VOLUME; 4288 if (track->mFillingUpStatus == Track::FS_FILLED) { 4289 // no ramp for the first volume setting 4290 track->mFillingUpStatus = Track::FS_ACTIVE; 4291 if (track->mState == TrackBase::RESUMING) { 4292 track->mState = TrackBase::ACTIVE; 4293 param = AudioMixer::RAMP_VOLUME; 4294 } 4295 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL); 4296 // FIXME should not make a decision based on mServer 4297 } else if (cblk->mServer != 0) { 4298 // If the track is stopped before the first frame was mixed, 4299 // do not apply ramp 4300 param = AudioMixer::RAMP_VOLUME; 4301 } 4302 4303 // compute volume for this track 4304 uint32_t vl, vr; // in U8.24 integer format 4305 float vlf, vrf, vaf; // in [0.0, 1.0] float format 4306 if (track->isPausing() || mStreamTypes[track->streamType()].mute) { 4307 vl = vr = 0; 4308 vlf = vrf = vaf = 0.; 4309 if (track->isPausing()) { 4310 track->setPaused(); 4311 } 4312 } else { 4313 4314 // read original volumes with volume control 4315 float typeVolume = mStreamTypes[track->streamType()].volume; 4316 float v = masterVolume * typeVolume; 4317 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy; 4318 gain_minifloat_packed_t vlr = proxy->getVolumeLR(); 4319 vlf = float_from_gain(gain_minifloat_unpack_left(vlr)); 4320 vrf = float_from_gain(gain_minifloat_unpack_right(vlr)); 4321 // track volumes come from shared memory, so can't be trusted and must be clamped 4322 if (vlf > GAIN_FLOAT_UNITY) { 4323 ALOGV("Track left volume out of range: %.3g", vlf); 4324 vlf = GAIN_FLOAT_UNITY; 4325 } 4326 if (vrf > GAIN_FLOAT_UNITY) { 4327 ALOGV("Track right volume out of range: %.3g", vrf); 4328 vrf = GAIN_FLOAT_UNITY; 4329 } 4330 const float vh = track->getVolumeHandler()->getVolume( 4331 track->mAudioTrackServerProxy->framesReleased()).first; 4332 // now apply the master volume and stream type volume and shaper volume 4333 vlf *= v * vh; 4334 vrf *= v * vh; 4335 // assuming master volume and stream type volume each go up to 1.0, 4336 // then derive vl and vr as U8.24 versions for the effect chain 4337 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT; 4338 vl = (uint32_t) (scaleto8_24 * vlf); 4339 vr = (uint32_t) (scaleto8_24 * vrf); 4340 // vl and vr are now in U8.24 format 4341 uint16_t sendLevel = proxy->getSendLevel_U4_12(); 4342 // send level comes from shared memory and so may be corrupt 4343 if (sendLevel > MAX_GAIN_INT) { 4344 ALOGV("Track send level out of range: %04X", sendLevel); 4345 sendLevel = MAX_GAIN_INT; 4346 } 4347 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel 4348 vaf = v * sendLevel * (1. / MAX_GAIN_INT); 4349 } 4350 4351 // Delegate volume control to effect in track effect chain if needed 4352 if (chain != 0 && chain->setVolume_l(&vl, &vr)) { 4353 // Do not ramp volume if volume is controlled by effect 4354 param = AudioMixer::VOLUME; 4355 // Update remaining floating point volume levels 4356 vlf = (float)vl / (1 << 24); 4357 vrf = (float)vr / (1 << 24); 4358 track->mHasVolumeController = true; 4359 } else { 4360 // force no volume ramp when volume controller was just disabled or removed 4361 // from effect chain to avoid volume spike 4362 if (track->mHasVolumeController) { 4363 param = AudioMixer::VOLUME; 4364 } 4365 track->mHasVolumeController = false; 4366 } 4367 4368 // XXX: these things DON'T need to be done each time 4369 mAudioMixer->setBufferProvider(name, track); 4370 mAudioMixer->enable(name); 4371 4372 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf); 4373 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf); 4374 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf); 4375 mAudioMixer->setParameter( 4376 name, 4377 AudioMixer::TRACK, 4378 AudioMixer::FORMAT, (void *)track->format()); 4379 mAudioMixer->setParameter( 4380 name, 4381 AudioMixer::TRACK, 4382 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask()); 4383 mAudioMixer->setParameter( 4384 name, 4385 AudioMixer::TRACK, 4386 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask); 4387 // limit track sample rate to 2 x output sample rate, which changes at re-configuration 4388 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX; 4389 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate(); 4390 if (reqSampleRate == 0) { 4391 reqSampleRate = mSampleRate; 4392 } else if (reqSampleRate > maxSampleRate) { 4393 reqSampleRate = maxSampleRate; 4394 } 4395 mAudioMixer->setParameter( 4396 name, 4397 AudioMixer::RESAMPLE, 4398 AudioMixer::SAMPLE_RATE, 4399 (void *)(uintptr_t)reqSampleRate); 4400 4401 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate(); 4402 mAudioMixer->setParameter( 4403 name, 4404 AudioMixer::TIMESTRETCH, 4405 AudioMixer::PLAYBACK_RATE, 4406 &playbackRate); 4407 4408 /* 4409 * Select the appropriate output buffer for the track. 4410 * 4411 * Tracks with effects go into their own effects chain buffer 4412 * and from there into either mEffectBuffer or mSinkBuffer. 4413 * 4414 * Other tracks can use mMixerBuffer for higher precision 4415 * channel accumulation. If this buffer is enabled 4416 * (mMixerBufferEnabled true), then selected tracks will accumulate 4417 * into it. 4418 * 4419 */ 4420 if (mMixerBufferEnabled 4421 && (track->mainBuffer() == mSinkBuffer 4422 || track->mainBuffer() == mMixerBuffer)) { 4423 mAudioMixer->setParameter( 4424 name, 4425 AudioMixer::TRACK, 4426 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat); 4427 mAudioMixer->setParameter( 4428 name, 4429 AudioMixer::TRACK, 4430 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer); 4431 // TODO: override track->mainBuffer()? 4432 mMixerBufferValid = true; 4433 } else { 4434 mAudioMixer->setParameter( 4435 name, 4436 AudioMixer::TRACK, 4437 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT); 4438 mAudioMixer->setParameter( 4439 name, 4440 AudioMixer::TRACK, 4441 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer()); 4442 } 4443 mAudioMixer->setParameter( 4444 name, 4445 AudioMixer::TRACK, 4446 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer()); 4447 4448 // reset retry count 4449 track->mRetryCount = kMaxTrackRetries; 4450 4451 // If one track is ready, set the mixer ready if: 4452 // - the mixer was not ready during previous round OR 4453 // - no other track is not ready 4454 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY || 4455 mixerStatus != MIXER_TRACKS_ENABLED) { 4456 mixerStatus = MIXER_TRACKS_READY; 4457 } 4458 } else { 4459 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) { 4460 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)", 4461 track, framesReady, desiredFrames); 4462 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames); 4463 } else { 4464 track->mAudioTrackServerProxy->tallyUnderrunFrames(0); 4465 } 4466 4467 // clear effect chain input buffer if an active track underruns to avoid sending 4468 // previous audio buffer again to effects 4469 chain = getEffectChain_l(track->sessionId()); 4470 if (chain != 0) { 4471 chain->clearInputBuffer(); 4472 } 4473 4474 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this); 4475 if ((track->sharedBuffer() != 0) || track->isTerminated() || 4476 track->isStopped() || track->isPaused()) { 4477 // We have consumed all the buffers of this track. 4478 // Remove it from the list of active tracks. 4479 // TODO: use actual buffer filling status instead of latency when available from 4480 // audio HAL 4481 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000; 4482 int64_t framesWritten = mBytesWritten / mFrameSize; 4483 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) { 4484 if (track->isStopped()) { 4485 track->reset(); 4486 } 4487 tracksToRemove->add(track); 4488 } 4489 } else { 4490 // No buffers for this track. Give it a few chances to 4491 // fill a buffer, then remove it from active list. 4492 if (--(track->mRetryCount) <= 0) { 4493 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this); 4494 tracksToRemove->add(track); 4495 // indicate to client process that the track was disabled because of underrun; 4496 // it will then automatically call start() when data is available 4497 track->disable(); 4498 // If one track is not ready, mark the mixer also not ready if: 4499 // - the mixer was ready during previous round OR 4500 // - no other track is ready 4501 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY || 4502 mixerStatus != MIXER_TRACKS_READY) { 4503 mixerStatus = MIXER_TRACKS_ENABLED; 4504 } 4505 } 4506 mAudioMixer->disable(name); 4507 } 4508 4509 } // local variable scope to avoid goto warning 4510 4511 } 4512 4513 // Push the new FastMixer state if necessary 4514 bool pauseAudioWatchdog = false; 4515 if (didModify) { 4516 state->mFastTracksGen++; 4517 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle 4518 if (kUseFastMixer == FastMixer_Dynamic && 4519 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) { 4520 state->mCommand = FastMixerState::COLD_IDLE; 4521 state->mColdFutexAddr = &mFastMixerFutex; 4522 state->mColdGen++; 4523 mFastMixerFutex = 0; 4524 if (kUseFastMixer == FastMixer_Dynamic) { 4525 mNormalSink = mOutputSink; 4526 } 4527 // If we go into cold idle, need to wait for acknowledgement 4528 // so that fast mixer stops doing I/O. 4529 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED; 4530 pauseAudioWatchdog = true; 4531 } 4532 } 4533 if (sq != NULL) { 4534 sq->end(didModify); 4535 // No need to block if the FastMixer is in COLD_IDLE as the FastThread 4536 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE 4537 // when bringing the output sink into standby.) 4538 // 4539 // We will get the latest FastMixer state when we come out of COLD_IDLE. 4540 // 4541 // This occurs with BT suspend when we idle the FastMixer with 4542 // active tracks, which may be added or removed. 4543 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block); 4544 } 4545 #ifdef AUDIO_WATCHDOG 4546 if (pauseAudioWatchdog && mAudioWatchdog != 0) { 4547 mAudioWatchdog->pause(); 4548 } 4549 #endif 4550 4551 // Now perform the deferred reset on fast tracks that have stopped 4552 while (resetMask != 0) { 4553 size_t i = __builtin_ctz(resetMask); 4554 ALOG_ASSERT(i < count); 4555 resetMask &= ~(1 << i); 4556 sp<Track> track = mActiveTracks[i]; 4557 ALOG_ASSERT(track->isFastTrack() && track->isStopped()); 4558 track->reset(); 4559 } 4560 4561 // remove all the tracks that need to be... 4562 removeTracks_l(*tracksToRemove); 4563 4564 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) { 4565 mEffectBufferValid = true; 4566 } 4567 4568 if (mEffectBufferValid) { 4569 // as long as there are effects we should clear the effects buffer, to avoid 4570 // passing a non-clean buffer to the effect chain 4571 memset(mEffectBuffer, 0, mEffectBufferSize); 4572 } 4573 // sink or mix buffer must be cleared if all tracks are connected to an 4574 // effect chain as in this case the mixer will not write to the sink or mix buffer 4575 // and track effects will accumulate into it 4576 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || 4577 (mixedTracks == 0 && fastTracks > 0))) { 4578 // FIXME as a performance optimization, should remember previous zero status 4579 if (mMixerBufferValid) { 4580 memset(mMixerBuffer, 0, mMixerBufferSize); 4581 // TODO: In testing, mSinkBuffer below need not be cleared because 4582 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer 4583 // after mixing. 4584 // 4585 // To enforce this guarantee: 4586 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || 4587 // (mixedTracks == 0 && fastTracks > 0)) 4588 // must imply MIXER_TRACKS_READY. 4589 // Later, we may clear buffers regardless, and skip much of this logic. 4590 } 4591 // FIXME as a performance optimization, should remember previous zero status 4592 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize); 4593 } 4594 4595 // if any fast tracks, then status is ready 4596 mMixerStatusIgnoringFastTracks = mixerStatus; 4597 if (fastTracks > 0) { 4598 mixerStatus = MIXER_TRACKS_READY; 4599 } 4600 return mixerStatus; 4601 } 4602 4603 // trackCountForUid_l() must be called with ThreadBase::mLock held 4604 uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) 4605 { 4606 uint32_t trackCount = 0; 4607 for (size_t i = 0; i < mTracks.size() ; i++) { 4608 if (mTracks[i]->uid() == uid) { 4609 trackCount++; 4610 } 4611 } 4612 return trackCount; 4613 } 4614 4615 // getTrackName_l() must be called with ThreadBase::mLock held 4616 int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, 4617 audio_format_t format, audio_session_t sessionId, uid_t uid) 4618 { 4619 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) { 4620 return -1; 4621 } 4622 return mAudioMixer->getTrackName(channelMask, format, sessionId); 4623 } 4624 4625 // deleteTrackName_l() must be called with ThreadBase::mLock held 4626 void AudioFlinger::MixerThread::deleteTrackName_l(int name) 4627 { 4628 ALOGV("remove track (%d) and delete from mixer", name); 4629 mAudioMixer->deleteTrackName(name); 4630 } 4631 4632 // checkForNewParameter_l() must be called with ThreadBase::mLock held 4633 bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair, 4634 status_t& status) 4635 { 4636 bool reconfig = false; 4637 bool a2dpDeviceChanged = false; 4638 4639 status = NO_ERROR; 4640 4641 AutoPark<FastMixer> park(mFastMixer); 4642 4643 AudioParameter param = AudioParameter(keyValuePair); 4644 int value; 4645 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { 4646 reconfig = true; 4647 } 4648 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { 4649 if (!isValidPcmSinkFormat((audio_format_t) value)) { 4650 status = BAD_VALUE; 4651 } else { 4652 // no need to save value, since it's constant 4653 reconfig = true; 4654 } 4655 } 4656 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { 4657 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) { 4658 status = BAD_VALUE; 4659 } else { 4660 // no need to save value, since it's constant 4661 reconfig = true; 4662 } 4663 } 4664 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 4665 // do not accept frame count changes if tracks are open as the track buffer 4666 // size depends on frame count and correct behavior would not be guaranteed 4667 // if frame count is changed after track creation 4668 if (!mTracks.isEmpty()) { 4669 status = INVALID_OPERATION; 4670 } else { 4671 reconfig = true; 4672 } 4673 } 4674 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 4675 #ifdef ADD_BATTERY_DATA 4676 // when changing the audio output device, call addBatteryData to notify 4677 // the change 4678 if (mOutDevice != value) { 4679 uint32_t params = 0; 4680 // check whether speaker is on 4681 if (value & AUDIO_DEVICE_OUT_SPEAKER) { 4682 params |= IMediaPlayerService::kBatteryDataSpeakerOn; 4683 } 4684 4685 audio_devices_t deviceWithoutSpeaker 4686 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER; 4687 // check if any other device (except speaker) is on 4688 if (value & deviceWithoutSpeaker) { 4689 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn; 4690 } 4691 4692 if (params != 0) { 4693 addBatteryData(params); 4694 } 4695 } 4696 #endif 4697 4698 // forward device change to effects that have requested to be 4699 // aware of attached audio device. 4700 if (value != AUDIO_DEVICE_NONE) { 4701 a2dpDeviceChanged = 4702 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP); 4703 mOutDevice = value; 4704 for (size_t i = 0; i < mEffectChains.size(); i++) { 4705 mEffectChains[i]->setDevice_l(mOutDevice); 4706 } 4707 } 4708 } 4709 4710 if (status == NO_ERROR) { 4711 status = mOutput->stream->setParameters(keyValuePair); 4712 if (!mStandby && status == INVALID_OPERATION) { 4713 mOutput->standby(); 4714 mStandby = true; 4715 mBytesWritten = 0; 4716 status = mOutput->stream->setParameters(keyValuePair); 4717 } 4718 if (status == NO_ERROR && reconfig) { 4719 readOutputParameters_l(); 4720 delete mAudioMixer; 4721 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate); 4722 for (size_t i = 0; i < mTracks.size() ; i++) { 4723 int name = getTrackName_l(mTracks[i]->mChannelMask, 4724 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid()); 4725 if (name < 0) { 4726 break; 4727 } 4728 mTracks[i]->mName = name; 4729 } 4730 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED); 4731 } 4732 } 4733 4734 return reconfig || a2dpDeviceChanged; 4735 } 4736 4737 4738 void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args) 4739 { 4740 PlaybackThread::dumpInternals(fd, args); 4741 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs); 4742 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames()); 4743 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off"); 4744 4745 if (hasFastMixer()) { 4746 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid()); 4747 4748 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us 4749 // while we are dumping it. It may be inconsistent, but it won't mutate! 4750 // This is a large object so we place it on the heap. 4751 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages. 4752 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState); 4753 copy->dump(fd); 4754 delete copy; 4755 4756 #ifdef STATE_QUEUE_DUMP 4757 // Similar for state queue 4758 StateQueueObserverDump observerCopy = mStateQueueObserverDump; 4759 observerCopy.dump(fd); 4760 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump; 4761 mutatorCopy.dump(fd); 4762 #endif 4763 4764 #ifdef AUDIO_WATCHDOG 4765 if (mAudioWatchdog != 0) { 4766 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us 4767 AudioWatchdogDump wdCopy = mAudioWatchdogDump; 4768 wdCopy.dump(fd); 4769 } 4770 #endif 4771 4772 } else { 4773 dprintf(fd, " No FastMixer\n"); 4774 } 4775 4776 #ifdef TEE_SINK 4777 // Write the tee output to a .wav file 4778 dumpTee(fd, mTeeSource, mId); 4779 #endif 4780 4781 } 4782 4783 uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const 4784 { 4785 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2; 4786 } 4787 4788 uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const 4789 { 4790 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000); 4791 } 4792 4793 void AudioFlinger::MixerThread::cacheParameters_l() 4794 { 4795 PlaybackThread::cacheParameters_l(); 4796 4797 // FIXME: Relaxed timing because of a certain device that can't meet latency 4798 // Should be reduced to 2x after the vendor fixes the driver issue 4799 // increase threshold again due to low power audio mode. The way this warning 4800 // threshold is calculated and its usefulness should be reconsidered anyway. 4801 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15; 4802 } 4803 4804 // ---------------------------------------------------------------------------- 4805 4806 AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, 4807 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady) 4808 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady) 4809 // mLeftVolFloat, mRightVolFloat 4810 { 4811 } 4812 4813 AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, 4814 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, 4815 ThreadBase::type_t type, bool systemReady) 4816 : PlaybackThread(audioFlinger, output, id, device, type, systemReady) 4817 // mLeftVolFloat, mRightVolFloat 4818 , mVolumeShaperActive(false) 4819 { 4820 } 4821 4822 AudioFlinger::DirectOutputThread::~DirectOutputThread() 4823 { 4824 } 4825 4826 void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack) 4827 { 4828 float left, right; 4829 4830 if (mMasterMute || mStreamTypes[track->streamType()].mute) { 4831 left = right = 0; 4832 } else { 4833 float typeVolume = mStreamTypes[track->streamType()].volume; 4834 float v = mMasterVolume * typeVolume; 4835 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy; 4836 4837 // Get volumeshaper scaling 4838 std::pair<float /* volume */, bool /* active */> 4839 vh = track->getVolumeHandler()->getVolume( 4840 track->mAudioTrackServerProxy->framesReleased()); 4841 v *= vh.first; 4842 mVolumeShaperActive = vh.second; 4843 4844 gain_minifloat_packed_t vlr = proxy->getVolumeLR(); 4845 left = float_from_gain(gain_minifloat_unpack_left(vlr)); 4846 if (left > GAIN_FLOAT_UNITY) { 4847 left = GAIN_FLOAT_UNITY; 4848 } 4849 left *= v; 4850 right = float_from_gain(gain_minifloat_unpack_right(vlr)); 4851 if (right > GAIN_FLOAT_UNITY) { 4852 right = GAIN_FLOAT_UNITY; 4853 } 4854 right *= v; 4855 } 4856 4857 if (lastTrack) { 4858 if (left != mLeftVolFloat || right != mRightVolFloat) { 4859 mLeftVolFloat = left; 4860 mRightVolFloat = right; 4861 4862 // Convert volumes from float to 8.24 4863 uint32_t vl = (uint32_t)(left * (1 << 24)); 4864 uint32_t vr = (uint32_t)(right * (1 << 24)); 4865 4866 // Delegate volume control to effect in track effect chain if needed 4867 // only one effect chain can be present on DirectOutputThread, so if 4868 // there is one, the track is connected to it 4869 if (!mEffectChains.isEmpty()) { 4870 mEffectChains[0]->setVolume_l(&vl, &vr); 4871 left = (float)vl / (1 << 24); 4872 right = (float)vr / (1 << 24); 4873 } 4874 status_t result = mOutput->stream->setVolume(left, right); 4875 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result); 4876 } 4877 } 4878 } 4879 4880 void AudioFlinger::DirectOutputThread::onAddNewTrack_l() 4881 { 4882 sp<Track> previousTrack = mPreviousTrack.promote(); 4883 sp<Track> latestTrack = mActiveTracks.getLatest(); 4884 4885 if (previousTrack != 0 && latestTrack != 0) { 4886 if (mType == DIRECT) { 4887 if (previousTrack.get() != latestTrack.get()) { 4888 mFlushPending = true; 4889 } 4890 } else /* mType == OFFLOAD */ { 4891 if (previousTrack->sessionId() != latestTrack->sessionId()) { 4892 mFlushPending = true; 4893 } 4894 } 4895 } 4896 PlaybackThread::onAddNewTrack_l(); 4897 } 4898 4899 AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l( 4900 Vector< sp<Track> > *tracksToRemove 4901 ) 4902 { 4903 size_t count = mActiveTracks.size(); 4904 mixer_state mixerStatus = MIXER_IDLE; 4905 bool doHwPause = false; 4906 bool doHwResume = false; 4907 4908 // find out which tracks need to be processed 4909 for (const sp<Track> &t : mActiveTracks) { 4910 if (t->isInvalid()) { 4911 ALOGW("An invalidated track shouldn't be in active list"); 4912 tracksToRemove->add(t); 4913 continue; 4914 } 4915 4916 Track* const track = t.get(); 4917 #ifdef VERY_VERY_VERBOSE_LOGGING 4918 audio_track_cblk_t* cblk = track->cblk(); 4919 #endif 4920 // Only consider last track started for volume and mixer state control. 4921 // In theory an older track could underrun and restart after the new one starts 4922 // but as we only care about the transition phase between two tracks on a 4923 // direct output, it is not a problem to ignore the underrun case. 4924 sp<Track> l = mActiveTracks.getLatest(); 4925 bool last = l.get() == track; 4926 4927 if (track->isPausing()) { 4928 track->setPaused(); 4929 if (mHwSupportsPause && last && !mHwPaused) { 4930 doHwPause = true; 4931 mHwPaused = true; 4932 } 4933 tracksToRemove->add(track); 4934 } else if (track->isFlushPending()) { 4935 track->flushAck(); 4936 if (last) { 4937 mFlushPending = true; 4938 } 4939 } else if (track->isResumePending()) { 4940 track->resumeAck(); 4941 if (last) { 4942 mLeftVolFloat = mRightVolFloat = -1.0; 4943 if (mHwPaused) { 4944 doHwResume = true; 4945 mHwPaused = false; 4946 } 4947 } 4948 } 4949 4950 // The first time a track is added we wait 4951 // for all its buffers to be filled before processing it. 4952 // Allow draining the buffer in case the client 4953 // app does not call stop() and relies on underrun to stop: 4954 // hence the test on (track->mRetryCount > 1). 4955 // If retryCount<=1 then track is about to underrun and be removed. 4956 // Do not use a high threshold for compressed audio. 4957 uint32_t minFrames; 4958 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing() 4959 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) { 4960 minFrames = mNormalFrameCount; 4961 } else { 4962 minFrames = 1; 4963 } 4964 4965 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() && 4966 !track->isStopping_2() && !track->isStopped()) 4967 { 4968 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer); 4969 4970 if (track->mFillingUpStatus == Track::FS_FILLED) { 4971 track->mFillingUpStatus = Track::FS_ACTIVE; 4972 if (last) { 4973 // make sure processVolume_l() will apply new volume even if 0 4974 mLeftVolFloat = mRightVolFloat = -1.0; 4975 } 4976 if (!mHwSupportsPause) { 4977 track->resumeAck(); 4978 } 4979 } 4980 4981 // compute volume for this track 4982 processVolume_l(track, last); 4983 if (last) { 4984 sp<Track> previousTrack = mPreviousTrack.promote(); 4985 if (previousTrack != 0) { 4986 if (track != previousTrack.get()) { 4987 // Flush any data still being written from last track 4988 mBytesRemaining = 0; 4989 // Invalidate previous track to force a seek when resuming. 4990 previousTrack->invalidate(); 4991 } 4992 } 4993 mPreviousTrack = track; 4994 4995 // reset retry count 4996 track->mRetryCount = kMaxTrackRetriesDirect; 4997 mActiveTrack = t; 4998 mixerStatus = MIXER_TRACKS_READY; 4999 if (mHwPaused) { 5000 doHwResume = true; 5001 mHwPaused = false; 5002 } 5003 } 5004 } else { 5005 // clear effect chain input buffer if the last active track started underruns 5006 // to avoid sending previous audio buffer again to effects 5007 if (!mEffectChains.isEmpty() && last) { 5008 mEffectChains[0]->clearInputBuffer(); 5009 } 5010 if (track->isStopping_1()) { 5011 track->mState = TrackBase::STOPPING_2; 5012 if (last && mHwPaused) { 5013 doHwResume = true; 5014 mHwPaused = false; 5015 } 5016 } 5017 if ((track->sharedBuffer() != 0) || track->isStopped() || 5018 track->isStopping_2() || track->isPaused()) { 5019 // We have consumed all the buffers of this track. 5020 // Remove it from the list of active tracks. 5021 size_t audioHALFrames; 5022 if (audio_has_proportional_frames(mFormat)) { 5023 audioHALFrames = (latency_l() * mSampleRate) / 1000; 5024 } else { 5025 audioHALFrames = 0; 5026 } 5027 5028 int64_t framesWritten = mBytesWritten / mFrameSize; 5029 if (mStandby || !last || 5030 track->presentationComplete(framesWritten, audioHALFrames)) { 5031 if (track->isStopping_2()) { 5032 track->mState = TrackBase::STOPPED; 5033 } 5034 if (track->isStopped()) { 5035 track->reset(); 5036 } 5037 tracksToRemove->add(track); 5038 } 5039 } else { 5040 // No buffers for this track. Give it a few chances to 5041 // fill a buffer, then remove it from active list. 5042 // Only consider last track started for mixer state control 5043 if (--(track->mRetryCount) <= 0) { 5044 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name()); 5045 tracksToRemove->add(track); 5046 // indicate to client process that the track was disabled because of underrun; 5047 // it will then automatically call start() when data is available 5048 track->disable(); 5049 } else if (last) { 5050 ALOGW("pause because of UNDERRUN, framesReady = %zu," 5051 "minFrames = %u, mFormat = %#x", 5052 track->framesReady(), minFrames, mFormat); 5053 mixerStatus = MIXER_TRACKS_ENABLED; 5054 if (mHwSupportsPause && !mHwPaused && !mStandby) { 5055 doHwPause = true; 5056 mHwPaused = true; 5057 } 5058 } 5059 } 5060 } 5061 } 5062 5063 // if an active track did not command a flush, check for pending flush on stopped tracks 5064 if (!mFlushPending) { 5065 for (size_t i = 0; i < mTracks.size(); i++) { 5066 if (mTracks[i]->isFlushPending()) { 5067 mTracks[i]->flushAck(); 5068 mFlushPending = true; 5069 } 5070 } 5071 } 5072 5073 // make sure the pause/flush/resume sequence is executed in the right order. 5074 // If a flush is pending and a track is active but the HW is not paused, force a HW pause 5075 // before flush and then resume HW. This can happen in case of pause/flush/resume 5076 // if resume is received before pause is executed. 5077 if (mHwSupportsPause && !mStandby && 5078 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) { 5079 status_t result = mOutput->stream->pause(); 5080 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result); 5081 } 5082 if (mFlushPending) { 5083 flushHw_l(); 5084 } 5085 if (mHwSupportsPause && !mStandby && doHwResume) { 5086 status_t result = mOutput->stream->resume(); 5087 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result); 5088 } 5089 // remove all the tracks that need to be... 5090 removeTracks_l(*tracksToRemove); 5091 5092 return mixerStatus; 5093 } 5094 5095 void AudioFlinger::DirectOutputThread::threadLoop_mix() 5096 { 5097 size_t frameCount = mFrameCount; 5098 int8_t *curBuf = (int8_t *)mSinkBuffer; 5099 // output audio to hardware 5100 while (frameCount) { 5101 AudioBufferProvider::Buffer buffer; 5102 buffer.frameCount = frameCount; 5103 status_t status = mActiveTrack->getNextBuffer(&buffer); 5104 if (status != NO_ERROR || buffer.raw == NULL) { 5105 // no need to pad with 0 for compressed audio 5106 if (audio_has_proportional_frames(mFormat)) { 5107 memset(curBuf, 0, frameCount * mFrameSize); 5108 } 5109 break; 5110 } 5111 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize); 5112 frameCount -= buffer.frameCount; 5113 curBuf += buffer.frameCount * mFrameSize; 5114 mActiveTrack->releaseBuffer(&buffer); 5115 } 5116 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer; 5117 mSleepTimeUs = 0; 5118 mStandbyTimeNs = systemTime() + mStandbyDelayNs; 5119 mActiveTrack.clear(); 5120 } 5121 5122 void AudioFlinger::DirectOutputThread::threadLoop_sleepTime() 5123 { 5124 // do not write to HAL when paused 5125 if (mHwPaused || (usesHwAvSync() && mStandby)) { 5126 mSleepTimeUs = mIdleSleepTimeUs; 5127 return; 5128 } 5129 if (mSleepTimeUs == 0) { 5130 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 5131 mSleepTimeUs = mActiveSleepTimeUs; 5132 } else { 5133 mSleepTimeUs = mIdleSleepTimeUs; 5134 } 5135 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) { 5136 memset(mSinkBuffer, 0, mFrameCount * mFrameSize); 5137 mSleepTimeUs = 0; 5138 } 5139 } 5140 5141 void AudioFlinger::DirectOutputThread::threadLoop_exit() 5142 { 5143 { 5144 Mutex::Autolock _l(mLock); 5145 for (size_t i = 0; i < mTracks.size(); i++) { 5146 if (mTracks[i]->isFlushPending()) { 5147 mTracks[i]->flushAck(); 5148 mFlushPending = true; 5149 } 5150 } 5151 if (mFlushPending) { 5152 flushHw_l(); 5153 } 5154 } 5155 PlaybackThread::threadLoop_exit(); 5156 } 5157 5158 // must be called with thread mutex locked 5159 bool AudioFlinger::DirectOutputThread::shouldStandby_l() 5160 { 5161 bool trackPaused = false; 5162 bool trackStopped = false; 5163 5164 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) { 5165 return !mStandby; 5166 } 5167 5168 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack 5169 // after a timeout and we will enter standby then. 5170 if (mTracks.size() > 0) { 5171 trackPaused = mTracks[mTracks.size() - 1]->isPaused(); 5172 trackStopped = mTracks[mTracks.size() - 1]->isStopped() || 5173 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE; 5174 } 5175 5176 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped)); 5177 } 5178 5179 // getTrackName_l() must be called with ThreadBase::mLock held 5180 int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused, 5181 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid) 5182 { 5183 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) { 5184 return -1; 5185 } 5186 return 0; 5187 } 5188 5189 // deleteTrackName_l() must be called with ThreadBase::mLock held 5190 void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused) 5191 { 5192 } 5193 5194 // checkForNewParameter_l() must be called with ThreadBase::mLock held 5195 bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair, 5196 status_t& status) 5197 { 5198 bool reconfig = false; 5199 bool a2dpDeviceChanged = false; 5200 5201 status = NO_ERROR; 5202 5203 AudioParameter param = AudioParameter(keyValuePair); 5204 int value; 5205 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 5206 // forward device change to effects that have requested to be 5207 // aware of attached audio device. 5208 if (value != AUDIO_DEVICE_NONE) { 5209 a2dpDeviceChanged = 5210 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP); 5211 mOutDevice = value; 5212 for (size_t i = 0; i < mEffectChains.size(); i++) { 5213 mEffectChains[i]->setDevice_l(mOutDevice); 5214 } 5215 } 5216 } 5217 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 5218 // do not accept frame count changes if tracks are open as the track buffer 5219 // size depends on frame count and correct behavior would not be garantied 5220 // if frame count is changed after track creation 5221 if (!mTracks.isEmpty()) { 5222 status = INVALID_OPERATION; 5223 } else { 5224 reconfig = true; 5225 } 5226 } 5227 if (status == NO_ERROR) { 5228 status = mOutput->stream->setParameters(keyValuePair); 5229 if (!mStandby && status == INVALID_OPERATION) { 5230 mOutput->standby(); 5231 mStandby = true; 5232 mBytesWritten = 0; 5233 status = mOutput->stream->setParameters(keyValuePair); 5234 } 5235 if (status == NO_ERROR && reconfig) { 5236 readOutputParameters_l(); 5237 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED); 5238 } 5239 } 5240 5241 return reconfig || a2dpDeviceChanged; 5242 } 5243 5244 uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const 5245 { 5246 uint32_t time; 5247 if (audio_has_proportional_frames(mFormat)) { 5248 time = PlaybackThread::activeSleepTimeUs(); 5249 } else { 5250 time = kDirectMinSleepTimeUs; 5251 } 5252 return time; 5253 } 5254 5255 uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const 5256 { 5257 uint32_t time; 5258 if (audio_has_proportional_frames(mFormat)) { 5259 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2; 5260 } else { 5261 time = kDirectMinSleepTimeUs; 5262 } 5263 return time; 5264 } 5265 5266 uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const 5267 { 5268 uint32_t time; 5269 if (audio_has_proportional_frames(mFormat)) { 5270 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000); 5271 } else { 5272 time = kDirectMinSleepTimeUs; 5273 } 5274 return time; 5275 } 5276 5277 void AudioFlinger::DirectOutputThread::cacheParameters_l() 5278 { 5279 PlaybackThread::cacheParameters_l(); 5280 5281 // use shorter standby delay as on normal output to release 5282 // hardware resources as soon as possible 5283 // no delay on outputs with HW A/V sync 5284 if (usesHwAvSync()) { 5285 mStandbyDelayNs = 0; 5286 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) { 5287 mStandbyDelayNs = kOffloadStandbyDelayNs; 5288 } else { 5289 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2); 5290 } 5291 } 5292 5293 void AudioFlinger::DirectOutputThread::flushHw_l() 5294 { 5295 mOutput->flush(); 5296 mHwPaused = false; 5297 mFlushPending = false; 5298 } 5299 5300 int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const { 5301 // If a VolumeShaper is active, we must wake up periodically to update volume. 5302 const int64_t NS_PER_MS = 1000000; 5303 return mVolumeShaperActive ? 5304 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l(); 5305 } 5306 5307 // ---------------------------------------------------------------------------- 5308 5309 AudioFlinger::AsyncCallbackThread::AsyncCallbackThread( 5310 const wp<AudioFlinger::PlaybackThread>& playbackThread) 5311 : Thread(false /*canCallJava*/), 5312 mPlaybackThread(playbackThread), 5313 mWriteAckSequence(0), 5314 mDrainSequence(0), 5315 mAsyncError(false) 5316 { 5317 } 5318 5319 AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread() 5320 { 5321 } 5322 5323 void AudioFlinger::AsyncCallbackThread::onFirstRef() 5324 { 5325 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO); 5326 } 5327 5328 bool AudioFlinger::AsyncCallbackThread::threadLoop() 5329 { 5330 while (!exitPending()) { 5331 uint32_t writeAckSequence; 5332 uint32_t drainSequence; 5333 bool asyncError; 5334 5335 { 5336 Mutex::Autolock _l(mLock); 5337 while (!((mWriteAckSequence & 1) || 5338 (mDrainSequence & 1) || 5339 mAsyncError || 5340 exitPending())) { 5341 mWaitWorkCV.wait(mLock); 5342 } 5343 5344 if (exitPending()) { 5345 break; 5346 } 5347 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d", 5348 mWriteAckSequence, mDrainSequence); 5349 writeAckSequence = mWriteAckSequence; 5350 mWriteAckSequence &= ~1; 5351 drainSequence = mDrainSequence; 5352 mDrainSequence &= ~1; 5353 asyncError = mAsyncError; 5354 mAsyncError = false; 5355 } 5356 { 5357 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote(); 5358 if (playbackThread != 0) { 5359 if (writeAckSequence & 1) { 5360 playbackThread->resetWriteBlocked(writeAckSequence >> 1); 5361 } 5362 if (drainSequence & 1) { 5363 playbackThread->resetDraining(drainSequence >> 1); 5364 } 5365 if (asyncError) { 5366 playbackThread->onAsyncError(); 5367 } 5368 } 5369 } 5370 } 5371 return false; 5372 } 5373 5374 void AudioFlinger::AsyncCallbackThread::exit() 5375 { 5376 ALOGV("AsyncCallbackThread::exit"); 5377 Mutex::Autolock _l(mLock); 5378 requestExit(); 5379 mWaitWorkCV.broadcast(); 5380 } 5381 5382 void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence) 5383 { 5384 Mutex::Autolock _l(mLock); 5385 // bit 0 is cleared 5386 mWriteAckSequence = sequence << 1; 5387 } 5388 5389 void AudioFlinger::AsyncCallbackThread::resetWriteBlocked() 5390 { 5391 Mutex::Autolock _l(mLock); 5392 // ignore unexpected callbacks 5393 if (mWriteAckSequence & 2) { 5394 mWriteAckSequence |= 1; 5395 mWaitWorkCV.signal(); 5396 } 5397 } 5398 5399 void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence) 5400 { 5401 Mutex::Autolock _l(mLock); 5402 // bit 0 is cleared 5403 mDrainSequence = sequence << 1; 5404 } 5405 5406 void AudioFlinger::AsyncCallbackThread::resetDraining() 5407 { 5408 Mutex::Autolock _l(mLock); 5409 // ignore unexpected callbacks 5410 if (mDrainSequence & 2) { 5411 mDrainSequence |= 1; 5412 mWaitWorkCV.signal(); 5413 } 5414 } 5415 5416 void AudioFlinger::AsyncCallbackThread::setAsyncError() 5417 { 5418 Mutex::Autolock _l(mLock); 5419 mAsyncError = true; 5420 mWaitWorkCV.signal(); 5421 } 5422 5423 5424 // ---------------------------------------------------------------------------- 5425 AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger, 5426 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady) 5427 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady), 5428 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true), 5429 mOffloadUnderrunPosition(~0LL) 5430 { 5431 //FIXME: mStandby should be set to true by ThreadBase constructor 5432 mStandby = true; 5433 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */); 5434 } 5435 5436 void AudioFlinger::OffloadThread::threadLoop_exit() 5437 { 5438 if (mFlushPending || mHwPaused) { 5439 // If a flush is pending or track was paused, just discard buffered data 5440 flushHw_l(); 5441 } else { 5442 mMixerStatus = MIXER_DRAIN_ALL; 5443 threadLoop_drain(); 5444 } 5445 if (mUseAsyncWrite) { 5446 ALOG_ASSERT(mCallbackThread != 0); 5447 mCallbackThread->exit(); 5448 } 5449 PlaybackThread::threadLoop_exit(); 5450 } 5451 5452 AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l( 5453 Vector< sp<Track> > *tracksToRemove 5454 ) 5455 { 5456 size_t count = mActiveTracks.size(); 5457 5458 mixer_state mixerStatus = MIXER_IDLE; 5459 bool doHwPause = false; 5460 bool doHwResume = false; 5461 5462 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count); 5463 5464 // find out which tracks need to be processed 5465 for (const sp<Track> &t : mActiveTracks) { 5466 Track* const track = t.get(); 5467 #ifdef VERY_VERY_VERBOSE_LOGGING 5468 audio_track_cblk_t* cblk = track->cblk(); 5469 #endif 5470 // Only consider last track started for volume and mixer state control. 5471 // In theory an older track could underrun and restart after the new one starts 5472 // but as we only care about the transition phase between two tracks on a 5473 // direct output, it is not a problem to ignore the underrun case. 5474 sp<Track> l = mActiveTracks.getLatest(); 5475 bool last = l.get() == track; 5476 5477 if (track->isInvalid()) { 5478 ALOGW("An invalidated track shouldn't be in active list"); 5479 tracksToRemove->add(track); 5480 continue; 5481 } 5482 5483 if (track->mState == TrackBase::IDLE) { 5484 ALOGW("An idle track shouldn't be in active list"); 5485 continue; 5486 } 5487 5488 if (track->isPausing()) { 5489 track->setPaused(); 5490 if (last) { 5491 if (mHwSupportsPause && !mHwPaused) { 5492 doHwPause = true; 5493 mHwPaused = true; 5494 } 5495 // If we were part way through writing the mixbuffer to 5496 // the HAL we must save this until we resume 5497 // BUG - this will be wrong if a different track is made active, 5498 // in that case we want to discard the pending data in the 5499 // mixbuffer and tell the client to present it again when the 5500 // track is resumed 5501 mPausedWriteLength = mCurrentWriteLength; 5502 mPausedBytesRemaining = mBytesRemaining; 5503 mBytesRemaining = 0; // stop writing 5504 } 5505 tracksToRemove->add(track); 5506 } else if (track->isFlushPending()) { 5507 if (track->isStopping_1()) { 5508 track->mRetryCount = kMaxTrackStopRetriesOffload; 5509 } else { 5510 track->mRetryCount = kMaxTrackRetriesOffload; 5511 } 5512 track->flushAck(); 5513 if (last) { 5514 mFlushPending = true; 5515 } 5516 } else if (track->isResumePending()){ 5517 track->resumeAck(); 5518 if (last) { 5519 if (mPausedBytesRemaining) { 5520 // Need to continue write that was interrupted 5521 mCurrentWriteLength = mPausedWriteLength; 5522 mBytesRemaining = mPausedBytesRemaining; 5523 mPausedBytesRemaining = 0; 5524 } 5525 if (mHwPaused) { 5526 doHwResume = true; 5527 mHwPaused = false; 5528 // threadLoop_mix() will handle the case that we need to 5529 // resume an interrupted write 5530 } 5531 // enable write to audio HAL 5532 mSleepTimeUs = 0; 5533 5534 mLeftVolFloat = mRightVolFloat = -1.0; 5535 5536 // Do not handle new data in this iteration even if track->framesReady() 5537 mixerStatus = MIXER_TRACKS_ENABLED; 5538 } 5539 } else if (track->framesReady() && track->isReady() && 5540 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) { 5541 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer); 5542 if (track->mFillingUpStatus == Track::FS_FILLED) { 5543 track->mFillingUpStatus = Track::FS_ACTIVE; 5544 if (last) { 5545 // make sure processVolume_l() will apply new volume even if 0 5546 mLeftVolFloat = mRightVolFloat = -1.0; 5547 } 5548 } 5549 5550 if (last) { 5551 sp<Track> previousTrack = mPreviousTrack.promote(); 5552 if (previousTrack != 0) { 5553 if (track != previousTrack.get()) { 5554 // Flush any data still being written from last track 5555 mBytesRemaining = 0; 5556 if (mPausedBytesRemaining) { 5557 // Last track was paused so we also need to flush saved 5558 // mixbuffer state and invalidate track so that it will 5559 // re-submit that unwritten data when it is next resumed 5560 mPausedBytesRemaining = 0; 5561 // Invalidate is a bit drastic - would be more efficient 5562 // to have a flag to tell client that some of the 5563 // previously written data was lost 5564 previousTrack->invalidate(); 5565 } 5566 // flush data already sent to the DSP if changing audio session as audio 5567 // comes from a different source. Also invalidate previous track to force a 5568 // seek when resuming. 5569 if (previousTrack->sessionId() != track->sessionId()) { 5570 previousTrack->invalidate(); 5571 } 5572 } 5573 } 5574 mPreviousTrack = track; 5575 // reset retry count 5576 if (track->isStopping_1()) { 5577 track->mRetryCount = kMaxTrackStopRetriesOffload; 5578 } else { 5579 track->mRetryCount = kMaxTrackRetriesOffload; 5580 } 5581 mActiveTrack = t; 5582 mixerStatus = MIXER_TRACKS_READY; 5583 } 5584 } else { 5585 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer); 5586 if (track->isStopping_1()) { 5587 if (--(track->mRetryCount) <= 0) { 5588 // Hardware buffer can hold a large amount of audio so we must 5589 // wait for all current track's data to drain before we say 5590 // that the track is stopped. 5591 if (mBytesRemaining == 0) { 5592 // Only start draining when all data in mixbuffer 5593 // has been written 5594 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2"); 5595 track->mState = TrackBase::STOPPING_2; // so presentation completes after 5596 // drain do not drain if no data was ever sent to HAL (mStandby == true) 5597 if (last && !mStandby) { 5598 // do not modify drain sequence if we are already draining. This happens 5599 // when resuming from pause after drain. 5600 if ((mDrainSequence & 1) == 0) { 5601 mSleepTimeUs = 0; 5602 mStandbyTimeNs = systemTime() + mStandbyDelayNs; 5603 mixerStatus = MIXER_DRAIN_TRACK; 5604 mDrainSequence += 2; 5605 } 5606 if (mHwPaused) { 5607 // It is possible to move from PAUSED to STOPPING_1 without 5608 // a resume so we must ensure hardware is running 5609 doHwResume = true; 5610 mHwPaused = false; 5611 } 5612 } 5613 } 5614 } else if (last) { 5615 ALOGV("stopping1 underrun retries left %d", track->mRetryCount); 5616 mixerStatus = MIXER_TRACKS_ENABLED; 5617 } 5618 } else if (track->isStopping_2()) { 5619 // Drain has completed or we are in standby, signal presentation complete 5620 if (!(mDrainSequence & 1) || !last || mStandby) { 5621 track->mState = TrackBase::STOPPED; 5622 uint32_t latency = 0; 5623 status_t result = mOutput->stream->getLatency(&latency); 5624 ALOGE_IF(result != OK, 5625 "Error when retrieving output stream latency: %d", result); 5626 size_t audioHALFrames = (latency * mSampleRate) / 1000; 5627 int64_t framesWritten = 5628 mBytesWritten / mOutput->getFrameSize(); 5629 track->presentationComplete(framesWritten, audioHALFrames); 5630 track->reset(); 5631 tracksToRemove->add(track); 5632 } 5633 } else { 5634 // No buffers for this track. Give it a few chances to 5635 // fill a buffer, then remove it from active list. 5636 if (--(track->mRetryCount) <= 0) { 5637 bool running = false; 5638 uint64_t position = 0; 5639 struct timespec unused; 5640 // The running check restarts the retry counter at least once. 5641 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused); 5642 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) { 5643 running = true; 5644 mOffloadUnderrunPosition = position; 5645 } 5646 if (ret == NO_ERROR) { 5647 ALOGVV("underrun counter, running(%d): %lld vs %lld", running, 5648 (long long)position, (long long)mOffloadUnderrunPosition); 5649 } 5650 if (running) { // still running, give us more time. 5651 track->mRetryCount = kMaxTrackRetriesOffload; 5652 } else { 5653 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list", 5654 track->name()); 5655 tracksToRemove->add(track); 5656 // tell client process that the track was disabled because of underrun; 5657 // it will then automatically call start() when data is available 5658 track->disable(); 5659 } 5660 } else if (last){ 5661 mixerStatus = MIXER_TRACKS_ENABLED; 5662 } 5663 } 5664 } 5665 // compute volume for this track 5666 processVolume_l(track, last); 5667 } 5668 5669 // make sure the pause/flush/resume sequence is executed in the right order. 5670 // If a flush is pending and a track is active but the HW is not paused, force a HW pause 5671 // before flush and then resume HW. This can happen in case of pause/flush/resume 5672 // if resume is received before pause is executed. 5673 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) { 5674 status_t result = mOutput->stream->pause(); 5675 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result); 5676 } 5677 if (mFlushPending) { 5678 flushHw_l(); 5679 } 5680 if (!mStandby && doHwResume) { 5681 status_t result = mOutput->stream->resume(); 5682 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result); 5683 } 5684 5685 // remove all the tracks that need to be... 5686 removeTracks_l(*tracksToRemove); 5687 5688 return mixerStatus; 5689 } 5690 5691 // must be called with thread mutex locked 5692 bool AudioFlinger::OffloadThread::waitingAsyncCallback_l() 5693 { 5694 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d", 5695 mWriteAckSequence, mDrainSequence); 5696 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) { 5697 return true; 5698 } 5699 return false; 5700 } 5701 5702 bool AudioFlinger::OffloadThread::waitingAsyncCallback() 5703 { 5704 Mutex::Autolock _l(mLock); 5705 return waitingAsyncCallback_l(); 5706 } 5707 5708 void AudioFlinger::OffloadThread::flushHw_l() 5709 { 5710 DirectOutputThread::flushHw_l(); 5711 // Flush anything still waiting in the mixbuffer 5712 mCurrentWriteLength = 0; 5713 mBytesRemaining = 0; 5714 mPausedWriteLength = 0; 5715 mPausedBytesRemaining = 0; 5716 // reset bytes written count to reflect that DSP buffers are empty after flush. 5717 mBytesWritten = 0; 5718 mOffloadUnderrunPosition = ~0LL; 5719 5720 if (mUseAsyncWrite) { 5721 // discard any pending drain or write ack by incrementing sequence 5722 mWriteAckSequence = (mWriteAckSequence + 2) & ~1; 5723 mDrainSequence = (mDrainSequence + 2) & ~1; 5724 ALOG_ASSERT(mCallbackThread != 0); 5725 mCallbackThread->setWriteBlocked(mWriteAckSequence); 5726 mCallbackThread->setDraining(mDrainSequence); 5727 } 5728 } 5729 5730 void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType) 5731 { 5732 Mutex::Autolock _l(mLock); 5733 if (PlaybackThread::invalidateTracks_l(streamType)) { 5734 mFlushPending = true; 5735 } 5736 } 5737 5738 // ---------------------------------------------------------------------------- 5739 5740 AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, 5741 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady) 5742 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(), 5743 systemReady, DUPLICATING), 5744 mWaitTimeMs(UINT_MAX) 5745 { 5746 addOutputTrack(mainThread); 5747 } 5748 5749 AudioFlinger::DuplicatingThread::~DuplicatingThread() 5750 { 5751 for (size_t i = 0; i < mOutputTracks.size(); i++) { 5752 mOutputTracks[i]->destroy(); 5753 } 5754 } 5755 5756 void AudioFlinger::DuplicatingThread::threadLoop_mix() 5757 { 5758 // mix buffers... 5759 if (outputsReady(outputTracks)) { 5760 mAudioMixer->process(); 5761 } else { 5762 if (mMixerBufferValid) { 5763 memset(mMixerBuffer, 0, mMixerBufferSize); 5764 } else { 5765 memset(mSinkBuffer, 0, mSinkBufferSize); 5766 } 5767 } 5768 mSleepTimeUs = 0; 5769 writeFrames = mNormalFrameCount; 5770 mCurrentWriteLength = mSinkBufferSize; 5771 mStandbyTimeNs = systemTime() + mStandbyDelayNs; 5772 } 5773 5774 void AudioFlinger::DuplicatingThread::threadLoop_sleepTime() 5775 { 5776 if (mSleepTimeUs == 0) { 5777 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 5778 mSleepTimeUs = mActiveSleepTimeUs; 5779 } else { 5780 mSleepTimeUs = mIdleSleepTimeUs; 5781 } 5782 } else if (mBytesWritten != 0) { 5783 if (mMixerStatus == MIXER_TRACKS_ENABLED) { 5784 writeFrames = mNormalFrameCount; 5785 memset(mSinkBuffer, 0, mSinkBufferSize); 5786 } else { 5787 // flush remaining overflow buffers in output tracks 5788 writeFrames = 0; 5789 } 5790 mSleepTimeUs = 0; 5791 } 5792 } 5793 5794 ssize_t AudioFlinger::DuplicatingThread::threadLoop_write() 5795 { 5796 for (size_t i = 0; i < outputTracks.size(); i++) { 5797 outputTracks[i]->write(mSinkBuffer, writeFrames); 5798 } 5799 mStandby = false; 5800 return (ssize_t)mSinkBufferSize; 5801 } 5802 5803 void AudioFlinger::DuplicatingThread::threadLoop_standby() 5804 { 5805 // DuplicatingThread implements standby by stopping all tracks 5806 for (size_t i = 0; i < outputTracks.size(); i++) { 5807 outputTracks[i]->stop(); 5808 } 5809 } 5810 5811 void AudioFlinger::DuplicatingThread::saveOutputTracks() 5812 { 5813 outputTracks = mOutputTracks; 5814 } 5815 5816 void AudioFlinger::DuplicatingThread::clearOutputTracks() 5817 { 5818 outputTracks.clear(); 5819 } 5820 5821 void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread) 5822 { 5823 Mutex::Autolock _l(mLock); 5824 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass. 5825 // Adjust for thread->sampleRate() to determine minimum buffer frame count. 5826 // Then triple buffer because Threads do not run synchronously and may not be clock locked. 5827 const size_t frameCount = 5828 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate()); 5829 // TODO: Consider asynchronous sample rate conversion to handle clock disparity 5830 // from different OutputTracks and their associated MixerThreads (e.g. one may 5831 // nearly empty and the other may be dropping data). 5832 5833 sp<OutputTrack> outputTrack = new OutputTrack(thread, 5834 this, 5835 mSampleRate, 5836 mFormat, 5837 mChannelMask, 5838 frameCount, 5839 IPCThreadState::self()->getCallingUid()); 5840 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY; 5841 if (status != NO_ERROR) { 5842 ALOGE("addOutputTrack() initCheck failed %d", status); 5843 return; 5844 } 5845 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f); 5846 mOutputTracks.add(outputTrack); 5847 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread); 5848 updateWaitTime_l(); 5849 } 5850 5851 void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread) 5852 { 5853 Mutex::Autolock _l(mLock); 5854 for (size_t i = 0; i < mOutputTracks.size(); i++) { 5855 if (mOutputTracks[i]->thread() == thread) { 5856 mOutputTracks[i]->destroy(); 5857 mOutputTracks.removeAt(i); 5858 updateWaitTime_l(); 5859 if (thread->getOutput() == mOutput) { 5860 mOutput = NULL; 5861 } 5862 return; 5863 } 5864 } 5865 ALOGV("removeOutputTrack(): unknown thread: %p", thread); 5866 } 5867 5868 // caller must hold mLock 5869 void AudioFlinger::DuplicatingThread::updateWaitTime_l() 5870 { 5871 mWaitTimeMs = UINT_MAX; 5872 for (size_t i = 0; i < mOutputTracks.size(); i++) { 5873 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote(); 5874 if (strong != 0) { 5875 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate(); 5876 if (waitTimeMs < mWaitTimeMs) { 5877 mWaitTimeMs = waitTimeMs; 5878 } 5879 } 5880 } 5881 } 5882 5883 5884 bool AudioFlinger::DuplicatingThread::outputsReady( 5885 const SortedVector< sp<OutputTrack> > &outputTracks) 5886 { 5887 for (size_t i = 0; i < outputTracks.size(); i++) { 5888 sp<ThreadBase> thread = outputTracks[i]->thread().promote(); 5889 if (thread == 0) { 5890 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", 5891 outputTracks[i].get()); 5892 return false; 5893 } 5894 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 5895 // see note at standby() declaration 5896 if (playbackThread->standby() && !playbackThread->isSuspended()) { 5897 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), 5898 thread.get()); 5899 return false; 5900 } 5901 } 5902 return true; 5903 } 5904 5905 uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const 5906 { 5907 return (mWaitTimeMs * 1000) / 2; 5908 } 5909 5910 void AudioFlinger::DuplicatingThread::cacheParameters_l() 5911 { 5912 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first 5913 updateWaitTime_l(); 5914 5915 MixerThread::cacheParameters_l(); 5916 } 5917 5918 5919 // ---------------------------------------------------------------------------- 5920 // Record 5921 // ---------------------------------------------------------------------------- 5922 5923 AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, 5924 AudioStreamIn *input, 5925 audio_io_handle_t id, 5926 audio_devices_t outDevice, 5927 audio_devices_t inDevice, 5928 bool systemReady 5929 #ifdef TEE_SINK 5930 , const sp<NBAIO_Sink>& teeSink 5931 #endif 5932 ) : 5933 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady), 5934 mInput(input), mRsmpInBuffer(NULL), 5935 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l() 5936 mRsmpInRear(0) 5937 #ifdef TEE_SINK 5938 , mTeeSink(teeSink) 5939 #endif 5940 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize, 5941 "RecordThreadRO", MemoryHeapBase::READ_ONLY)) 5942 // mFastCapture below 5943 , mFastCaptureFutex(0) 5944 // mInputSource 5945 // mPipeSink 5946 // mPipeSource 5947 , mPipeFramesP2(0) 5948 // mPipeMemory 5949 // mFastCaptureNBLogWriter 5950 , mFastTrackAvail(false) 5951 { 5952 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id); 5953 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName); 5954 5955 readInputParameters_l(); 5956 5957 // create an NBAIO source for the HAL input stream, and negotiate 5958 mInputSource = new AudioStreamInSource(input->stream); 5959 size_t numCounterOffers = 0; 5960 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)}; 5961 #if !LOG_NDEBUG 5962 ssize_t index = 5963 #else 5964 (void) 5965 #endif 5966 mInputSource->negotiate(offers, 1, NULL, numCounterOffers); 5967 ALOG_ASSERT(index == 0); 5968 5969 // initialize fast capture depending on configuration 5970 bool initFastCapture; 5971 switch (kUseFastCapture) { 5972 case FastCapture_Never: 5973 initFastCapture = false; 5974 break; 5975 case FastCapture_Always: 5976 initFastCapture = true; 5977 break; 5978 case FastCapture_Static: 5979 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs; 5980 break; 5981 // case FastCapture_Dynamic: 5982 } 5983 5984 if (initFastCapture) { 5985 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from 5986 NBAIO_Format format = mInputSource->format(); 5987 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread 5988 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000); 5989 size_t pipeSize = pipeFramesP2 * Format_frameSize(format); 5990 void *pipeBuffer; 5991 const sp<MemoryDealer> roHeap(readOnlyHeap()); 5992 sp<IMemory> pipeMemory; 5993 if ((roHeap == 0) || 5994 (pipeMemory = roHeap->allocate(pipeSize)) == 0 || 5995 (pipeBuffer = pipeMemory->pointer()) == NULL) { 5996 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize); 5997 goto failed; 5998 } 5999 // pipe will be shared directly with fast clients, so clear to avoid leaking old information 6000 memset(pipeBuffer, 0, pipeSize); 6001 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer); 6002 const NBAIO_Format offers[1] = {format}; 6003 size_t numCounterOffers = 0; 6004 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers); 6005 ALOG_ASSERT(index == 0); 6006 mPipeSink = pipe; 6007 PipeReader *pipeReader = new PipeReader(*pipe); 6008 numCounterOffers = 0; 6009 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers); 6010 ALOG_ASSERT(index == 0); 6011 mPipeSource = pipeReader; 6012 mPipeFramesP2 = pipeFramesP2; 6013 mPipeMemory = pipeMemory; 6014 6015 // create fast capture 6016 mFastCapture = new FastCapture(); 6017 FastCaptureStateQueue *sq = mFastCapture->sq(); 6018 #ifdef STATE_QUEUE_DUMP 6019 // FIXME 6020 #endif 6021 FastCaptureState *state = sq->begin(); 6022 state->mCblk = NULL; 6023 state->mInputSource = mInputSource.get(); 6024 state->mInputSourceGen++; 6025 state->mPipeSink = pipe; 6026 state->mPipeSinkGen++; 6027 state->mFrameCount = mFrameCount; 6028 state->mCommand = FastCaptureState::COLD_IDLE; 6029 // already done in constructor initialization list 6030 //mFastCaptureFutex = 0; 6031 state->mColdFutexAddr = &mFastCaptureFutex; 6032 state->mColdGen++; 6033 state->mDumpState = &mFastCaptureDumpState; 6034 #ifdef TEE_SINK 6035 // FIXME 6036 #endif 6037 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture"); 6038 state->mNBLogWriter = mFastCaptureNBLogWriter.get(); 6039 sq->end(); 6040 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED); 6041 6042 // start the fast capture 6043 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO); 6044 pid_t tid = mFastCapture->getTid(); 6045 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture, false); 6046 stream()->setHalThreadPriority(kPriorityFastCapture); 6047 #ifdef AUDIO_WATCHDOG 6048 // FIXME 6049 #endif 6050 6051 mFastTrackAvail = true; 6052 } 6053 failed: ; 6054 6055 // FIXME mNormalSource 6056 } 6057 6058 AudioFlinger::RecordThread::~RecordThread() 6059 { 6060 if (mFastCapture != 0) { 6061 FastCaptureStateQueue *sq = mFastCapture->sq(); 6062 FastCaptureState *state = sq->begin(); 6063 if (state->mCommand == FastCaptureState::COLD_IDLE) { 6064 int32_t old = android_atomic_inc(&mFastCaptureFutex); 6065 if (old == -1) { 6066 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1); 6067 } 6068 } 6069 state->mCommand = FastCaptureState::EXIT; 6070 sq->end(); 6071 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED); 6072 mFastCapture->join(); 6073 mFastCapture.clear(); 6074 } 6075 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter); 6076 mAudioFlinger->unregisterWriter(mNBLogWriter); 6077 free(mRsmpInBuffer); 6078 } 6079 6080 void AudioFlinger::RecordThread::onFirstRef() 6081 { 6082 run(mThreadName, PRIORITY_URGENT_AUDIO); 6083 } 6084 6085 void AudioFlinger::RecordThread::preExit() 6086 { 6087 ALOGV(" preExit()"); 6088 Mutex::Autolock _l(mLock); 6089 for (size_t i = 0; i < mTracks.size(); i++) { 6090 sp<RecordTrack> track = mTracks[i]; 6091 track->invalidate(); 6092 } 6093 mActiveTracks.clear(); 6094 mStartStopCond.broadcast(); 6095 } 6096 6097 bool AudioFlinger::RecordThread::threadLoop() 6098 { 6099 nsecs_t lastWarning = 0; 6100 6101 inputStandBy(); 6102 6103 reacquire_wakelock: 6104 sp<RecordTrack> activeTrack; 6105 { 6106 Mutex::Autolock _l(mLock); 6107 acquireWakeLock_l(); 6108 } 6109 6110 // used to request a deferred sleep, to be executed later while mutex is unlocked 6111 uint32_t sleepUs = 0; 6112 6113 // loop while there is work to do 6114 for (;;) { 6115 Vector< sp<EffectChain> > effectChains; 6116 6117 // activeTracks accumulates a copy of a subset of mActiveTracks 6118 Vector< sp<RecordTrack> > activeTracks; 6119 6120 // reference to the (first and only) active fast track 6121 sp<RecordTrack> fastTrack; 6122 6123 // reference to a fast track which is about to be removed 6124 sp<RecordTrack> fastTrackToRemove; 6125 6126 { // scope for mLock 6127 Mutex::Autolock _l(mLock); 6128 6129 processConfigEvents_l(); 6130 6131 // check exitPending here because checkForNewParameters_l() and 6132 // checkForNewParameters_l() can temporarily release mLock 6133 if (exitPending()) { 6134 break; 6135 } 6136 6137 // sleep with mutex unlocked 6138 if (sleepUs > 0) { 6139 ATRACE_BEGIN("sleepC"); 6140 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs)); 6141 ATRACE_END(); 6142 sleepUs = 0; 6143 continue; 6144 } 6145 6146 // if no active track(s), then standby and release wakelock 6147 size_t size = mActiveTracks.size(); 6148 if (size == 0) { 6149 standbyIfNotAlreadyInStandby(); 6150 // exitPending() can't become true here 6151 releaseWakeLock_l(); 6152 ALOGV("RecordThread: loop stopping"); 6153 // go to sleep 6154 mWaitWorkCV.wait(mLock); 6155 ALOGV("RecordThread: loop starting"); 6156 goto reacquire_wakelock; 6157 } 6158 6159 bool doBroadcast = false; 6160 bool allStopped = true; 6161 for (size_t i = 0; i < size; ) { 6162 6163 activeTrack = mActiveTracks[i]; 6164 if (activeTrack->isTerminated()) { 6165 if (activeTrack->isFastTrack()) { 6166 ALOG_ASSERT(fastTrackToRemove == 0); 6167 fastTrackToRemove = activeTrack; 6168 } 6169 removeTrack_l(activeTrack); 6170 mActiveTracks.remove(activeTrack); 6171 size--; 6172 continue; 6173 } 6174 6175 TrackBase::track_state activeTrackState = activeTrack->mState; 6176 switch (activeTrackState) { 6177 6178 case TrackBase::PAUSING: 6179 mActiveTracks.remove(activeTrack); 6180 doBroadcast = true; 6181 size--; 6182 continue; 6183 6184 case TrackBase::STARTING_1: 6185 sleepUs = 10000; 6186 i++; 6187 allStopped = false; 6188 continue; 6189 6190 case TrackBase::STARTING_2: 6191 doBroadcast = true; 6192 mStandby = false; 6193 activeTrack->mState = TrackBase::ACTIVE; 6194 allStopped = false; 6195 break; 6196 6197 case TrackBase::ACTIVE: 6198 allStopped = false; 6199 break; 6200 6201 case TrackBase::IDLE: 6202 i++; 6203 continue; 6204 6205 default: 6206 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState); 6207 } 6208 6209 activeTracks.add(activeTrack); 6210 i++; 6211 6212 if (activeTrack->isFastTrack()) { 6213 ALOG_ASSERT(!mFastTrackAvail); 6214 ALOG_ASSERT(fastTrack == 0); 6215 fastTrack = activeTrack; 6216 } 6217 } 6218 6219 mActiveTracks.updatePowerState(this); 6220 6221 if (allStopped) { 6222 standbyIfNotAlreadyInStandby(); 6223 } 6224 if (doBroadcast) { 6225 mStartStopCond.broadcast(); 6226 } 6227 6228 // sleep if there are no active tracks to process 6229 if (activeTracks.size() == 0) { 6230 if (sleepUs == 0) { 6231 sleepUs = kRecordThreadSleepUs; 6232 } 6233 continue; 6234 } 6235 sleepUs = 0; 6236 6237 lockEffectChains_l(effectChains); 6238 } 6239 6240 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0 6241 6242 size_t size = effectChains.size(); 6243 for (size_t i = 0; i < size; i++) { 6244 // thread mutex is not locked, but effect chain is locked 6245 effectChains[i]->process_l(); 6246 } 6247 6248 // Push a new fast capture state if fast capture is not already running, or cblk change 6249 if (mFastCapture != 0) { 6250 FastCaptureStateQueue *sq = mFastCapture->sq(); 6251 FastCaptureState *state = sq->begin(); 6252 bool didModify = false; 6253 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED; 6254 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME && 6255 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) { 6256 if (state->mCommand == FastCaptureState::COLD_IDLE) { 6257 int32_t old = android_atomic_inc(&mFastCaptureFutex); 6258 if (old == -1) { 6259 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1); 6260 } 6261 } 6262 state->mCommand = FastCaptureState::READ_WRITE; 6263 #if 0 // FIXME 6264 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ? 6265 FastThreadDumpState::kSamplingNforLowRamDevice : 6266 FastThreadDumpState::kSamplingN); 6267 #endif 6268 didModify = true; 6269 } 6270 audio_track_cblk_t *cblkOld = state->mCblk; 6271 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL; 6272 if (cblkNew != cblkOld) { 6273 state->mCblk = cblkNew; 6274 // block until acked if removing a fast track 6275 if (cblkOld != NULL) { 6276 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED; 6277 } 6278 didModify = true; 6279 } 6280 sq->end(didModify); 6281 if (didModify) { 6282 sq->push(block); 6283 #if 0 6284 if (kUseFastCapture == FastCapture_Dynamic) { 6285 mNormalSource = mPipeSource; 6286 } 6287 #endif 6288 } 6289 } 6290 6291 // now run the fast track destructor with thread mutex unlocked 6292 fastTrackToRemove.clear(); 6293 6294 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one. 6295 // Only the client(s) that are too slow will overrun. But if even the fastest client is too 6296 // slow, then this RecordThread will overrun by not calling HAL read often enough. 6297 // If destination is non-contiguous, first read past the nominal end of buffer, then 6298 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated. 6299 6300 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1); 6301 ssize_t framesRead; 6302 6303 // If an NBAIO source is present, use it to read the normal capture's data 6304 if (mPipeSource != 0) { 6305 size_t framesToRead = mBufferSize / mFrameSize; 6306 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2); 6307 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize, 6308 framesToRead); 6309 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of 6310 // buffer size or at least for 20ms. 6311 size_t sleepFrames = max( 6312 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000); 6313 if (framesRead <= (ssize_t) sleepFrames) { 6314 sleepUs = (sleepFrames * 1000000LL) / mSampleRate; 6315 } 6316 if (framesRead < 0) { 6317 status_t status = (status_t) framesRead; 6318 switch (status) { 6319 case OVERRUN: 6320 ALOGW("overrun on read from pipe"); 6321 framesRead = 0; 6322 break; 6323 case NEGOTIATE: 6324 ALOGE("re-negotiation is needed"); 6325 framesRead = -1; // Will cause an attempt to recover. 6326 break; 6327 default: 6328 ALOGE("unknown error %d on read from pipe", status); 6329 break; 6330 } 6331 } 6332 // otherwise use the HAL / AudioStreamIn directly 6333 } else { 6334 ATRACE_BEGIN("read"); 6335 size_t bytesRead; 6336 status_t result = mInput->stream->read( 6337 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead); 6338 ATRACE_END(); 6339 if (result < 0) { 6340 framesRead = result; 6341 } else { 6342 framesRead = bytesRead / mFrameSize; 6343 } 6344 } 6345 6346 // Update server timestamp with server stats 6347 // systemTime() is optional if the hardware supports timestamps. 6348 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead; 6349 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime(); 6350 6351 // Update server timestamp with kernel stats 6352 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) { 6353 int64_t position, time; 6354 int ret = mInput->stream->getCapturePosition(&position, &time); 6355 if (ret == NO_ERROR) { 6356 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position; 6357 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time; 6358 // Note: In general record buffers should tend to be empty in 6359 // a properly running pipeline. 6360 // 6361 // Also, it is not advantageous to call get_presentation_position during the read 6362 // as the read obtains a lock, preventing the timestamp call from executing. 6363 } 6364 } 6365 // Use this to track timestamp information 6366 // ALOGD("%s", mTimestamp.toString().c_str()); 6367 6368 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) { 6369 ALOGE("read failed: framesRead=%zd", framesRead); 6370 // Force input into standby so that it tries to recover at next read attempt 6371 inputStandBy(); 6372 sleepUs = kRecordThreadSleepUs; 6373 } 6374 if (framesRead <= 0) { 6375 goto unlock; 6376 } 6377 ALOG_ASSERT(framesRead > 0); 6378 6379 if (mTeeSink != 0) { 6380 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead); 6381 } 6382 // If destination is non-contiguous, we now correct for reading past end of buffer. 6383 { 6384 size_t part1 = mRsmpInFramesP2 - rear; 6385 if ((size_t) framesRead > part1) { 6386 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize, 6387 (framesRead - part1) * mFrameSize); 6388 } 6389 } 6390 rear = mRsmpInRear += framesRead; 6391 6392 size = activeTracks.size(); 6393 // loop over each active track 6394 for (size_t i = 0; i < size; i++) { 6395 activeTrack = activeTracks[i]; 6396 6397 // skip fast tracks, as those are handled directly by FastCapture 6398 if (activeTrack->isFastTrack()) { 6399 continue; 6400 } 6401 6402 // TODO: This code probably should be moved to RecordTrack. 6403 // TODO: Update the activeTrack buffer converter in case of reconfigure. 6404 6405 enum { 6406 OVERRUN_UNKNOWN, 6407 OVERRUN_TRUE, 6408 OVERRUN_FALSE 6409 } overrun = OVERRUN_UNKNOWN; 6410 6411 // loop over getNextBuffer to handle circular sink 6412 for (;;) { 6413 6414 activeTrack->mSink.frameCount = ~0; 6415 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink); 6416 size_t framesOut = activeTrack->mSink.frameCount; 6417 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0)); 6418 6419 // check available frames and handle overrun conditions 6420 // if the record track isn't draining fast enough. 6421 bool hasOverrun; 6422 size_t framesIn; 6423 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun); 6424 if (hasOverrun) { 6425 overrun = OVERRUN_TRUE; 6426 } 6427 if (framesOut == 0 || framesIn == 0) { 6428 break; 6429 } 6430 6431 // Don't allow framesOut to be larger than what is possible with resampling 6432 // from framesIn. 6433 // This isn't strictly necessary but helps limit buffer resizing in 6434 // RecordBufferConverter. TODO: remove when no longer needed. 6435 framesOut = min(framesOut, 6436 destinationFramesPossible( 6437 framesIn, mSampleRate, activeTrack->mSampleRate)); 6438 // process frames from the RecordThread buffer provider to the RecordTrack buffer 6439 framesOut = activeTrack->mRecordBufferConverter->convert( 6440 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut); 6441 6442 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) { 6443 overrun = OVERRUN_FALSE; 6444 } 6445 6446 if (activeTrack->mFramesToDrop == 0) { 6447 if (framesOut > 0) { 6448 activeTrack->mSink.frameCount = framesOut; 6449 activeTrack->releaseBuffer(&activeTrack->mSink); 6450 } 6451 } else { 6452 // FIXME could do a partial drop of framesOut 6453 if (activeTrack->mFramesToDrop > 0) { 6454 activeTrack->mFramesToDrop -= framesOut; 6455 if (activeTrack->mFramesToDrop <= 0) { 6456 activeTrack->clearSyncStartEvent(); 6457 } 6458 } else { 6459 activeTrack->mFramesToDrop += framesOut; 6460 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 || 6461 activeTrack->mSyncStartEvent->isCancelled()) { 6462 ALOGW("Synced record %s, session %d, trigger session %d", 6463 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled", 6464 activeTrack->sessionId(), 6465 (activeTrack->mSyncStartEvent != 0) ? 6466 activeTrack->mSyncStartEvent->triggerSession() : 6467 AUDIO_SESSION_NONE); 6468 activeTrack->clearSyncStartEvent(); 6469 } 6470 } 6471 } 6472 6473 if (framesOut == 0) { 6474 break; 6475 } 6476 } 6477 6478 switch (overrun) { 6479 case OVERRUN_TRUE: 6480 // client isn't retrieving buffers fast enough 6481 if (!activeTrack->setOverflow()) { 6482 nsecs_t now = systemTime(); 6483 // FIXME should lastWarning per track? 6484 if ((now - lastWarning) > kWarningThrottleNs) { 6485 ALOGW("RecordThread: buffer overflow"); 6486 lastWarning = now; 6487 } 6488 } 6489 break; 6490 case OVERRUN_FALSE: 6491 activeTrack->clearOverflow(); 6492 break; 6493 case OVERRUN_UNKNOWN: 6494 break; 6495 } 6496 6497 // update frame information and push timestamp out 6498 activeTrack->updateTrackFrameInfo( 6499 activeTrack->mServerProxy->framesReleased(), 6500 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER], 6501 mSampleRate, mTimestamp); 6502 } 6503 6504 unlock: 6505 // enable changes in effect chain 6506 unlockEffectChains(effectChains); 6507 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end 6508 } 6509 6510 standbyIfNotAlreadyInStandby(); 6511 6512 { 6513 Mutex::Autolock _l(mLock); 6514 for (size_t i = 0; i < mTracks.size(); i++) { 6515 sp<RecordTrack> track = mTracks[i]; 6516 track->invalidate(); 6517 } 6518 mActiveTracks.clear(); 6519 mStartStopCond.broadcast(); 6520 } 6521 6522 releaseWakeLock(); 6523 6524 ALOGV("RecordThread %p exiting", this); 6525 return false; 6526 } 6527 6528 void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby() 6529 { 6530 if (!mStandby) { 6531 inputStandBy(); 6532 mStandby = true; 6533 } 6534 } 6535 6536 void AudioFlinger::RecordThread::inputStandBy() 6537 { 6538 // Idle the fast capture if it's currently running 6539 if (mFastCapture != 0) { 6540 FastCaptureStateQueue *sq = mFastCapture->sq(); 6541 FastCaptureState *state = sq->begin(); 6542 if (!(state->mCommand & FastCaptureState::IDLE)) { 6543 state->mCommand = FastCaptureState::COLD_IDLE; 6544 state->mColdFutexAddr = &mFastCaptureFutex; 6545 state->mColdGen++; 6546 mFastCaptureFutex = 0; 6547 sq->end(); 6548 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now 6549 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED); 6550 #if 0 6551 if (kUseFastCapture == FastCapture_Dynamic) { 6552 // FIXME 6553 } 6554 #endif 6555 #ifdef AUDIO_WATCHDOG 6556 // FIXME 6557 #endif 6558 } else { 6559 sq->end(false /*didModify*/); 6560 } 6561 } 6562 status_t result = mInput->stream->standby(); 6563 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result); 6564 6565 // If going into standby, flush the pipe source. 6566 if (mPipeSource.get() != nullptr) { 6567 const ssize_t flushed = mPipeSource->flush(); 6568 if (flushed > 0) { 6569 ALOGV("Input standby flushed PipeSource %zd frames", flushed); 6570 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed; 6571 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime(); 6572 } 6573 } 6574 } 6575 6576 // RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held 6577 sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l( 6578 const sp<AudioFlinger::Client>& client, 6579 uint32_t sampleRate, 6580 audio_format_t format, 6581 audio_channel_mask_t channelMask, 6582 size_t *pFrameCount, 6583 audio_session_t sessionId, 6584 size_t *notificationFrames, 6585 uid_t uid, 6586 audio_input_flags_t *flags, 6587 pid_t tid, 6588 status_t *status, 6589 audio_port_handle_t portId) 6590 { 6591 size_t frameCount = *pFrameCount; 6592 sp<RecordTrack> track; 6593 status_t lStatus; 6594 audio_input_flags_t inputFlags = mInput->flags; 6595 6596 // special case for FAST flag considered OK if fast capture is present 6597 if (hasFastCapture()) { 6598 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST); 6599 } 6600 6601 // Check if requested flags are compatible with output stream flags 6602 if ((*flags & inputFlags) != *flags) { 6603 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and" 6604 " input flags (%08x)", 6605 *flags, inputFlags); 6606 *flags = (audio_input_flags_t)(*flags & inputFlags); 6607 } 6608 6609 // client expresses a preference for FAST, but we get the final say 6610 if (*flags & AUDIO_INPUT_FLAG_FAST) { 6611 if ( 6612 // we formerly checked for a callback handler (non-0 tid), 6613 // but that is no longer required for TRANSFER_OBTAIN mode 6614 // 6615 // frame count is not specified, or is exactly the pipe depth 6616 ((frameCount == 0) || (frameCount == mPipeFramesP2)) && 6617 // PCM data 6618 audio_is_linear_pcm(format) && 6619 // hardware format 6620 (format == mFormat) && 6621 // hardware channel mask 6622 (channelMask == mChannelMask) && 6623 // hardware sample rate 6624 (sampleRate == mSampleRate) && 6625 // record thread has an associated fast capture 6626 hasFastCapture() && 6627 // there are sufficient fast track slots available 6628 mFastTrackAvail 6629 ) { 6630 // check compatibility with audio effects. 6631 Mutex::Autolock _l(mLock); 6632 // Do not accept FAST flag if the session has software effects 6633 sp<EffectChain> chain = getEffectChain_l(sessionId); 6634 if (chain != 0) { 6635 audio_input_flags_t old = *flags; 6636 chain->checkInputFlagCompatibility(flags); 6637 if (old != *flags) { 6638 ALOGV("AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x", 6639 (int)old, (int)*flags); 6640 } 6641 } 6642 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0, 6643 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu", 6644 frameCount, mFrameCount); 6645 } else { 6646 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu " 6647 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u " 6648 "hasFastCapture=%d tid=%d mFastTrackAvail=%d", 6649 frameCount, mFrameCount, mPipeFramesP2, 6650 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate, 6651 hasFastCapture(), tid, mFastTrackAvail); 6652 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST); 6653 } 6654 } 6655 6656 // compute track buffer size in frames, and suggest the notification frame count 6657 if (*flags & AUDIO_INPUT_FLAG_FAST) { 6658 // fast track: frame count is exactly the pipe depth 6659 frameCount = mPipeFramesP2; 6660 // ignore requested notificationFrames, and always notify exactly once every HAL buffer 6661 *notificationFrames = mFrameCount; 6662 } else { 6663 // not fast track: max notification period is resampled equivalent of one HAL buffer time 6664 // or 20 ms if there is a fast capture 6665 // TODO This could be a roundupRatio inline, and const 6666 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount) 6667 * sampleRate + mSampleRate - 1) / mSampleRate; 6668 // minimum number of notification periods is at least kMinNotifications, 6669 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs) 6670 static const size_t kMinNotifications = 3; 6671 static const uint32_t kMinMs = 30; 6672 // TODO This could be a roundupRatio inline 6673 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000; 6674 // TODO This could be a roundupRatio inline 6675 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) / 6676 maxNotificationFrames; 6677 const size_t minFrameCount = maxNotificationFrames * 6678 max(kMinNotifications, minNotificationsByMs); 6679 frameCount = max(frameCount, minFrameCount); 6680 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) { 6681 *notificationFrames = maxNotificationFrames; 6682 } 6683 } 6684 *pFrameCount = frameCount; 6685 6686 lStatus = initCheck(); 6687 if (lStatus != NO_ERROR) { 6688 ALOGE("createRecordTrack_l() audio driver not initialized"); 6689 goto Exit; 6690 } 6691 6692 { // scope for mLock 6693 Mutex::Autolock _l(mLock); 6694 6695 track = new RecordTrack(this, client, sampleRate, 6696 format, channelMask, frameCount, NULL, sessionId, uid, 6697 *flags, TrackBase::TYPE_DEFAULT, portId); 6698 6699 lStatus = track->initCheck(); 6700 if (lStatus != NO_ERROR) { 6701 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus); 6702 // track must be cleared from the caller as the caller has the AF lock 6703 goto Exit; 6704 } 6705 mTracks.add(track); 6706 6707 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings 6708 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 6709 mAudioFlinger->btNrecIsOff(); 6710 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId); 6711 setEffectSuspended_l(FX_IID_NS, suspend, sessionId); 6712 6713 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) { 6714 pid_t callingPid = IPCThreadState::self()->getCallingPid(); 6715 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful, 6716 // so ask activity manager to do this on our behalf 6717 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true); 6718 } 6719 } 6720 6721 lStatus = NO_ERROR; 6722 6723 Exit: 6724 *status = lStatus; 6725 return track; 6726 } 6727 6728 status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, 6729 AudioSystem::sync_event_t event, 6730 audio_session_t triggerSession) 6731 { 6732 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession); 6733 sp<ThreadBase> strongMe = this; 6734 status_t status = NO_ERROR; 6735 6736 if (event == AudioSystem::SYNC_EVENT_NONE) { 6737 recordTrack->clearSyncStartEvent(); 6738 } else if (event != AudioSystem::SYNC_EVENT_SAME) { 6739 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event, 6740 triggerSession, 6741 recordTrack->sessionId(), 6742 syncStartEventCallback, 6743 recordTrack); 6744 // Sync event can be cancelled by the trigger session if the track is not in a 6745 // compatible state in which case we start record immediately 6746 if (recordTrack->mSyncStartEvent->isCancelled()) { 6747 recordTrack->clearSyncStartEvent(); 6748 } else { 6749 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs 6750 recordTrack->mFramesToDrop = - 6751 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000); 6752 } 6753 } 6754 6755 { 6756 // This section is a rendezvous between binder thread executing start() and RecordThread 6757 AutoMutex lock(mLock); 6758 if (mActiveTracks.indexOf(recordTrack) >= 0) { 6759 if (recordTrack->mState == TrackBase::PAUSING) { 6760 ALOGV("active record track PAUSING -> ACTIVE"); 6761 recordTrack->mState = TrackBase::ACTIVE; 6762 } else { 6763 ALOGV("active record track state %d", recordTrack->mState); 6764 } 6765 return status; 6766 } 6767 6768 // TODO consider other ways of handling this, such as changing the state to :STARTING and 6769 // adding the track to mActiveTracks after returning from AudioSystem::startInput(), 6770 // or using a separate command thread 6771 recordTrack->mState = TrackBase::STARTING_1; 6772 mActiveTracks.add(recordTrack); 6773 status_t status = NO_ERROR; 6774 if (recordTrack->isExternalTrack()) { 6775 mLock.unlock(); 6776 status = AudioSystem::startInput(mId, recordTrack->sessionId()); 6777 mLock.lock(); 6778 // FIXME should verify that recordTrack is still in mActiveTracks 6779 if (status != NO_ERROR) { 6780 mActiveTracks.remove(recordTrack); 6781 recordTrack->clearSyncStartEvent(); 6782 ALOGV("RecordThread::start error %d", status); 6783 return status; 6784 } 6785 } 6786 // Catch up with current buffer indices if thread is already running. 6787 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront 6788 // was initialized to some value closer to the thread's mRsmpInFront, then the track could 6789 // see previously buffered data before it called start(), but with greater risk of overrun. 6790 6791 recordTrack->mResamplerBufferProvider->reset(); 6792 // clear any converter state as new data will be discontinuous 6793 recordTrack->mRecordBufferConverter->reset(); 6794 recordTrack->mState = TrackBase::STARTING_2; 6795 // signal thread to start 6796 mWaitWorkCV.broadcast(); 6797 if (mActiveTracks.indexOf(recordTrack) < 0) { 6798 ALOGV("Record failed to start"); 6799 status = BAD_VALUE; 6800 goto startError; 6801 } 6802 return status; 6803 } 6804 6805 startError: 6806 if (recordTrack->isExternalTrack()) { 6807 AudioSystem::stopInput(mId, recordTrack->sessionId()); 6808 } 6809 recordTrack->clearSyncStartEvent(); 6810 // FIXME I wonder why we do not reset the state here? 6811 return status; 6812 } 6813 6814 void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event) 6815 { 6816 sp<SyncEvent> strongEvent = event.promote(); 6817 6818 if (strongEvent != 0) { 6819 sp<RefBase> ptr = strongEvent->cookie().promote(); 6820 if (ptr != 0) { 6821 RecordTrack *recordTrack = (RecordTrack *)ptr.get(); 6822 recordTrack->handleSyncStartEvent(strongEvent); 6823 } 6824 } 6825 } 6826 6827 bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) { 6828 ALOGV("RecordThread::stop"); 6829 AutoMutex _l(mLock); 6830 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) { 6831 return false; 6832 } 6833 // note that threadLoop may still be processing the track at this point [without lock] 6834 recordTrack->mState = TrackBase::PAUSING; 6835 // signal thread to stop 6836 mWaitWorkCV.broadcast(); 6837 // do not wait for mStartStopCond if exiting 6838 if (exitPending()) { 6839 return true; 6840 } 6841 // FIXME incorrect usage of wait: no explicit predicate or loop 6842 mStartStopCond.wait(mLock); 6843 // if we have been restarted, recordTrack is in mActiveTracks here 6844 if (exitPending() || mActiveTracks.indexOf(recordTrack) < 0) { 6845 ALOGV("Record stopped OK"); 6846 return true; 6847 } 6848 return false; 6849 } 6850 6851 bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const 6852 { 6853 return false; 6854 } 6855 6856 status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused) 6857 { 6858 #if 0 // This branch is currently dead code, but is preserved in case it will be needed in future 6859 if (!isValidSyncEvent(event)) { 6860 return BAD_VALUE; 6861 } 6862 6863 audio_session_t eventSession = event->triggerSession(); 6864 status_t ret = NAME_NOT_FOUND; 6865 6866 Mutex::Autolock _l(mLock); 6867 6868 for (size_t i = 0; i < mTracks.size(); i++) { 6869 sp<RecordTrack> track = mTracks[i]; 6870 if (eventSession == track->sessionId()) { 6871 (void) track->setSyncEvent(event); 6872 ret = NO_ERROR; 6873 } 6874 } 6875 return ret; 6876 #else 6877 return BAD_VALUE; 6878 #endif 6879 } 6880 6881 // destroyTrack_l() must be called with ThreadBase::mLock held 6882 void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track) 6883 { 6884 track->terminate(); 6885 track->mState = TrackBase::STOPPED; 6886 // active tracks are removed by threadLoop() 6887 if (mActiveTracks.indexOf(track) < 0) { 6888 removeTrack_l(track); 6889 } 6890 } 6891 6892 void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track) 6893 { 6894 mTracks.remove(track); 6895 // need anything related to effects here? 6896 if (track->isFastTrack()) { 6897 ALOG_ASSERT(!mFastTrackAvail); 6898 mFastTrackAvail = true; 6899 } 6900 } 6901 6902 void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args) 6903 { 6904 dumpInternals(fd, args); 6905 dumpTracks(fd, args); 6906 dumpEffectChains(fd, args); 6907 } 6908 6909 void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args) 6910 { 6911 dumpBase(fd, args); 6912 6913 AudioStreamIn *input = mInput; 6914 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE; 6915 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n", 6916 input, flags, inputFlagsToString(flags).c_str()); 6917 if (mActiveTracks.size() == 0) { 6918 dprintf(fd, " No active record clients\n"); 6919 } 6920 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no"); 6921 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no"); 6922 6923 // Make a non-atomic copy of fast capture dump state so it won't change underneath us 6924 // while we are dumping it. It may be inconsistent, but it won't mutate! 6925 // This is a large object so we place it on the heap. 6926 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages. 6927 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState); 6928 copy->dump(fd); 6929 delete copy; 6930 } 6931 6932 void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused) 6933 { 6934 const size_t SIZE = 256; 6935 char buffer[SIZE]; 6936 String8 result; 6937 6938 size_t numtracks = mTracks.size(); 6939 size_t numactive = mActiveTracks.size(); 6940 size_t numactiveseen = 0; 6941 dprintf(fd, " %zu Tracks", numtracks); 6942 if (numtracks) { 6943 dprintf(fd, " of which %zu are active\n", numactive); 6944 RecordTrack::appendDumpHeader(result); 6945 for (size_t i = 0; i < numtracks ; ++i) { 6946 sp<RecordTrack> track = mTracks[i]; 6947 if (track != 0) { 6948 bool active = mActiveTracks.indexOf(track) >= 0; 6949 if (active) { 6950 numactiveseen++; 6951 } 6952 track->dump(buffer, SIZE, active); 6953 result.append(buffer); 6954 } 6955 } 6956 } else { 6957 dprintf(fd, "\n"); 6958 } 6959 6960 if (numactiveseen != numactive) { 6961 snprintf(buffer, SIZE, " The following tracks are in the active list but" 6962 " not in the track list\n"); 6963 result.append(buffer); 6964 RecordTrack::appendDumpHeader(result); 6965 for (size_t i = 0; i < numactive; ++i) { 6966 sp<RecordTrack> track = mActiveTracks[i]; 6967 if (mTracks.indexOf(track) < 0) { 6968 track->dump(buffer, SIZE, true); 6969 result.append(buffer); 6970 } 6971 } 6972 6973 } 6974 write(fd, result.string(), result.size()); 6975 } 6976 6977 6978 void AudioFlinger::RecordThread::ResamplerBufferProvider::reset() 6979 { 6980 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote(); 6981 RecordThread *recordThread = (RecordThread *) threadBase.get(); 6982 mRsmpInFront = recordThread->mRsmpInRear; 6983 mRsmpInUnrel = 0; 6984 } 6985 6986 void AudioFlinger::RecordThread::ResamplerBufferProvider::sync( 6987 size_t *framesAvailable, bool *hasOverrun) 6988 { 6989 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote(); 6990 RecordThread *recordThread = (RecordThread *) threadBase.get(); 6991 const int32_t rear = recordThread->mRsmpInRear; 6992 const int32_t front = mRsmpInFront; 6993 const ssize_t filled = rear - front; 6994 6995 size_t framesIn; 6996 bool overrun = false; 6997 if (filled < 0) { 6998 // should not happen, but treat like a massive overrun and re-sync 6999 framesIn = 0; 7000 mRsmpInFront = rear; 7001 overrun = true; 7002 } else if ((size_t) filled <= recordThread->mRsmpInFrames) { 7003 framesIn = (size_t) filled; 7004 } else { 7005 // client is not keeping up with server, but give it latest data 7006 framesIn = recordThread->mRsmpInFrames; 7007 mRsmpInFront = /* front = */ rear - framesIn; 7008 overrun = true; 7009 } 7010 if (framesAvailable != NULL) { 7011 *framesAvailable = framesIn; 7012 } 7013 if (hasOverrun != NULL) { 7014 *hasOverrun = overrun; 7015 } 7016 } 7017 7018 // AudioBufferProvider interface 7019 status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer( 7020 AudioBufferProvider::Buffer* buffer) 7021 { 7022 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote(); 7023 if (threadBase == 0) { 7024 buffer->frameCount = 0; 7025 buffer->raw = NULL; 7026 return NOT_ENOUGH_DATA; 7027 } 7028 RecordThread *recordThread = (RecordThread *) threadBase.get(); 7029 int32_t rear = recordThread->mRsmpInRear; 7030 int32_t front = mRsmpInFront; 7031 ssize_t filled = rear - front; 7032 // FIXME should not be P2 (don't want to increase latency) 7033 // FIXME if client not keeping up, discard 7034 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames)); 7035 // 'filled' may be non-contiguous, so return only the first contiguous chunk 7036 front &= recordThread->mRsmpInFramesP2 - 1; 7037 size_t part1 = recordThread->mRsmpInFramesP2 - front; 7038 if (part1 > (size_t) filled) { 7039 part1 = filled; 7040 } 7041 size_t ask = buffer->frameCount; 7042 ALOG_ASSERT(ask > 0); 7043 if (part1 > ask) { 7044 part1 = ask; 7045 } 7046 if (part1 == 0) { 7047 // out of data is fine since the resampler will return a short-count. 7048 buffer->raw = NULL; 7049 buffer->frameCount = 0; 7050 mRsmpInUnrel = 0; 7051 return NOT_ENOUGH_DATA; 7052 } 7053 7054 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize; 7055 buffer->frameCount = part1; 7056 mRsmpInUnrel = part1; 7057 return NO_ERROR; 7058 } 7059 7060 // AudioBufferProvider interface 7061 void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer( 7062 AudioBufferProvider::Buffer* buffer) 7063 { 7064 size_t stepCount = buffer->frameCount; 7065 if (stepCount == 0) { 7066 return; 7067 } 7068 ALOG_ASSERT(stepCount <= mRsmpInUnrel); 7069 mRsmpInUnrel -= stepCount; 7070 mRsmpInFront += stepCount; 7071 buffer->raw = NULL; 7072 buffer->frameCount = 0; 7073 } 7074 7075 7076 bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair, 7077 status_t& status) 7078 { 7079 bool reconfig = false; 7080 7081 status = NO_ERROR; 7082 7083 audio_format_t reqFormat = mFormat; 7084 uint32_t samplingRate = mSampleRate; 7085 // TODO this may change if we want to support capture from HDMI PCM multi channel (e.g on TVs). 7086 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount); 7087 7088 AudioParameter param = AudioParameter(keyValuePair); 7089 int value; 7090 7091 // scope for AutoPark extends to end of method 7092 AutoPark<FastCapture> park(mFastCapture); 7093 7094 // TODO Investigate when this code runs. Check with audio policy when a sample rate and 7095 // channel count change can be requested. Do we mandate the first client defines the 7096 // HAL sampling rate and channel count or do we allow changes on the fly? 7097 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) { 7098 samplingRate = value; 7099 reconfig = true; 7100 } 7101 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) { 7102 if (!audio_is_linear_pcm((audio_format_t) value)) { 7103 status = BAD_VALUE; 7104 } else { 7105 reqFormat = (audio_format_t) value; 7106 reconfig = true; 7107 } 7108 } 7109 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) { 7110 audio_channel_mask_t mask = (audio_channel_mask_t) value; 7111 if (!audio_is_input_channel(mask) || 7112 audio_channel_count_from_in_mask(mask) > FCC_8) { 7113 status = BAD_VALUE; 7114 } else { 7115 channelMask = mask; 7116 reconfig = true; 7117 } 7118 } 7119 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) { 7120 // do not accept frame count changes if tracks are open as the track buffer 7121 // size depends on frame count and correct behavior would not be guaranteed 7122 // if frame count is changed after track creation 7123 if (mActiveTracks.size() > 0) { 7124 status = INVALID_OPERATION; 7125 } else { 7126 reconfig = true; 7127 } 7128 } 7129 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 7130 // forward device change to effects that have requested to be 7131 // aware of attached audio device. 7132 for (size_t i = 0; i < mEffectChains.size(); i++) { 7133 mEffectChains[i]->setDevice_l(value); 7134 } 7135 7136 // store input device and output device but do not forward output device to audio HAL. 7137 // Note that status is ignored by the caller for output device 7138 // (see AudioFlinger::setParameters() 7139 if (audio_is_output_devices(value)) { 7140 mOutDevice = value; 7141 status = BAD_VALUE; 7142 } else { 7143 mInDevice = value; 7144 if (value != AUDIO_DEVICE_NONE) { 7145 mPrevInDevice = value; 7146 } 7147 // disable AEC and NS if the device is a BT SCO headset supporting those 7148 // pre processings 7149 if (mTracks.size() > 0) { 7150 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 7151 mAudioFlinger->btNrecIsOff(); 7152 for (size_t i = 0; i < mTracks.size(); i++) { 7153 sp<RecordTrack> track = mTracks[i]; 7154 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId()); 7155 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId()); 7156 } 7157 } 7158 } 7159 } 7160 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR && 7161 mAudioSource != (audio_source_t)value) { 7162 // forward device change to effects that have requested to be 7163 // aware of attached audio device. 7164 for (size_t i = 0; i < mEffectChains.size(); i++) { 7165 mEffectChains[i]->setAudioSource_l((audio_source_t)value); 7166 } 7167 mAudioSource = (audio_source_t)value; 7168 } 7169 7170 if (status == NO_ERROR) { 7171 status = mInput->stream->setParameters(keyValuePair); 7172 if (status == INVALID_OPERATION) { 7173 inputStandBy(); 7174 status = mInput->stream->setParameters(keyValuePair); 7175 } 7176 if (reconfig) { 7177 if (status == BAD_VALUE) { 7178 uint32_t sRate; 7179 audio_channel_mask_t channelMask; 7180 audio_format_t format; 7181 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK && 7182 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) && 7183 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) && 7184 audio_channel_count_from_in_mask(channelMask) <= FCC_8) { 7185 status = NO_ERROR; 7186 } 7187 } 7188 if (status == NO_ERROR) { 7189 readInputParameters_l(); 7190 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED); 7191 } 7192 } 7193 } 7194 7195 return reconfig; 7196 } 7197 7198 String8 AudioFlinger::RecordThread::getParameters(const String8& keys) 7199 { 7200 Mutex::Autolock _l(mLock); 7201 if (initCheck() == NO_ERROR) { 7202 String8 out_s8; 7203 if (mInput->stream->getParameters(keys, &out_s8) == OK) { 7204 return out_s8; 7205 } 7206 } 7207 return String8(); 7208 } 7209 7210 void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) { 7211 sp<AudioIoDescriptor> desc = new AudioIoDescriptor(); 7212 7213 desc->mIoHandle = mId; 7214 7215 switch (event) { 7216 case AUDIO_INPUT_OPENED: 7217 case AUDIO_INPUT_CONFIG_CHANGED: 7218 desc->mPatch = mPatch; 7219 desc->mChannelMask = mChannelMask; 7220 desc->mSamplingRate = mSampleRate; 7221 desc->mFormat = mFormat; 7222 desc->mFrameCount = mFrameCount; 7223 desc->mFrameCountHAL = mFrameCount; 7224 desc->mLatency = 0; 7225 break; 7226 7227 case AUDIO_INPUT_CLOSED: 7228 default: 7229 break; 7230 } 7231 mAudioFlinger->ioConfigChanged(event, desc, pid); 7232 } 7233 7234 void AudioFlinger::RecordThread::readInputParameters_l() 7235 { 7236 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat); 7237 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result); 7238 mChannelCount = audio_channel_count_from_in_mask(mChannelMask); 7239 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8); 7240 mFormat = mHALFormat; 7241 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat); 7242 result = mInput->stream->getFrameSize(&mFrameSize); 7243 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result); 7244 result = mInput->stream->getBufferSize(&mBufferSize); 7245 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result); 7246 mFrameCount = mBufferSize / mFrameSize; 7247 // This is the formula for calculating the temporary buffer size. 7248 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to 7249 // 1 full output buffer, regardless of the alignment of the available input. 7250 // The value is somewhat arbitrary, and could probably be even larger. 7251 // A larger value should allow more old data to be read after a track calls start(), 7252 // without increasing latency. 7253 // 7254 // Note this is independent of the maximum downsampling ratio permitted for capture. 7255 mRsmpInFrames = mFrameCount * 7; 7256 mRsmpInFramesP2 = roundup(mRsmpInFrames); 7257 free(mRsmpInBuffer); 7258 mRsmpInBuffer = NULL; 7259 7260 // TODO optimize audio capture buffer sizes ... 7261 // Here we calculate the size of the sliding buffer used as a source 7262 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7). 7263 // For current HAL frame counts, this is usually 2048 = 40 ms. It would 7264 // be better to have it derived from the pipe depth in the long term. 7265 // The current value is higher than necessary. However it should not add to latency. 7266 7267 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer 7268 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1; 7269 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize); 7270 // if posix_memalign fails, will segv here. 7271 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize); 7272 7273 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints. 7274 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks? 7275 } 7276 7277 uint32_t AudioFlinger::RecordThread::getInputFramesLost() 7278 { 7279 Mutex::Autolock _l(mLock); 7280 uint32_t result; 7281 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) { 7282 return result; 7283 } 7284 return 0; 7285 } 7286 7287 // hasAudioSession_l() must be called with ThreadBase::mLock held 7288 uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const 7289 { 7290 uint32_t result = 0; 7291 if (getEffectChain_l(sessionId) != 0) { 7292 result = EFFECT_SESSION; 7293 } 7294 7295 for (size_t i = 0; i < mTracks.size(); ++i) { 7296 if (sessionId == mTracks[i]->sessionId()) { 7297 result |= TRACK_SESSION; 7298 if (mTracks[i]->isFastTrack()) { 7299 result |= FAST_SESSION; 7300 } 7301 break; 7302 } 7303 } 7304 7305 return result; 7306 } 7307 7308 KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const 7309 { 7310 KeyedVector<audio_session_t, bool> ids; 7311 Mutex::Autolock _l(mLock); 7312 for (size_t j = 0; j < mTracks.size(); ++j) { 7313 sp<RecordThread::RecordTrack> track = mTracks[j]; 7314 audio_session_t sessionId = track->sessionId(); 7315 if (ids.indexOfKey(sessionId) < 0) { 7316 ids.add(sessionId, true); 7317 } 7318 } 7319 return ids; 7320 } 7321 7322 AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput() 7323 { 7324 Mutex::Autolock _l(mLock); 7325 AudioStreamIn *input = mInput; 7326 mInput = NULL; 7327 return input; 7328 } 7329 7330 // this method must always be called either with ThreadBase mLock held or inside the thread loop 7331 sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const 7332 { 7333 if (mInput == NULL) { 7334 return NULL; 7335 } 7336 return mInput->stream; 7337 } 7338 7339 status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain) 7340 { 7341 // only one chain per input thread 7342 if (mEffectChains.size() != 0) { 7343 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this); 7344 return INVALID_OPERATION; 7345 } 7346 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this); 7347 chain->setThread(this); 7348 chain->setInBuffer(NULL); 7349 chain->setOutBuffer(NULL); 7350 7351 checkSuspendOnAddEffectChain_l(chain); 7352 7353 // make sure enabled pre processing effects state is communicated to the HAL as we 7354 // just moved them to a new input stream. 7355 chain->syncHalEffectsState(); 7356 7357 mEffectChains.add(chain); 7358 7359 return NO_ERROR; 7360 } 7361 7362 size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain) 7363 { 7364 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this); 7365 ALOGW_IF(mEffectChains.size() != 1, 7366 "removeEffectChain_l() %p invalid chain size %zu on thread %p", 7367 chain.get(), mEffectChains.size(), this); 7368 if (mEffectChains.size() == 1) { 7369 mEffectChains.removeAt(0); 7370 } 7371 return 0; 7372 } 7373 7374 status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch, 7375 audio_patch_handle_t *handle) 7376 { 7377 status_t status = NO_ERROR; 7378 7379 // store new device and send to effects 7380 mInDevice = patch->sources[0].ext.device.type; 7381 mPatch = *patch; 7382 for (size_t i = 0; i < mEffectChains.size(); i++) { 7383 mEffectChains[i]->setDevice_l(mInDevice); 7384 } 7385 7386 // disable AEC and NS if the device is a BT SCO headset supporting those 7387 // pre processings 7388 if (mTracks.size() > 0) { 7389 bool suspend = audio_is_bluetooth_sco_device(mInDevice) && 7390 mAudioFlinger->btNrecIsOff(); 7391 for (size_t i = 0; i < mTracks.size(); i++) { 7392 sp<RecordTrack> track = mTracks[i]; 7393 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId()); 7394 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId()); 7395 } 7396 } 7397 7398 // store new source and send to effects 7399 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) { 7400 mAudioSource = patch->sinks[0].ext.mix.usecase.source; 7401 for (size_t i = 0; i < mEffectChains.size(); i++) { 7402 mEffectChains[i]->setAudioSource_l(mAudioSource); 7403 } 7404 } 7405 7406 if (mInput->audioHwDev->supportsAudioPatches()) { 7407 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice(); 7408 status = hwDevice->createAudioPatch(patch->num_sources, 7409 patch->sources, 7410 patch->num_sinks, 7411 patch->sinks, 7412 handle); 7413 } else { 7414 char *address; 7415 if (strcmp(patch->sources[0].ext.device.address, "") != 0) { 7416 address = audio_device_address_to_parameter( 7417 patch->sources[0].ext.device.type, 7418 patch->sources[0].ext.device.address); 7419 } else { 7420 address = (char *)calloc(1, 1); 7421 } 7422 AudioParameter param = AudioParameter(String8(address)); 7423 free(address); 7424 param.addInt(String8(AudioParameter::keyRouting), 7425 (int)patch->sources[0].ext.device.type); 7426 param.addInt(String8(AudioParameter::keyInputSource), 7427 (int)patch->sinks[0].ext.mix.usecase.source); 7428 status = mInput->stream->setParameters(param.toString()); 7429 *handle = AUDIO_PATCH_HANDLE_NONE; 7430 } 7431 7432 if (mInDevice != mPrevInDevice) { 7433 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED); 7434 mPrevInDevice = mInDevice; 7435 } 7436 7437 return status; 7438 } 7439 7440 status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle) 7441 { 7442 status_t status = NO_ERROR; 7443 7444 mInDevice = AUDIO_DEVICE_NONE; 7445 7446 if (mInput->audioHwDev->supportsAudioPatches()) { 7447 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice(); 7448 status = hwDevice->releaseAudioPatch(handle); 7449 } else { 7450 AudioParameter param; 7451 param.addInt(String8(AudioParameter::keyRouting), 0); 7452 status = mInput->stream->setParameters(param.toString()); 7453 } 7454 return status; 7455 } 7456 7457 void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record) 7458 { 7459 Mutex::Autolock _l(mLock); 7460 mTracks.add(record); 7461 } 7462 7463 void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record) 7464 { 7465 Mutex::Autolock _l(mLock); 7466 destroyTrack_l(record); 7467 } 7468 7469 void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config) 7470 { 7471 ThreadBase::getAudioPortConfig(config); 7472 config->role = AUDIO_PORT_ROLE_SINK; 7473 config->ext.mix.hw_module = mInput->audioHwDev->handle(); 7474 config->ext.mix.usecase.source = mAudioSource; 7475 } 7476 7477 // ---------------------------------------------------------------------------- 7478 // Mmap 7479 // ---------------------------------------------------------------------------- 7480 7481 AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread) 7482 : mThread(thread) 7483 { 7484 } 7485 7486 AudioFlinger::MmapThreadHandle::~MmapThreadHandle() 7487 { 7488 MmapThread *thread = mThread.get(); 7489 // clear our strong reference before disconnecting the thread: the last strong reference 7490 // will be removed when closeInput/closeOutput is executed upon call from audio policy manager 7491 // and the thread removed from mMMapThreads list causing the thread destruction. 7492 mThread.clear(); 7493 if (thread != nullptr) { 7494 thread->disconnect(); 7495 } 7496 } 7497 7498 status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames, 7499 struct audio_mmap_buffer_info *info) 7500 { 7501 if (mThread == 0) { 7502 return NO_INIT; 7503 } 7504 return mThread->createMmapBuffer(minSizeFrames, info); 7505 } 7506 7507 status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position) 7508 { 7509 if (mThread == 0) { 7510 return NO_INIT; 7511 } 7512 return mThread->getMmapPosition(position); 7513 } 7514 7515 status_t AudioFlinger::MmapThreadHandle::start(const MmapStreamInterface::Client& client, 7516 audio_port_handle_t *handle) 7517 7518 { 7519 if (mThread == 0) { 7520 return NO_INIT; 7521 } 7522 return mThread->start(client, handle); 7523 } 7524 7525 status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle) 7526 { 7527 if (mThread == 0) { 7528 return NO_INIT; 7529 } 7530 return mThread->stop(handle); 7531 } 7532 7533 status_t AudioFlinger::MmapThreadHandle::standby() 7534 { 7535 if (mThread == 0) { 7536 return NO_INIT; 7537 } 7538 return mThread->standby(); 7539 } 7540 7541 7542 AudioFlinger::MmapThread::MmapThread( 7543 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id, 7544 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, 7545 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady) 7546 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady), 7547 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev) 7548 { 7549 mStandby = true; 7550 readHalParameters_l(); 7551 } 7552 7553 AudioFlinger::MmapThread::~MmapThread() 7554 { 7555 releaseWakeLock_l(); 7556 } 7557 7558 void AudioFlinger::MmapThread::onFirstRef() 7559 { 7560 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO); 7561 } 7562 7563 void AudioFlinger::MmapThread::disconnect() 7564 { 7565 for (const sp<MmapTrack> &t : mActiveTracks) { 7566 stop(t->portId()); 7567 } 7568 // this will cause the destruction of this thread. 7569 if (isOutput()) { 7570 AudioSystem::releaseOutput(mId, streamType(), mSessionId); 7571 } else { 7572 AudioSystem::releaseInput(mId, mSessionId); 7573 } 7574 } 7575 7576 7577 void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr, 7578 audio_stream_type_t streamType __unused, 7579 audio_session_t sessionId, 7580 const sp<MmapStreamCallback>& callback, 7581 audio_port_handle_t portId) 7582 { 7583 mAttr = *attr; 7584 mSessionId = sessionId; 7585 mCallback = callback; 7586 mPortId = portId; 7587 } 7588 7589 status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames, 7590 struct audio_mmap_buffer_info *info) 7591 { 7592 if (mHalStream == 0) { 7593 return NO_INIT; 7594 } 7595 mStandby = true; 7596 acquireWakeLock(); 7597 return mHalStream->createMmapBuffer(minSizeFrames, info); 7598 } 7599 7600 status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position) 7601 { 7602 if (mHalStream == 0) { 7603 return NO_INIT; 7604 } 7605 return mHalStream->getMmapPosition(position); 7606 } 7607 7608 status_t AudioFlinger::MmapThread::start(const MmapStreamInterface::Client& client, 7609 audio_port_handle_t *handle) 7610 { 7611 ALOGV("%s clientUid %d mStandby %d", __FUNCTION__, client.clientUid, mStandby); 7612 if (mHalStream == 0) { 7613 return NO_INIT; 7614 } 7615 7616 status_t ret; 7617 audio_session_t sessionId; 7618 audio_port_handle_t portId; 7619 7620 if (mActiveTracks.size() == 0) { 7621 // for the first track, reuse portId and session allocated when the stream was opened 7622 ret = mHalStream->start(); 7623 if (ret != NO_ERROR) { 7624 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret); 7625 return ret; 7626 } 7627 portId = mPortId; 7628 sessionId = mSessionId; 7629 mStandby = false; 7630 } else { 7631 // for other tracks than first one, get a new port ID from APM. 7632 sessionId = (audio_session_t)mAudioFlinger->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION); 7633 audio_io_handle_t io; 7634 if (isOutput()) { 7635 audio_config_t config = AUDIO_CONFIG_INITIALIZER; 7636 config.sample_rate = mSampleRate; 7637 config.channel_mask = mChannelMask; 7638 config.format = mFormat; 7639 audio_stream_type_t stream = streamType(); 7640 audio_output_flags_t flags = 7641 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT); 7642 ret = AudioSystem::getOutputForAttr(&mAttr, &io, 7643 sessionId, 7644 &stream, 7645 client.clientUid, 7646 &config, 7647 flags, 7648 AUDIO_PORT_HANDLE_NONE, 7649 &portId); 7650 } else { 7651 audio_config_base_t config; 7652 config.sample_rate = mSampleRate; 7653 config.channel_mask = mChannelMask; 7654 config.format = mFormat; 7655 ret = AudioSystem::getInputForAttr(&mAttr, &io, 7656 sessionId, 7657 client.clientPid, 7658 client.clientUid, 7659 &config, 7660 AUDIO_INPUT_FLAG_MMAP_NOIRQ, 7661 AUDIO_PORT_HANDLE_NONE, 7662 &portId); 7663 } 7664 // APM should not chose a different input or output stream for the same set of attributes 7665 // and audo configuration 7666 if (ret != NO_ERROR || io != mId) { 7667 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)", 7668 __FUNCTION__, ret, io, mId); 7669 return BAD_VALUE; 7670 } 7671 } 7672 7673 if (isOutput()) { 7674 ret = AudioSystem::startOutput(mId, streamType(), sessionId); 7675 } else { 7676 ret = AudioSystem::startInput(mId, sessionId); 7677 } 7678 7679 // abort if start is rejected by audio policy manager 7680 if (ret != NO_ERROR) { 7681 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret); 7682 if (mActiveTracks.size() != 0) { 7683 if (isOutput()) { 7684 AudioSystem::releaseOutput(mId, streamType(), sessionId); 7685 } else { 7686 AudioSystem::releaseInput(mId, sessionId); 7687 } 7688 } else { 7689 mHalStream->stop(); 7690 } 7691 return PERMISSION_DENIED; 7692 } 7693 7694 sp<MmapTrack> track = new MmapTrack(this, mSampleRate, mFormat, mChannelMask, sessionId, 7695 client.clientUid, portId); 7696 7697 mActiveTracks.add(track); 7698 sp<EffectChain> chain = getEffectChain_l(sessionId); 7699 if (chain != 0) { 7700 chain->setStrategy(AudioSystem::getStrategyForStream(streamType())); 7701 chain->incTrackCnt(); 7702 chain->incActiveTrackCnt(); 7703 } 7704 7705 *handle = portId; 7706 7707 broadcast_l(); 7708 7709 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, portId, mHalStream.get()); 7710 7711 return NO_ERROR; 7712 } 7713 7714 status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle) 7715 { 7716 ALOGV("%s handle %d", __FUNCTION__, handle); 7717 7718 if (mHalStream == 0) { 7719 return NO_INIT; 7720 } 7721 7722 sp<MmapTrack> track; 7723 for (const sp<MmapTrack> &t : mActiveTracks) { 7724 if (handle == t->portId()) { 7725 track = t; 7726 break; 7727 } 7728 } 7729 if (track == 0) { 7730 return BAD_VALUE; 7731 } 7732 7733 mActiveTracks.remove(track); 7734 7735 if (isOutput()) { 7736 AudioSystem::stopOutput(mId, streamType(), track->sessionId()); 7737 if (mActiveTracks.size() != 0) { 7738 AudioSystem::releaseOutput(mId, streamType(), track->sessionId()); 7739 } 7740 } else { 7741 AudioSystem::stopInput(mId, track->sessionId()); 7742 if (mActiveTracks.size() != 0) { 7743 AudioSystem::releaseInput(mId, track->sessionId()); 7744 } 7745 } 7746 7747 sp<EffectChain> chain = getEffectChain_l(track->sessionId()); 7748 if (chain != 0) { 7749 chain->decActiveTrackCnt(); 7750 chain->decTrackCnt(); 7751 } 7752 7753 broadcast_l(); 7754 7755 if (mActiveTracks.size() == 0) { 7756 mHalStream->stop(); 7757 } 7758 return NO_ERROR; 7759 } 7760 7761 status_t AudioFlinger::MmapThread::standby() 7762 { 7763 ALOGV("%s", __FUNCTION__); 7764 7765 if (mHalStream == 0) { 7766 return NO_INIT; 7767 } 7768 if (mActiveTracks.size() != 0) { 7769 return INVALID_OPERATION; 7770 } 7771 mHalStream->standby(); 7772 mStandby = true; 7773 releaseWakeLock(); 7774 return NO_ERROR; 7775 } 7776 7777 7778 void AudioFlinger::MmapThread::readHalParameters_l() 7779 { 7780 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat); 7781 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result); 7782 mFormat = mHALFormat; 7783 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat); 7784 result = mHalStream->getFrameSize(&mFrameSize); 7785 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result); 7786 result = mHalStream->getBufferSize(&mBufferSize); 7787 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result); 7788 mFrameCount = mBufferSize / mFrameSize; 7789 } 7790 7791 bool AudioFlinger::MmapThread::threadLoop() 7792 { 7793 checkSilentMode_l(); 7794 7795 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid())); 7796 7797 while (!exitPending()) 7798 { 7799 Mutex::Autolock _l(mLock); 7800 Vector< sp<EffectChain> > effectChains; 7801 7802 if (mSignalPending) { 7803 // A signal was raised while we were unlocked 7804 mSignalPending = false; 7805 } else { 7806 if (mConfigEvents.isEmpty()) { 7807 // we're about to wait, flush the binder command buffer 7808 IPCThreadState::self()->flushCommands(); 7809 7810 if (exitPending()) { 7811 break; 7812 } 7813 7814 // wait until we have something to do... 7815 ALOGV("%s going to sleep", myName.string()); 7816 mWaitWorkCV.wait(mLock); 7817 ALOGV("%s waking up", myName.string()); 7818 7819 checkSilentMode_l(); 7820 7821 continue; 7822 } 7823 } 7824 7825 processConfigEvents_l(); 7826 7827 processVolume_l(); 7828 7829 checkInvalidTracks_l(); 7830 7831 mActiveTracks.updatePowerState(this); 7832 7833 lockEffectChains_l(effectChains); 7834 for (size_t i = 0; i < effectChains.size(); i ++) { 7835 effectChains[i]->process_l(); 7836 } 7837 // enable changes in effect chain 7838 unlockEffectChains(effectChains); 7839 // Effect chains will be actually deleted here if they were removed from 7840 // mEffectChains list during mixing or effects processing 7841 } 7842 7843 threadLoop_exit(); 7844 7845 if (!mStandby) { 7846 threadLoop_standby(); 7847 mStandby = true; 7848 } 7849 7850 ALOGV("Thread %p type %d exiting", this, mType); 7851 return false; 7852 } 7853 7854 // checkForNewParameter_l() must be called with ThreadBase::mLock held 7855 bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair, 7856 status_t& status) 7857 { 7858 AudioParameter param = AudioParameter(keyValuePair); 7859 int value; 7860 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) { 7861 // forward device change to effects that have requested to be 7862 // aware of attached audio device. 7863 if (value != AUDIO_DEVICE_NONE) { 7864 mOutDevice = value; 7865 for (size_t i = 0; i < mEffectChains.size(); i++) { 7866 mEffectChains[i]->setDevice_l(mOutDevice); 7867 } 7868 } 7869 } 7870 status = mHalStream->setParameters(keyValuePair); 7871 7872 return false; 7873 } 7874 7875 String8 AudioFlinger::MmapThread::getParameters(const String8& keys) 7876 { 7877 Mutex::Autolock _l(mLock); 7878 String8 out_s8; 7879 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) { 7880 return out_s8; 7881 } 7882 return String8(); 7883 } 7884 7885 void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) { 7886 sp<AudioIoDescriptor> desc = new AudioIoDescriptor(); 7887 7888 desc->mIoHandle = mId; 7889 7890 switch (event) { 7891 case AUDIO_INPUT_OPENED: 7892 case AUDIO_INPUT_CONFIG_CHANGED: 7893 case AUDIO_OUTPUT_OPENED: 7894 case AUDIO_OUTPUT_CONFIG_CHANGED: 7895 desc->mPatch = mPatch; 7896 desc->mChannelMask = mChannelMask; 7897 desc->mSamplingRate = mSampleRate; 7898 desc->mFormat = mFormat; 7899 desc->mFrameCount = mFrameCount; 7900 desc->mFrameCountHAL = mFrameCount; 7901 desc->mLatency = 0; 7902 break; 7903 7904 case AUDIO_INPUT_CLOSED: 7905 case AUDIO_OUTPUT_CLOSED: 7906 default: 7907 break; 7908 } 7909 mAudioFlinger->ioConfigChanged(event, desc, pid); 7910 } 7911 7912 status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch, 7913 audio_patch_handle_t *handle) 7914 { 7915 status_t status = NO_ERROR; 7916 7917 // store new device and send to effects 7918 audio_devices_t type = AUDIO_DEVICE_NONE; 7919 audio_port_handle_t deviceId; 7920 if (isOutput()) { 7921 for (unsigned int i = 0; i < patch->num_sinks; i++) { 7922 type |= patch->sinks[i].ext.device.type; 7923 } 7924 deviceId = patch->sinks[0].id; 7925 } else { 7926 type = patch->sources[0].ext.device.type; 7927 deviceId = patch->sources[0].id; 7928 } 7929 7930 for (size_t i = 0; i < mEffectChains.size(); i++) { 7931 mEffectChains[i]->setDevice_l(type); 7932 } 7933 7934 if (isOutput()) { 7935 mOutDevice = type; 7936 } else { 7937 mInDevice = type; 7938 // store new source and send to effects 7939 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) { 7940 mAudioSource = patch->sinks[0].ext.mix.usecase.source; 7941 for (size_t i = 0; i < mEffectChains.size(); i++) { 7942 mEffectChains[i]->setAudioSource_l(mAudioSource); 7943 } 7944 } 7945 } 7946 7947 if (mAudioHwDev->supportsAudioPatches()) { 7948 status = mHalDevice->createAudioPatch(patch->num_sources, 7949 patch->sources, 7950 patch->num_sinks, 7951 patch->sinks, 7952 handle); 7953 } else { 7954 char *address; 7955 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) { 7956 //FIXME: we only support address on first sink with HAL version < 3.0 7957 address = audio_device_address_to_parameter( 7958 patch->sinks[0].ext.device.type, 7959 patch->sinks[0].ext.device.address); 7960 } else { 7961 address = (char *)calloc(1, 1); 7962 } 7963 AudioParameter param = AudioParameter(String8(address)); 7964 free(address); 7965 param.addInt(String8(AudioParameter::keyRouting), (int)type); 7966 if (!isOutput()) { 7967 param.addInt(String8(AudioParameter::keyInputSource), 7968 (int)patch->sinks[0].ext.mix.usecase.source); 7969 } 7970 status = mHalStream->setParameters(param.toString()); 7971 *handle = AUDIO_PATCH_HANDLE_NONE; 7972 } 7973 7974 if (isOutput() && mPrevOutDevice != mOutDevice) { 7975 mPrevOutDevice = type; 7976 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED); 7977 sp<MmapStreamCallback> callback = mCallback.promote(); 7978 if (callback != 0) { 7979 callback->onRoutingChanged(deviceId); 7980 } 7981 } 7982 if (!isOutput() && mPrevInDevice != mInDevice) { 7983 mPrevInDevice = type; 7984 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED); 7985 sp<MmapStreamCallback> callback = mCallback.promote(); 7986 if (callback != 0) { 7987 callback->onRoutingChanged(deviceId); 7988 } 7989 } 7990 return status; 7991 } 7992 7993 status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle) 7994 { 7995 status_t status = NO_ERROR; 7996 7997 mInDevice = AUDIO_DEVICE_NONE; 7998 7999 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ? 8000 supportsAudioPatches : false; 8001 8002 if (supportsAudioPatches) { 8003 status = mHalDevice->releaseAudioPatch(handle); 8004 } else { 8005 AudioParameter param; 8006 param.addInt(String8(AudioParameter::keyRouting), 0); 8007 status = mHalStream->setParameters(param.toString()); 8008 } 8009 return status; 8010 } 8011 8012 void AudioFlinger::MmapThread::getAudioPortConfig(struct audio_port_config *config) 8013 { 8014 ThreadBase::getAudioPortConfig(config); 8015 if (isOutput()) { 8016 config->role = AUDIO_PORT_ROLE_SOURCE; 8017 config->ext.mix.hw_module = mAudioHwDev->handle(); 8018 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT; 8019 } else { 8020 config->role = AUDIO_PORT_ROLE_SINK; 8021 config->ext.mix.hw_module = mAudioHwDev->handle(); 8022 config->ext.mix.usecase.source = mAudioSource; 8023 } 8024 } 8025 8026 status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain) 8027 { 8028 audio_session_t session = chain->sessionId(); 8029 8030 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session); 8031 // Attach all tracks with same session ID to this chain. 8032 // indicate all active tracks in the chain 8033 for (const sp<MmapTrack> &track : mActiveTracks) { 8034 if (session == track->sessionId()) { 8035 chain->incTrackCnt(); 8036 chain->incActiveTrackCnt(); 8037 } 8038 } 8039 8040 chain->setThread(this); 8041 chain->setInBuffer(nullptr); 8042 chain->setOutBuffer(nullptr); 8043 chain->syncHalEffectsState(); 8044 8045 mEffectChains.add(chain); 8046 checkSuspendOnAddEffectChain_l(chain); 8047 return NO_ERROR; 8048 } 8049 8050 size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain) 8051 { 8052 audio_session_t session = chain->sessionId(); 8053 8054 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session); 8055 8056 for (size_t i = 0; i < mEffectChains.size(); i++) { 8057 if (chain == mEffectChains[i]) { 8058 mEffectChains.removeAt(i); 8059 // detach all active tracks from the chain 8060 // detach all tracks with same session ID from this chain 8061 for (const sp<MmapTrack> &track : mActiveTracks) { 8062 if (session == track->sessionId()) { 8063 chain->decActiveTrackCnt(); 8064 chain->decTrackCnt(); 8065 } 8066 } 8067 break; 8068 } 8069 } 8070 return mEffectChains.size(); 8071 } 8072 8073 // hasAudioSession_l() must be called with ThreadBase::mLock held 8074 uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const 8075 { 8076 uint32_t result = 0; 8077 if (getEffectChain_l(sessionId) != 0) { 8078 result = EFFECT_SESSION; 8079 } 8080 8081 for (size_t i = 0; i < mActiveTracks.size(); i++) { 8082 sp<MmapTrack> track = mActiveTracks[i]; 8083 if (sessionId == track->sessionId()) { 8084 result |= TRACK_SESSION; 8085 if (track->isFastTrack()) { 8086 result |= FAST_SESSION; 8087 } 8088 break; 8089 } 8090 } 8091 8092 return result; 8093 } 8094 8095 void AudioFlinger::MmapThread::threadLoop_standby() 8096 { 8097 mHalStream->standby(); 8098 } 8099 8100 void AudioFlinger::MmapThread::threadLoop_exit() 8101 { 8102 sp<MmapStreamCallback> callback = mCallback.promote(); 8103 if (callback != 0) { 8104 callback->onTearDown(); 8105 } 8106 } 8107 8108 status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused) 8109 { 8110 return BAD_VALUE; 8111 } 8112 8113 bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const 8114 { 8115 return false; 8116 } 8117 8118 status_t AudioFlinger::MmapThread::checkEffectCompatibility_l( 8119 const effect_descriptor_t *desc, audio_session_t sessionId) 8120 { 8121 // No global effect sessions on mmap threads 8122 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) { 8123 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s", 8124 desc->name, mThreadName); 8125 return BAD_VALUE; 8126 } 8127 8128 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) { 8129 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread", 8130 desc->name); 8131 return BAD_VALUE; 8132 } 8133 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) { 8134 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap " 8135 "thread", desc->name); 8136 return BAD_VALUE; 8137 } 8138 8139 // Only allow effects without processing load or latency 8140 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) { 8141 return BAD_VALUE; 8142 } 8143 8144 return NO_ERROR; 8145 8146 } 8147 8148 void AudioFlinger::MmapThread::checkInvalidTracks_l() 8149 { 8150 for (const sp<MmapTrack> &track : mActiveTracks) { 8151 if (track->isInvalid()) { 8152 sp<MmapStreamCallback> callback = mCallback.promote(); 8153 if (callback != 0) { 8154 callback->onTearDown(); 8155 } 8156 break; 8157 } 8158 } 8159 } 8160 8161 void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args) 8162 { 8163 dumpInternals(fd, args); 8164 dumpTracks(fd, args); 8165 dumpEffectChains(fd, args); 8166 } 8167 8168 void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args) 8169 { 8170 dumpBase(fd, args); 8171 8172 dprintf(fd, " Attributes: content type %d usage %d source %d\n", 8173 mAttr.content_type, mAttr.usage, mAttr.source); 8174 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId); 8175 if (mActiveTracks.size() == 0) { 8176 dprintf(fd, " No active clients\n"); 8177 } 8178 } 8179 8180 void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused) 8181 { 8182 const size_t SIZE = 256; 8183 char buffer[SIZE]; 8184 String8 result; 8185 8186 size_t numtracks = mActiveTracks.size(); 8187 dprintf(fd, " %zu Tracks", numtracks); 8188 if (numtracks) { 8189 MmapTrack::appendDumpHeader(result); 8190 for (size_t i = 0; i < numtracks ; ++i) { 8191 sp<MmapTrack> track = mActiveTracks[i]; 8192 track->dump(buffer, SIZE); 8193 result.append(buffer); 8194 } 8195 } else { 8196 dprintf(fd, "\n"); 8197 } 8198 write(fd, result.string(), result.size()); 8199 } 8200 8201 AudioFlinger::MmapPlaybackThread::MmapPlaybackThread( 8202 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id, 8203 AudioHwDevice *hwDev, AudioStreamOut *output, 8204 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady) 8205 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady), 8206 mStreamType(AUDIO_STREAM_MUSIC), 8207 mStreamVolume(1.0), mStreamMute(false), mOutput(output) 8208 { 8209 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id); 8210 mChannelCount = audio_channel_count_from_out_mask(mChannelMask); 8211 mMasterVolume = audioFlinger->masterVolume_l(); 8212 mMasterMute = audioFlinger->masterMute_l(); 8213 if (mAudioHwDev) { 8214 if (mAudioHwDev->canSetMasterVolume()) { 8215 mMasterVolume = 1.0; 8216 } 8217 8218 if (mAudioHwDev->canSetMasterMute()) { 8219 mMasterMute = false; 8220 } 8221 } 8222 } 8223 8224 void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr, 8225 audio_stream_type_t streamType, 8226 audio_session_t sessionId, 8227 const sp<MmapStreamCallback>& callback, 8228 audio_port_handle_t portId) 8229 { 8230 MmapThread::configure(attr, streamType, sessionId, callback, portId); 8231 mStreamType = streamType; 8232 } 8233 8234 AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput() 8235 { 8236 Mutex::Autolock _l(mLock); 8237 AudioStreamOut *output = mOutput; 8238 mOutput = NULL; 8239 return output; 8240 } 8241 8242 void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value) 8243 { 8244 Mutex::Autolock _l(mLock); 8245 // Don't apply master volume in SW if our HAL can do it for us. 8246 if (mAudioHwDev && 8247 mAudioHwDev->canSetMasterVolume()) { 8248 mMasterVolume = 1.0; 8249 } else { 8250 mMasterVolume = value; 8251 } 8252 } 8253 8254 void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted) 8255 { 8256 Mutex::Autolock _l(mLock); 8257 // Don't apply master mute in SW if our HAL can do it for us. 8258 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) { 8259 mMasterMute = false; 8260 } else { 8261 mMasterMute = muted; 8262 } 8263 } 8264 8265 void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value) 8266 { 8267 Mutex::Autolock _l(mLock); 8268 if (stream == mStreamType) { 8269 mStreamVolume = value; 8270 broadcast_l(); 8271 } 8272 } 8273 8274 float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const 8275 { 8276 Mutex::Autolock _l(mLock); 8277 if (stream == mStreamType) { 8278 return mStreamVolume; 8279 } 8280 return 0.0f; 8281 } 8282 8283 void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted) 8284 { 8285 Mutex::Autolock _l(mLock); 8286 if (stream == mStreamType) { 8287 mStreamMute= muted; 8288 broadcast_l(); 8289 } 8290 } 8291 8292 void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType) 8293 { 8294 Mutex::Autolock _l(mLock); 8295 if (streamType == mStreamType) { 8296 for (const sp<MmapTrack> &track : mActiveTracks) { 8297 track->invalidate(); 8298 } 8299 broadcast_l(); 8300 } 8301 } 8302 8303 void AudioFlinger::MmapPlaybackThread::processVolume_l() 8304 { 8305 float volume; 8306 8307 if (mMasterMute || mStreamMute) { 8308 volume = 0; 8309 } else { 8310 volume = mMasterVolume * mStreamVolume; 8311 } 8312 8313 if (volume != mHalVolFloat) { 8314 mHalVolFloat = volume; 8315 8316 // Convert volumes from float to 8.24 8317 uint32_t vol = (uint32_t)(volume * (1 << 24)); 8318 8319 // Delegate volume control to effect in track effect chain if needed 8320 // only one effect chain can be present on DirectOutputThread, so if 8321 // there is one, the track is connected to it 8322 if (!mEffectChains.isEmpty()) { 8323 mEffectChains[0]->setVolume_l(&vol, &vol); 8324 volume = (float)vol / (1 << 24); 8325 } 8326 // Try to use HW volume control and fall back to SW control if not implemented 8327 if (mOutput->stream->setVolume(volume, volume) != NO_ERROR) { 8328 sp<MmapStreamCallback> callback = mCallback.promote(); 8329 if (callback != 0) { 8330 int channelCount; 8331 if (isOutput()) { 8332 channelCount = audio_channel_count_from_out_mask(mChannelMask); 8333 } else { 8334 channelCount = audio_channel_count_from_in_mask(mChannelMask); 8335 } 8336 Vector<float> values; 8337 for (int i = 0; i < channelCount; i++) { 8338 values.add(volume); 8339 } 8340 callback->onVolumeChanged(mChannelMask, values); 8341 } else { 8342 ALOGW("Could not set MMAP stream volume: no volume callback!"); 8343 } 8344 } 8345 } 8346 } 8347 8348 void AudioFlinger::MmapPlaybackThread::checkSilentMode_l() 8349 { 8350 if (!mMasterMute) { 8351 char value[PROPERTY_VALUE_MAX]; 8352 if (property_get("ro.audio.silent", value, "0") > 0) { 8353 char *endptr; 8354 unsigned long ul = strtoul(value, &endptr, 0); 8355 if (*endptr == '\0' && ul != 0) { 8356 ALOGD("Silence is golden"); 8357 // The setprop command will not allow a property to be changed after 8358 // the first time it is set, so we don't have to worry about un-muting. 8359 setMasterMute_l(true); 8360 } 8361 } 8362 } 8363 } 8364 8365 void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args) 8366 { 8367 MmapThread::dumpInternals(fd, args); 8368 8369 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n", 8370 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute); 8371 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute); 8372 } 8373 8374 AudioFlinger::MmapCaptureThread::MmapCaptureThread( 8375 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id, 8376 AudioHwDevice *hwDev, AudioStreamIn *input, 8377 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady) 8378 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady), 8379 mInput(input) 8380 { 8381 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id); 8382 mChannelCount = audio_channel_count_from_in_mask(mChannelMask); 8383 } 8384 8385 AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput() 8386 { 8387 Mutex::Autolock _l(mLock); 8388 AudioStreamIn *input = mInput; 8389 mInput = NULL; 8390 return input; 8391 } 8392 } // namespace android 8393