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 <media/audiohal/EffectsFactoryHalInterface.h> 60 #include <media/audiohal/StreamHalInterface.h> 61 62 #include "AudioFlinger.h" 63 #include "FastMixer.h" 64 #include "FastCapture.h" 65 #include "ServiceUtilities.h" 66 #include "mediautils/SchedulingPolicyService.h" 67 68 #ifdef ADD_BATTERY_DATA 69 #include <media/IMediaPlayerService.h> 70 #include <media/IMediaDeathNotifier.h> 71 #endif 72 73 #ifdef DEBUG_CPU_USAGE 74 #include <cpustats/CentralTendencyStatistics.h> 75 #include <cpustats/ThreadCpuUsage.h> 76 #endif 77 78 #include "AutoPark.h" 79 80 #include <pthread.h> 81 #include "TypedLogger.h" 82 83 // ---------------------------------------------------------------------------- 84 85 // Note: the following macro is used for extremely verbose logging message. In 86 // order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to 87 // 0; but one side effect of this is to turn all LOGV's as well. Some messages 88 // are so verbose that we want to suppress them even when we have ALOG_ASSERT 89 // turned on. Do not uncomment the #def below unless you really know what you 90 // are doing and want to see all of the extremely verbose messages. 91 //#define VERY_VERY_VERBOSE_LOGGING 92 #ifdef VERY_VERY_VERBOSE_LOGGING 93 #define ALOGVV ALOGV 94 #else 95 #define ALOGVV(a...) do { } while(0) 96 #endif 97 98 // TODO: Move these macro/inlines to a header file. 99 #define max(a, b) ((a) > (b) ? (a) : (b)) 100 template <typename T> 101 static inline T min(const T& a, const T& b) 102 { 103 return a < b ? a : b; 104 } 105 106 namespace android { 107 108 // retry counts for buffer fill timeout 109 // 50 * ~20msecs = 1 second 110 static const int8_t kMaxTrackRetries = 50; 111 static const int8_t kMaxTrackStartupRetries = 50; 112 // allow less retry attempts on direct output thread. 113 // direct outputs can be a scarce resource in audio hardware and should 114 // be released as quickly as possible. 115 static const int8_t kMaxTrackRetriesDirect = 2; 116 117 118 119 // don't warn about blocked writes or record buffer overflows more often than this 120 static const nsecs_t kWarningThrottleNs = seconds(5); 121 122 // RecordThread loop sleep time upon application overrun or audio HAL read error 123 static const int kRecordThreadSleepUs = 5000; 124 125 // maximum time to wait in sendConfigEvent_l() for a status to be received 126 static const nsecs_t kConfigEventTimeoutNs = seconds(2); 127 128 // minimum sleep time for the mixer thread loop when tracks are active but in underrun 129 static const uint32_t kMinThreadSleepTimeUs = 5000; 130 // maximum divider applied to the active sleep time in the mixer thread loop 131 static const uint32_t kMaxThreadSleepTimeShift = 2; 132 133 // minimum normal sink buffer size, expressed in milliseconds rather than frames 134 // FIXME This should be based on experimentally observed scheduling jitter 135 static const uint32_t kMinNormalSinkBufferSizeMs = 20; 136 // maximum normal sink buffer size 137 static const uint32_t kMaxNormalSinkBufferSizeMs = 24; 138 139 // minimum capture buffer size in milliseconds to _not_ need a fast capture thread 140 // FIXME This should be based on experimentally observed scheduling jitter 141 static const uint32_t kMinNormalCaptureBufferSizeMs = 12; 142 143 // Offloaded output thread standby delay: allows track transition without going to standby 144 static const nsecs_t kOffloadStandbyDelayNs = seconds(1); 145 146 // Direct output thread minimum sleep time in idle or active(underrun) state 147 static const nsecs_t kDirectMinSleepTimeUs = 10000; 148 149 // The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good 150 // balance between power consumption and latency, and allows threads to be scheduled reliably 151 // by the CFS scheduler. 152 // FIXME Express other hardcoded references to 20ms with references to this constant and move 153 // it appropriately. 154 #define FMS_20 20 155 156 // Whether to use fast mixer 157 static const enum { 158 FastMixer_Never, // never initialize or use: for debugging only 159 FastMixer_Always, // always initialize and use, even if not needed: for debugging only 160 // normal mixer multiplier is 1 161 FastMixer_Static, // initialize if needed, then use all the time if initialized, 162 // multiplier is calculated based on min & max normal mixer buffer size 163 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load, 164 // multiplier is calculated based on min & max normal mixer buffer size 165 // FIXME for FastMixer_Dynamic: 166 // Supporting this option will require fixing HALs that can't handle large writes. 167 // For example, one HAL implementation returns an error from a large write, 168 // and another HAL implementation corrupts memory, possibly in the sample rate converter. 169 // We could either fix the HAL implementations, or provide a wrapper that breaks 170 // up large writes into smaller ones, and the wrapper would need to deal with scheduler. 171 } kUseFastMixer = FastMixer_Static; 172 173 // Whether to use fast capture 174 static const enum { 175 FastCapture_Never, // never initialize or use: for debugging only 176 FastCapture_Always, // always initialize and use, even if not needed: for debugging only 177 FastCapture_Static, // initialize if needed, then use all the time if initialized 178 } kUseFastCapture = FastCapture_Static; 179 180 // Priorities for requestPriority 181 static const int kPriorityAudioApp = 2; 182 static const int kPriorityFastMixer = 3; 183 static const int kPriorityFastCapture = 3; 184 185 // IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the 186 // track buffer in shared memory. Zero on input means to use a default value. For fast tracks, 187 // AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'. 188 189 // This is the default value, if not specified by property. 190 static const int kFastTrackMultiplier = 2; 191 192 // The minimum and maximum allowed values 193 static const int kFastTrackMultiplierMin = 1; 194 static const int kFastTrackMultiplierMax = 2; 195 196 // The actual value to use, which can be specified per-device via property af.fast_track_multiplier. 197 static int sFastTrackMultiplier = kFastTrackMultiplier; 198 199 // See Thread::readOnlyHeap(). 200 // Initially this heap is used to allocate client buffers for "fast" AudioRecord. 201 // Eventually it will be the single buffer that FastCapture writes into via HAL read(), 202 // and that all "fast" AudioRecord clients read from. In either case, the size can be small. 203 static const size_t kRecordThreadReadOnlyHeapSize = 0x4000; 204 205 // ---------------------------------------------------------------------------- 206 207 static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT; 208 209 static void sFastTrackMultiplierInit() 210 { 211 char value[PROPERTY_VALUE_MAX]; 212 if (property_get("af.fast_track_multiplier", value, NULL) > 0) { 213 char *endptr; 214 unsigned long ul = strtoul(value, &endptr, 0); 215 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) { 216 sFastTrackMultiplier = (int) ul; 217 } 218 } 219 } 220 221 // ---------------------------------------------------------------------------- 222 223 #ifdef ADD_BATTERY_DATA 224 // To collect the amplifier usage 225 static void addBatteryData(uint32_t params) { 226 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService(); 227 if (service == NULL) { 228 // it already logged 229 return; 230 } 231 232 service->addBatteryData(params); 233 } 234 #endif 235 236 // Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset 237 struct { 238 // call when you acquire a partial wakelock 239 void acquire(const sp<IBinder> &wakeLockToken) { 240 pthread_mutex_lock(&mLock); 241 if (wakeLockToken.get() == nullptr) { 242 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME); 243 } else { 244 if (mCount == 0) { 245 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME); 246 } 247 ++mCount; 248 } 249 pthread_mutex_unlock(&mLock); 250 } 251 252 // call when you release a partial wakelock. 253 void release(const sp<IBinder> &wakeLockToken) { 254 if (wakeLockToken.get() == nullptr) { 255 return; 256 } 257 pthread_mutex_lock(&mLock); 258 if (--mCount < 0) { 259 ALOGE("negative wakelock count"); 260 mCount = 0; 261 } 262 pthread_mutex_unlock(&mLock); 263 } 264 265 // retrieves the boottime timebase offset from monotonic. 266 int64_t getBoottimeOffset() { 267 pthread_mutex_lock(&mLock); 268 int64_t boottimeOffset = mBoottimeOffset; 269 pthread_mutex_unlock(&mLock); 270 return boottimeOffset; 271 } 272 273 // Adjusts the timebase offset between TIMEBASE_MONOTONIC 274 // and the selected timebase. 275 // Currently only TIMEBASE_BOOTTIME is allowed. 276 // 277 // This only needs to be called upon acquiring the first partial wakelock 278 // after all other partial wakelocks are released. 279 // 280 // We do an empirical measurement of the offset rather than parsing 281 // /proc/timer_list since the latter is not a formal kernel ABI. 282 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) { 283 int clockbase; 284 switch (timebase) { 285 case ExtendedTimestamp::TIMEBASE_BOOTTIME: 286 clockbase = SYSTEM_TIME_BOOTTIME; 287 break; 288 default: 289 LOG_ALWAYS_FATAL("invalid timebase %d", timebase); 290 break; 291 } 292 // try three times to get the clock offset, choose the one 293 // with the minimum gap in measurements. 294 const int tries = 3; 295 nsecs_t bestGap, measured; 296 for (int i = 0; i < tries; ++i) { 297 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC); 298 const nsecs_t tbase = systemTime(clockbase); 299 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC); 300 const nsecs_t gap = tmono2 - tmono; 301 if (i == 0 || gap < bestGap) { 302 bestGap = gap; 303 measured = tbase - ((tmono + tmono2) >> 1); 304 } 305 } 306 307 // to avoid micro-adjusting, we don't change the timebase 308 // unless it is significantly different. 309 // 310 // Assumption: It probably takes more than toleranceNs to 311 // suspend and resume the device. 312 static int64_t toleranceNs = 10000; // 10 us 313 if (llabs(*offset - measured) > toleranceNs) { 314 ALOGV("Adjusting timebase offset old: %lld new: %lld", 315 (long long)*offset, (long long)measured); 316 *offset = measured; 317 } 318 } 319 320 pthread_mutex_t mLock; 321 int32_t mCount; 322 int64_t mBoottimeOffset; 323 } gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization 324 325 // ---------------------------------------------------------------------------- 326 // CPU Stats 327 // ---------------------------------------------------------------------------- 328 329 class CpuStats { 330 public: 331 CpuStats(); 332 void sample(const String8 &title); 333 #ifdef DEBUG_CPU_USAGE 334 private: 335 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns 336 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns 337 338 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles 339 340 int mCpuNum; // thread's current CPU number 341 int mCpukHz; // frequency of thread's current CPU in kHz 342 #endif 343 }; 344 345 CpuStats::CpuStats() 346 #ifdef DEBUG_CPU_USAGE 347 : mCpuNum(-1), mCpukHz(-1) 348 #endif 349 { 350 } 351 352 void CpuStats::sample(const String8 &title 353 #ifndef DEBUG_CPU_USAGE 354 __unused 355 #endif 356 ) { 357 #ifdef DEBUG_CPU_USAGE 358 // get current thread's delta CPU time in wall clock ns 359 double wcNs; 360 bool valid = mCpuUsage.sampleAndEnable(wcNs); 361 362 // record sample for wall clock statistics 363 if (valid) { 364 mWcStats.sample(wcNs); 365 } 366 367 // get the current CPU number 368 int cpuNum = sched_getcpu(); 369 370 // get the current CPU frequency in kHz 371 int cpukHz = mCpuUsage.getCpukHz(cpuNum); 372 373 // check if either CPU number or frequency changed 374 if (cpuNum != mCpuNum || cpukHz != mCpukHz) { 375 mCpuNum = cpuNum; 376 mCpukHz = cpukHz; 377 // ignore sample for purposes of cycles 378 valid = false; 379 } 380 381 // if no change in CPU number or frequency, then record sample for cycle statistics 382 if (valid && mCpukHz > 0) { 383 double cycles = wcNs * cpukHz * 0.000001; 384 mHzStats.sample(cycles); 385 } 386 387 unsigned n = mWcStats.n(); 388 // mCpuUsage.elapsed() is expensive, so don't call it every loop 389 if ((n & 127) == 1) { 390 long long elapsed = mCpuUsage.elapsed(); 391 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) { 392 double perLoop = elapsed / (double) n; 393 double perLoop100 = perLoop * 0.01; 394 double perLoop1k = perLoop * 0.001; 395 double mean = mWcStats.mean(); 396 double stddev = mWcStats.stddev(); 397 double minimum = mWcStats.minimum(); 398 double maximum = mWcStats.maximum(); 399 double meanCycles = mHzStats.mean(); 400 double stddevCycles = mHzStats.stddev(); 401 double minCycles = mHzStats.minimum(); 402 double maxCycles = mHzStats.maximum(); 403 mCpuUsage.resetElapsed(); 404 mWcStats.reset(); 405 mHzStats.reset(); 406 ALOGD("CPU usage for %s over past %.1f secs\n" 407 " (%u mixer loops at %.1f mean ms per loop):\n" 408 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n" 409 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n" 410 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f", 411 title.string(), 412 elapsed * .000000001, n, perLoop * .000001, 413 mean * .001, 414 stddev * .001, 415 minimum * .001, 416 maximum * .001, 417 mean / perLoop100, 418 stddev / perLoop100, 419 minimum / perLoop100, 420 maximum / perLoop100, 421 meanCycles / perLoop1k, 422 stddevCycles / perLoop1k, 423 minCycles / perLoop1k, 424 maxCycles / perLoop1k); 425 426 } 427 } 428 #endif 429 }; 430 431 // ---------------------------------------------------------------------------- 432 // ThreadBase 433 // ---------------------------------------------------------------------------- 434 435 // static 436 const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type) 437 { 438 switch (type) { 439 case MIXER: 440 return "MIXER"; 441 case DIRECT: 442 return "DIRECT"; 443 case DUPLICATING: 444 return "DUPLICATING"; 445 case RECORD: 446 return "RECORD"; 447 case OFFLOAD: 448 return "OFFLOAD"; 449 case MMAP: 450 return "MMAP"; 451 default: 452 return "unknown"; 453 } 454 } 455 456 std::string devicesToString(audio_devices_t devices) 457 { 458 std::string result; 459 if (devices & AUDIO_DEVICE_BIT_IN) { 460 InputDeviceConverter::maskToString(devices, result); 461 } else { 462 OutputDeviceConverter::maskToString(devices, result); 463 } 464 return result; 465 } 466 467 std::string inputFlagsToString(audio_input_flags_t flags) 468 { 469 std::string result; 470 InputFlagConverter::maskToString(flags, result); 471 return result; 472 } 473 474 std::string outputFlagsToString(audio_output_flags_t flags) 475 { 476 std::string result; 477 OutputFlagConverter::maskToString(flags, result); 478 return result; 479 } 480 481 const char *sourceToString(audio_source_t source) 482 { 483 switch (source) { 484 case AUDIO_SOURCE_DEFAULT: return "default"; 485 case AUDIO_SOURCE_MIC: return "mic"; 486 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink"; 487 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink"; 488 case AUDIO_SOURCE_VOICE_CALL: return "voice call"; 489 case AUDIO_SOURCE_CAMCORDER: return "camcorder"; 490 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition"; 491 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication"; 492 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix"; 493 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed"; 494 case AUDIO_SOURCE_FM_TUNER: return "FM tuner"; 495 case AUDIO_SOURCE_HOTWORD: return "hotword"; 496 default: return "unknown"; 497 } 498 } 499 500 AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id, 501 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady) 502 : Thread(false /*canCallJava*/), 503 mType(type), 504 mAudioFlinger(audioFlinger), 505 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize 506 // are set by PlaybackThread::readOutputParameters_l() or 507 // RecordThread::readInputParameters_l() 508 //FIXME: mStandby should be true here. Is this some kind of hack? 509 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice), 510 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE), 511 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id), 512 // mName will be set by concrete (non-virtual) subclass 513 mDeathRecipient(new PMDeathRecipient(this)), 514 mSystemReady(systemReady), 515 mSignalPending(false) 516 { 517 memset(&mPatch, 0, sizeof(struct audio_patch)); 518 } 519 520 AudioFlinger::ThreadBase::~ThreadBase() 521 { 522 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns 523 mConfigEvents.clear(); 524 525 // do not lock the mutex in destructor 526 releaseWakeLock_l(); 527 if (mPowerManager != 0) { 528 sp<IBinder> binder = IInterface::asBinder(mPowerManager); 529 binder->unlinkToDeath(mDeathRecipient); 530 } 531 } 532 533 status_t AudioFlinger::ThreadBase::readyToRun() 534 { 535 status_t status = initCheck(); 536 if (status == NO_ERROR) { 537 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid()); 538 } else { 539 ALOGE("No working audio driver found."); 540 } 541 return status; 542 } 543 544 void AudioFlinger::ThreadBase::exit() 545 { 546 ALOGV("ThreadBase::exit"); 547 // do any cleanup required for exit to succeed 548 preExit(); 549 { 550 // This lock prevents the following race in thread (uniprocessor for illustration): 551 // if (!exitPending()) { 552 // // context switch from here to exit() 553 // // exit() calls requestExit(), what exitPending() observes 554 // // exit() calls signal(), which is dropped since no waiters 555 // // context switch back from exit() to here 556 // mWaitWorkCV.wait(...); 557 // // now thread is hung 558 // } 559 AutoMutex lock(mLock); 560 requestExit(); 561 mWaitWorkCV.broadcast(); 562 } 563 // When Thread::requestExitAndWait is made virtual and this method is renamed to 564 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();" 565 requestExitAndWait(); 566 } 567 568 status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs) 569 { 570 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string()); 571 Mutex::Autolock _l(mLock); 572 573 return sendSetParameterConfigEvent_l(keyValuePairs); 574 } 575 576 // sendConfigEvent_l() must be called with ThreadBase::mLock held 577 // Can temporarily release the lock if waiting for a reply from processConfigEvents_l(). 578 status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event) 579 { 580 status_t status = NO_ERROR; 581 582 if (event->mRequiresSystemReady && !mSystemReady) { 583 event->mWaitStatus = false; 584 mPendingConfigEvents.add(event); 585 return status; 586 } 587 mConfigEvents.add(event); 588 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType); 589 mWaitWorkCV.signal(); 590 mLock.unlock(); 591 { 592 Mutex::Autolock _l(event->mLock); 593 while (event->mWaitStatus) { 594 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) { 595 event->mStatus = TIMED_OUT; 596 event->mWaitStatus = false; 597 } 598 } 599 status = event->mStatus; 600 } 601 mLock.lock(); 602 return status; 603 } 604 605 void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid) 606 { 607 Mutex::Autolock _l(mLock); 608 sendIoConfigEvent_l(event, pid); 609 } 610 611 // sendIoConfigEvent_l() must be called with ThreadBase::mLock held 612 void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid) 613 { 614 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid); 615 sendConfigEvent_l(configEvent); 616 } 617 618 void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp) 619 { 620 Mutex::Autolock _l(mLock); 621 sendPrioConfigEvent_l(pid, tid, prio, forApp); 622 } 623 624 // sendPrioConfigEvent_l() must be called with ThreadBase::mLock held 625 void AudioFlinger::ThreadBase::sendPrioConfigEvent_l( 626 pid_t pid, pid_t tid, int32_t prio, bool forApp) 627 { 628 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp); 629 sendConfigEvent_l(configEvent); 630 } 631 632 // sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held 633 status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair) 634 { 635 sp<ConfigEvent> configEvent; 636 AudioParameter param(keyValuePair); 637 int value; 638 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) { 639 setMasterMono_l(value != 0); 640 if (param.size() == 1) { 641 return NO_ERROR; // should be a solo parameter - we don't pass down 642 } 643 param.remove(String8(AudioParameter::keyMonoOutput)); 644 configEvent = new SetParameterConfigEvent(param.toString()); 645 } else { 646 configEvent = new SetParameterConfigEvent(keyValuePair); 647 } 648 return sendConfigEvent_l(configEvent); 649 } 650 651 status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent( 652 const struct audio_patch *patch, 653 audio_patch_handle_t *handle) 654 { 655 Mutex::Autolock _l(mLock); 656 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle); 657 status_t status = sendConfigEvent_l(configEvent); 658 if (status == NO_ERROR) { 659 CreateAudioPatchConfigEventData *data = 660 (CreateAudioPatchConfigEventData *)configEvent->mData.get(); 661 *handle = data->mHandle; 662 } 663 return status; 664 } 665 666 status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent( 667 const audio_patch_handle_t handle) 668 { 669 Mutex::Autolock _l(mLock); 670 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle); 671 return sendConfigEvent_l(configEvent); 672 } 673 674 675 // post condition: mConfigEvents.isEmpty() 676 void AudioFlinger::ThreadBase::processConfigEvents_l() 677 { 678 bool configChanged = false; 679 680 while (!mConfigEvents.isEmpty()) { 681 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size()); 682 sp<ConfigEvent> event = mConfigEvents[0]; 683 mConfigEvents.removeAt(0); 684 switch (event->mType) { 685 case CFG_EVENT_PRIO: { 686 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get(); 687 // FIXME Need to understand why this has to be done asynchronously 688 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp, 689 true /*asynchronous*/); 690 if (err != 0) { 691 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d", 692 data->mPrio, data->mPid, data->mTid, err); 693 } 694 } break; 695 case CFG_EVENT_IO: { 696 IoConfigEventData *data = (IoConfigEventData *)event->mData.get(); 697 ioConfigChanged(data->mEvent, data->mPid); 698 } break; 699 case CFG_EVENT_SET_PARAMETER: { 700 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get(); 701 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) { 702 configChanged = true; 703 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed", 704 data->mKeyValuePairs.string()); 705 } 706 } break; 707 case CFG_EVENT_CREATE_AUDIO_PATCH: { 708 const audio_devices_t oldDevice = getDevice(); 709 CreateAudioPatchConfigEventData *data = 710 (CreateAudioPatchConfigEventData *)event->mData.get(); 711 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle); 712 const audio_devices_t newDevice = getDevice(); 713 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)", 714 (unsigned)oldDevice, devicesToString(oldDevice).c_str(), 715 (unsigned)newDevice, devicesToString(newDevice).c_str()); 716 } break; 717 case CFG_EVENT_RELEASE_AUDIO_PATCH: { 718 const audio_devices_t oldDevice = getDevice(); 719 ReleaseAudioPatchConfigEventData *data = 720 (ReleaseAudioPatchConfigEventData *)event->mData.get(); 721 event->mStatus = releaseAudioPatch_l(data->mHandle); 722 const audio_devices_t newDevice = getDevice(); 723 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)", 724 (unsigned)oldDevice, devicesToString(oldDevice).c_str(), 725 (unsigned)newDevice, devicesToString(newDevice).c_str()); 726 } break; 727 default: 728 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType); 729 break; 730 } 731 { 732 Mutex::Autolock _l(event->mLock); 733 if (event->mWaitStatus) { 734 event->mWaitStatus = false; 735 event->mCond.signal(); 736 } 737 } 738 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this); 739 } 740 741 if (configChanged) { 742 cacheParameters_l(); 743 } 744 } 745 746 String8 channelMaskToString(audio_channel_mask_t mask, bool output) { 747 String8 s; 748 const audio_channel_representation_t representation = 749 audio_channel_mask_get_representation(mask); 750 751 switch (representation) { 752 case AUDIO_CHANNEL_REPRESENTATION_POSITION: { 753 if (output) { 754 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, "); 755 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, "); 756 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, "); 757 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, "); 758 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, "); 759 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, "); 760 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, "); 761 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, "); 762 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, "); 763 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, "); 764 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, "); 765 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,"); 766 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, "); 767 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, "); 768 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, "); 769 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, "); 770 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " ); 771 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " ); 772 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, "); 773 } else { 774 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, "); 775 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, "); 776 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, "); 777 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, "); 778 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, "); 779 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, "); 780 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, "); 781 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, "); 782 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, "); 783 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, "); 784 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, "); 785 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, "); 786 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, "); 787 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, "); 788 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, "); 789 } 790 const int len = s.length(); 791 if (len > 2) { 792 (void) s.lockBuffer(len); // needed? 793 s.unlockBuffer(len - 2); // remove trailing ", " 794 } 795 return s; 796 } 797 case AUDIO_CHANNEL_REPRESENTATION_INDEX: 798 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask)); 799 return s; 800 default: 801 s.appendFormat("unknown mask, representation:%d bits:%#x", 802 representation, audio_channel_mask_get_bits(mask)); 803 return s; 804 } 805 } 806 807 void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused) 808 { 809 const size_t SIZE = 256; 810 char buffer[SIZE]; 811 String8 result; 812 813 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input", 814 this, mThreadName, getTid(), type(), threadTypeToString(type())); 815 816 bool locked = AudioFlinger::dumpTryLock(mLock); 817 if (!locked) { 818 dprintf(fd, " Thread may be deadlocked\n"); 819 } 820 821 dprintf(fd, " I/O handle: %d\n", mId); 822 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no"); 823 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate); 824 dprintf(fd, " HAL frame count: %zu\n", mFrameCount); 825 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str()); 826 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize); 827 dprintf(fd, " Channel count: %u\n", mChannelCount); 828 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask, 829 channelMaskToString(mChannelMask, mType != RECORD).string()); 830 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str()); 831 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize); 832 dprintf(fd, " Pending config events:"); 833 size_t numConfig = mConfigEvents.size(); 834 if (numConfig) { 835 for (size_t i = 0; i < numConfig; i++) { 836 mConfigEvents[i]->dump(buffer, SIZE); 837 dprintf(fd, "\n %s", buffer); 838 } 839 dprintf(fd, "\n"); 840 } else { 841 dprintf(fd, " none\n"); 842 } 843 // Note: output device may be used by capture threads for effects such as AEC. 844 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str()); 845 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str()); 846 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource)); 847 848 if (locked) { 849 mLock.unlock(); 850 } 851 } 852 853 void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args) 854 { 855 const size_t SIZE = 256; 856 char buffer[SIZE]; 857 String8 result; 858 859 size_t numEffectChains = mEffectChains.size(); 860 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains); 861 write(fd, buffer, strlen(buffer)); 862 863 for (size_t i = 0; i < numEffectChains; ++i) { 864 sp<EffectChain> chain = mEffectChains[i]; 865 if (chain != 0) { 866 chain->dump(fd, args); 867 } 868 } 869 } 870 871 void AudioFlinger::ThreadBase::acquireWakeLock() 872 { 873 Mutex::Autolock _l(mLock); 874 acquireWakeLock_l(); 875 } 876 877 String16 AudioFlinger::ThreadBase::getWakeLockTag() 878 { 879 switch (mType) { 880 case MIXER: 881 return String16("AudioMix"); 882 case DIRECT: 883 return String16("AudioDirectOut"); 884 case DUPLICATING: 885 return String16("AudioDup"); 886 case RECORD: 887 return String16("AudioIn"); 888 case OFFLOAD: 889 return String16("AudioOffload"); 890 case MMAP: 891 return String16("Mmap"); 892 default: 893 ALOG_ASSERT(false); 894 return String16("AudioUnknown"); 895 } 896 } 897 898 void AudioFlinger::ThreadBase::acquireWakeLock_l() 899 { 900 getPowerManager_l(); 901 if (mPowerManager != 0) { 902 sp<IBinder> binder = new BBinder(); 903 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids. 904 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK, 905 binder, 906 getWakeLockTag(), 907 String16("audioserver"), 908 true /* FIXME force oneway contrary to .aidl */); 909 if (status == NO_ERROR) { 910 mWakeLockToken = binder; 911 } 912 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status); 913 } 914 915 gBoottime.acquire(mWakeLockToken); 916 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] = 917 gBoottime.getBoottimeOffset(); 918 } 919 920 void AudioFlinger::ThreadBase::releaseWakeLock() 921 { 922 Mutex::Autolock _l(mLock); 923 releaseWakeLock_l(); 924 } 925 926 void AudioFlinger::ThreadBase::releaseWakeLock_l() 927 { 928 gBoottime.release(mWakeLockToken); 929 if (mWakeLockToken != 0) { 930 ALOGV("releaseWakeLock_l() %s", mThreadName); 931 if (mPowerManager != 0) { 932 mPowerManager->releaseWakeLock(mWakeLockToken, 0, 933 true /* FIXME force oneway contrary to .aidl */); 934 } 935 mWakeLockToken.clear(); 936 } 937 } 938 939 void AudioFlinger::ThreadBase::getPowerManager_l() { 940 if (mSystemReady && mPowerManager == 0) { 941 // use checkService() to avoid blocking if power service is not up yet 942 sp<IBinder> binder = 943 defaultServiceManager()->checkService(String16("power")); 944 if (binder == 0) { 945 ALOGW("Thread %s cannot connect to the power manager service", mThreadName); 946 } else { 947 mPowerManager = interface_cast<IPowerManager>(binder); 948 binder->linkToDeath(mDeathRecipient); 949 } 950 } 951 } 952 953 void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) { 954 getPowerManager_l(); 955 956 #if !LOG_NDEBUG 957 std::stringstream s; 958 for (uid_t uid : uids) { 959 s << uid << " "; 960 } 961 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str()); 962 #endif 963 964 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called. 965 if (mSystemReady) { 966 ALOGE("no wake lock to update, but system ready!"); 967 } else { 968 ALOGW("no wake lock to update, system not ready yet"); 969 } 970 return; 971 } 972 if (mPowerManager != 0) { 973 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints 974 status_t status = mPowerManager->updateWakeLockUids( 975 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(), 976 true /* FIXME force oneway contrary to .aidl */); 977 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status); 978 } 979 } 980 981 void AudioFlinger::ThreadBase::clearPowerManager() 982 { 983 Mutex::Autolock _l(mLock); 984 releaseWakeLock_l(); 985 mPowerManager.clear(); 986 } 987 988 void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused) 989 { 990 sp<ThreadBase> thread = mThread.promote(); 991 if (thread != 0) { 992 thread->clearPowerManager(); 993 } 994 ALOGW("power manager service died !!!"); 995 } 996 997 void AudioFlinger::ThreadBase::setEffectSuspended_l( 998 const effect_uuid_t *type, bool suspend, audio_session_t sessionId) 999 { 1000 sp<EffectChain> chain = getEffectChain_l(sessionId); 1001 if (chain != 0) { 1002 if (type != NULL) { 1003 chain->setEffectSuspended_l(type, suspend); 1004 } else { 1005 chain->setEffectSuspendedAll_l(suspend); 1006 } 1007 } 1008 1009 updateSuspendedSessions_l(type, suspend, sessionId); 1010 } 1011 1012 void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain) 1013 { 1014 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId()); 1015 if (index < 0) { 1016 return; 1017 } 1018 1019 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects = 1020 mSuspendedSessions.valueAt(index); 1021 1022 for (size_t i = 0; i < sessionEffects.size(); i++) { 1023 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i); 1024 for (int j = 0; j < desc->mRefCount; j++) { 1025 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) { 1026 chain->setEffectSuspendedAll_l(true); 1027 } else { 1028 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x", 1029 desc->mType.timeLow); 1030 chain->setEffectSuspended_l(&desc->mType, true); 1031 } 1032 } 1033 } 1034 } 1035 1036 void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type, 1037 bool suspend, 1038 audio_session_t sessionId) 1039 { 1040 ssize_t index = mSuspendedSessions.indexOfKey(sessionId); 1041 1042 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects; 1043 1044 if (suspend) { 1045 if (index >= 0) { 1046 sessionEffects = mSuspendedSessions.valueAt(index); 1047 } else { 1048 mSuspendedSessions.add(sessionId, sessionEffects); 1049 } 1050 } else { 1051 if (index < 0) { 1052 return; 1053 } 1054 sessionEffects = mSuspendedSessions.valueAt(index); 1055 } 1056 1057 1058 int key = EffectChain::kKeyForSuspendAll; 1059 if (type != NULL) { 1060 key = type->timeLow; 1061 } 1062 index = sessionEffects.indexOfKey(key); 1063 1064 sp<SuspendedSessionDesc> desc; 1065 if (suspend) { 1066 if (index >= 0) { 1067 desc = sessionEffects.valueAt(index); 1068 } else { 1069 desc = new SuspendedSessionDesc(); 1070 if (type != NULL) { 1071 desc->mType = *type; 1072 } 1073 sessionEffects.add(key, desc); 1074 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key); 1075 } 1076 desc->mRefCount++; 1077 } else { 1078 if (index < 0) { 1079 return; 1080 } 1081 desc = sessionEffects.valueAt(index); 1082 if (--desc->mRefCount == 0) { 1083 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key); 1084 sessionEffects.removeItemsAt(index); 1085 if (sessionEffects.isEmpty()) { 1086 ALOGV("updateSuspendedSessions_l() restore removing session %d", 1087 sessionId); 1088 mSuspendedSessions.removeItem(sessionId); 1089 } 1090 } 1091 } 1092 if (!sessionEffects.isEmpty()) { 1093 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects); 1094 } 1095 } 1096 1097 void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect, 1098 bool enabled, 1099 audio_session_t sessionId) 1100 { 1101 Mutex::Autolock _l(mLock); 1102 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId); 1103 } 1104 1105 void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect, 1106 bool enabled, 1107 audio_session_t sessionId) 1108 { 1109 if (mType != RECORD) { 1110 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on 1111 // another session. This gives the priority to well behaved effect control panels 1112 // and applications not using global effects. 1113 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect 1114 // global effects 1115 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) { 1116 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX); 1117 } 1118 } 1119 1120 sp<EffectChain> chain = getEffectChain_l(sessionId); 1121 if (chain != 0) { 1122 chain->checkSuspendOnEffectEnabled(effect, enabled); 1123 } 1124 } 1125 1126 // checkEffectCompatibility_l() must be called with ThreadBase::mLock held 1127 status_t AudioFlinger::RecordThread::checkEffectCompatibility_l( 1128 const effect_descriptor_t *desc, audio_session_t sessionId) 1129 { 1130 // No global effect sessions on record threads 1131 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) { 1132 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s", 1133 desc->name, mThreadName); 1134 return BAD_VALUE; 1135 } 1136 // only pre processing effects on record thread 1137 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) { 1138 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s", 1139 desc->name, mThreadName); 1140 return BAD_VALUE; 1141 } 1142 1143 // always allow effects without processing load or latency 1144 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) { 1145 return NO_ERROR; 1146 } 1147 1148 audio_input_flags_t flags = mInput->flags; 1149 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) { 1150 if (flags & AUDIO_INPUT_FLAG_RAW) { 1151 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode", 1152 desc->name, mThreadName); 1153 return BAD_VALUE; 1154 } 1155 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) { 1156 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode", 1157 desc->name, mThreadName); 1158 return BAD_VALUE; 1159 } 1160 } 1161 return NO_ERROR; 1162 } 1163 1164 // checkEffectCompatibility_l() must be called with ThreadBase::mLock held 1165 status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l( 1166 const effect_descriptor_t *desc, audio_session_t sessionId) 1167 { 1168 // no preprocessing on playback threads 1169 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) { 1170 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback" 1171 " thread %s", desc->name, mThreadName); 1172 return BAD_VALUE; 1173 } 1174 1175 // always allow effects without processing load or latency 1176 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) { 1177 return NO_ERROR; 1178 } 1179 1180 switch (mType) { 1181 case MIXER: { 1182 #ifndef MULTICHANNEL_EFFECT_CHAIN 1183 // Reject any effect on mixer multichannel sinks. 1184 // TODO: fix both format and multichannel issues with effects. 1185 if (mChannelCount != FCC_2) { 1186 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER" 1187 " thread %s", desc->name, mChannelCount, mThreadName); 1188 return BAD_VALUE; 1189 } 1190 #endif 1191 audio_output_flags_t flags = mOutput->flags; 1192 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) { 1193 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) { 1194 // global effects are applied only to non fast tracks if they are SW 1195 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) { 1196 break; 1197 } 1198 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) { 1199 // only post processing on output stage session 1200 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) { 1201 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed" 1202 " on output stage session", desc->name); 1203 return BAD_VALUE; 1204 } 1205 } else { 1206 // no restriction on effects applied on non fast tracks 1207 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) { 1208 break; 1209 } 1210 } 1211 1212 if (flags & AUDIO_OUTPUT_FLAG_RAW) { 1213 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode", 1214 desc->name); 1215 return BAD_VALUE; 1216 } 1217 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) { 1218 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread" 1219 " in fast mode", desc->name); 1220 return BAD_VALUE; 1221 } 1222 } 1223 } break; 1224 case OFFLOAD: 1225 // nothing actionable on offload threads, if the effect: 1226 // - is offloadable: the effect can be created 1227 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable() 1228 // will take care of invalidating the tracks of the thread 1229 break; 1230 case DIRECT: 1231 // Reject any effect on Direct output threads for now, since the format of 1232 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo). 1233 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s", 1234 desc->name, mThreadName); 1235 return BAD_VALUE; 1236 case DUPLICATING: 1237 #ifndef MULTICHANNEL_EFFECT_CHAIN 1238 // Reject any effect on mixer multichannel sinks. 1239 // TODO: fix both format and multichannel issues with effects. 1240 if (mChannelCount != FCC_2) { 1241 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)" 1242 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName); 1243 return BAD_VALUE; 1244 } 1245 #endif 1246 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) { 1247 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING" 1248 " thread %s", desc->name, mThreadName); 1249 return BAD_VALUE; 1250 } 1251 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) { 1252 ALOGW("checkEffectCompatibility_l(): post processing effect %s on" 1253 " DUPLICATING thread %s", desc->name, mThreadName); 1254 return BAD_VALUE; 1255 } 1256 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) { 1257 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on" 1258 " DUPLICATING thread %s", desc->name, mThreadName); 1259 return BAD_VALUE; 1260 } 1261 break; 1262 default: 1263 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType); 1264 } 1265 1266 return NO_ERROR; 1267 } 1268 1269 // ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held 1270 sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l( 1271 const sp<AudioFlinger::Client>& client, 1272 const sp<IEffectClient>& effectClient, 1273 int32_t priority, 1274 audio_session_t sessionId, 1275 effect_descriptor_t *desc, 1276 int *enabled, 1277 status_t *status, 1278 bool pinned) 1279 { 1280 sp<EffectModule> effect; 1281 sp<EffectHandle> handle; 1282 status_t lStatus; 1283 sp<EffectChain> chain; 1284 bool chainCreated = false; 1285 bool effectCreated = false; 1286 bool effectRegistered = false; 1287 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; 1288 1289 lStatus = initCheck(); 1290 if (lStatus != NO_ERROR) { 1291 ALOGW("createEffect_l() Audio driver not initialized."); 1292 goto Exit; 1293 } 1294 1295 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId); 1296 1297 { // scope for mLock 1298 Mutex::Autolock _l(mLock); 1299 1300 lStatus = checkEffectCompatibility_l(desc, sessionId); 1301 if (lStatus != NO_ERROR) { 1302 goto Exit; 1303 } 1304 1305 // check for existing effect chain with the requested audio session 1306 chain = getEffectChain_l(sessionId); 1307 if (chain == 0) { 1308 // create a new chain for this session 1309 ALOGV("createEffect_l() new effect chain for session %d", sessionId); 1310 chain = new EffectChain(this, sessionId); 1311 addEffectChain_l(chain); 1312 chain->setStrategy(getStrategyForSession_l(sessionId)); 1313 chainCreated = true; 1314 } else { 1315 effect = chain->getEffectFromDesc_l(desc); 1316 } 1317 1318 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get()); 1319 1320 if (effect == 0) { 1321 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT); 1322 // Check CPU and memory usage 1323 lStatus = AudioSystem::registerEffect( 1324 desc, mId, chain->strategy(), sessionId, effectId); 1325 if (lStatus != NO_ERROR) { 1326 goto Exit; 1327 } 1328 effectRegistered = true; 1329 // create a new effect module if none present in the chain 1330 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned); 1331 if (lStatus != NO_ERROR) { 1332 goto Exit; 1333 } 1334 effectCreated = true; 1335 1336 effect->setDevice(mOutDevice); 1337 effect->setDevice(mInDevice); 1338 effect->setMode(mAudioFlinger->getMode()); 1339 effect->setAudioSource(mAudioSource); 1340 } 1341 // create effect handle and connect it to effect module 1342 handle = new EffectHandle(effect, client, effectClient, priority); 1343 lStatus = handle->initCheck(); 1344 if (lStatus == OK) { 1345 lStatus = effect->addHandle(handle.get()); 1346 } 1347 if (enabled != NULL) { 1348 *enabled = (int)effect->isEnabled(); 1349 } 1350 } 1351 1352 Exit: 1353 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) { 1354 Mutex::Autolock _l(mLock); 1355 if (effectCreated) { 1356 chain->removeEffect_l(effect); 1357 } 1358 if (effectRegistered) { 1359 AudioSystem::unregisterEffect(effectId); 1360 } 1361 if (chainCreated) { 1362 removeEffectChain_l(chain); 1363 } 1364 // handle must be cleared by caller to avoid deadlock. 1365 } 1366 1367 *status = lStatus; 1368 return handle; 1369 } 1370 1371 void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle, 1372 bool unpinIfLast) 1373 { 1374 bool remove = false; 1375 sp<EffectModule> effect; 1376 { 1377 Mutex::Autolock _l(mLock); 1378 1379 effect = handle->effect().promote(); 1380 if (effect == 0) { 1381 return; 1382 } 1383 // restore suspended effects if the disconnected handle was enabled and the last one. 1384 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast); 1385 if (remove) { 1386 removeEffect_l(effect, true); 1387 } 1388 } 1389 if (remove) { 1390 mAudioFlinger->updateOrphanEffectChains(effect); 1391 AudioSystem::unregisterEffect(effect->id()); 1392 if (handle->enabled()) { 1393 checkSuspendOnEffectEnabled(effect, false, effect->sessionId()); 1394 } 1395 } 1396 } 1397 1398 sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId, 1399 int effectId) 1400 { 1401 Mutex::Autolock _l(mLock); 1402 return getEffect_l(sessionId, effectId); 1403 } 1404 1405 sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId, 1406 int effectId) 1407 { 1408 sp<EffectChain> chain = getEffectChain_l(sessionId); 1409 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0; 1410 } 1411 1412 // PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and 1413 // PlaybackThread::mLock held 1414 status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect) 1415 { 1416 // check for existing effect chain with the requested audio session 1417 audio_session_t sessionId = effect->sessionId(); 1418 sp<EffectChain> chain = getEffectChain_l(sessionId); 1419 bool chainCreated = false; 1420 1421 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(), 1422 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x", 1423 this, effect->desc().name, effect->desc().flags); 1424 1425 if (chain == 0) { 1426 // create a new chain for this session 1427 ALOGV("addEffect_l() new effect chain for session %d", sessionId); 1428 chain = new EffectChain(this, sessionId); 1429 addEffectChain_l(chain); 1430 chain->setStrategy(getStrategyForSession_l(sessionId)); 1431 chainCreated = true; 1432 } 1433 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get()); 1434 1435 if (chain->getEffectFromId_l(effect->id()) != 0) { 1436 ALOGW("addEffect_l() %p effect %s already present in chain %p", 1437 this, effect->desc().name, chain.get()); 1438 return BAD_VALUE; 1439 } 1440 1441 effect->setOffloaded(mType == OFFLOAD, mId); 1442 1443 status_t status = chain->addEffect_l(effect); 1444 if (status != NO_ERROR) { 1445 if (chainCreated) { 1446 removeEffectChain_l(chain); 1447 } 1448 return status; 1449 } 1450 1451 effect->setDevice(mOutDevice); 1452 effect->setDevice(mInDevice); 1453 effect->setMode(mAudioFlinger->getMode()); 1454 effect->setAudioSource(mAudioSource); 1455 1456 return NO_ERROR; 1457 } 1458 1459 void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) { 1460 1461 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get()); 1462 effect_descriptor_t desc = effect->desc(); 1463 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { 1464 detachAuxEffect_l(effect->id()); 1465 } 1466 1467 sp<EffectChain> chain = effect->chain().promote(); 1468 if (chain != 0) { 1469 // remove effect chain if removing last effect 1470 if (chain->removeEffect_l(effect, release) == 0) { 1471 removeEffectChain_l(chain); 1472 } 1473 } else { 1474 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get()); 1475 } 1476 } 1477 1478 void AudioFlinger::ThreadBase::lockEffectChains_l( 1479 Vector< sp<AudioFlinger::EffectChain> >& effectChains) 1480 { 1481 effectChains = mEffectChains; 1482 for (size_t i = 0; i < mEffectChains.size(); i++) { 1483 mEffectChains[i]->lock(); 1484 } 1485 } 1486 1487 void AudioFlinger::ThreadBase::unlockEffectChains( 1488 const Vector< sp<AudioFlinger::EffectChain> >& effectChains) 1489 { 1490 for (size_t i = 0; i < effectChains.size(); i++) { 1491 effectChains[i]->unlock(); 1492 } 1493 } 1494 1495 sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId) 1496 { 1497 Mutex::Autolock _l(mLock); 1498 return getEffectChain_l(sessionId); 1499 } 1500 1501 sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId) 1502 const 1503 { 1504 size_t size = mEffectChains.size(); 1505 for (size_t i = 0; i < size; i++) { 1506 if (mEffectChains[i]->sessionId() == sessionId) { 1507 return mEffectChains[i]; 1508 } 1509 } 1510 return 0; 1511 } 1512 1513 void AudioFlinger::ThreadBase::setMode(audio_mode_t mode) 1514 { 1515 Mutex::Autolock _l(mLock); 1516 size_t size = mEffectChains.size(); 1517 for (size_t i = 0; i < size; i++) { 1518 mEffectChains[i]->setMode_l(mode); 1519 } 1520 } 1521 1522 void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config) 1523 { 1524 config->type = AUDIO_PORT_TYPE_MIX; 1525 config->ext.mix.handle = mId; 1526 config->sample_rate = mSampleRate; 1527 config->format = mFormat; 1528 config->channel_mask = mChannelMask; 1529 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK| 1530 AUDIO_PORT_CONFIG_FORMAT; 1531 } 1532 1533 void AudioFlinger::ThreadBase::systemReady() 1534 { 1535 Mutex::Autolock _l(mLock); 1536 if (mSystemReady) { 1537 return; 1538 } 1539 mSystemReady = true; 1540 1541 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) { 1542 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i)); 1543 } 1544 mPendingConfigEvents.clear(); 1545 } 1546 1547 template <typename T> 1548 ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) { 1549 ssize_t index = mActiveTracks.indexOf(track); 1550 if (index >= 0) { 1551 ALOGW("ActiveTracks<T>::add track %p already there", track.get()); 1552 return index; 1553 } 1554 logTrack("add", track); 1555 mActiveTracksGeneration++; 1556 mLatestActiveTrack = track; 1557 ++mBatteryCounter[track->uid()].second; 1558 mHasChanged = true; 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 logTrack("remove", track); 1570 mActiveTracksGeneration++; 1571 --mBatteryCounter[track->uid()].second; 1572 // mLatestActiveTrack is not cleared even if is the same as track. 1573 mHasChanged = true; 1574 return index; 1575 } 1576 1577 template <typename T> 1578 void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() { 1579 for (const sp<T> &track : mActiveTracks) { 1580 BatteryNotifier::getInstance().noteStopAudio(track->uid()); 1581 logTrack("clear", track); 1582 } 1583 mLastActiveTracksGeneration = mActiveTracksGeneration; 1584 if (!mActiveTracks.empty()) { mHasChanged = true; } 1585 mActiveTracks.clear(); 1586 mLatestActiveTrack.clear(); 1587 mBatteryCounter.clear(); 1588 } 1589 1590 template <typename T> 1591 void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState( 1592 sp<ThreadBase> thread, bool force) { 1593 // Updates ActiveTracks client uids to the thread wakelock. 1594 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) { 1595 thread->updateWakeLockUids_l(getWakeLockUids()); 1596 mLastActiveTracksGeneration = mActiveTracksGeneration; 1597 } 1598 1599 // Updates BatteryNotifier uids 1600 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) { 1601 const uid_t uid = it->first; 1602 ssize_t &previous = it->second.first; 1603 ssize_t ¤t = it->second.second; 1604 if (current > 0) { 1605 if (previous == 0) { 1606 BatteryNotifier::getInstance().noteStartAudio(uid); 1607 } 1608 previous = current; 1609 ++it; 1610 } else if (current == 0) { 1611 if (previous > 0) { 1612 BatteryNotifier::getInstance().noteStopAudio(uid); 1613 } 1614 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase. 1615 } else /* (current < 0) */ { 1616 LOG_ALWAYS_FATAL("negative battery count %zd", current); 1617 } 1618 } 1619 } 1620 1621 template <typename T> 1622 bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() { 1623 const bool hasChanged = mHasChanged; 1624 mHasChanged = false; 1625 return hasChanged; 1626 } 1627 1628 template <typename T> 1629 void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack( 1630 const char *funcName, const sp<T> &track) const { 1631 if (mLocalLog != nullptr) { 1632 String8 result; 1633 track->appendDump(result, false /* active */); 1634 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string()); 1635 } 1636 } 1637 1638 void AudioFlinger::ThreadBase::broadcast_l() 1639 { 1640 // Thread could be blocked waiting for async 1641 // so signal it to handle state changes immediately 1642 // If threadLoop is currently unlocked a signal of mWaitWorkCV will 1643 // be lost so we also flag to prevent it blocking on mWaitWorkCV 1644 mSignalPending = true; 1645 mWaitWorkCV.broadcast(); 1646 } 1647 1648 // ---------------------------------------------------------------------------- 1649 // Playback 1650 // ---------------------------------------------------------------------------- 1651 1652 AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, 1653 AudioStreamOut* output, 1654 audio_io_handle_t id, 1655 audio_devices_t device, 1656 type_t type, 1657 bool systemReady) 1658 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady), 1659 mNormalFrameCount(0), mSinkBuffer(NULL), 1660 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision), 1661 mMixerBuffer(NULL), 1662 mMixerBufferSize(0), 1663 mMixerBufferFormat(AUDIO_FORMAT_INVALID), 1664 mMixerBufferValid(false), 1665 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision), 1666 mEffectBuffer(NULL), 1667 mEffectBufferSize(0), 1668 mEffectBufferFormat(AUDIO_FORMAT_INVALID), 1669 mEffectBufferValid(false), 1670 mSuspended(0), mBytesWritten(0), 1671 mFramesWritten(0), 1672 mSuspendedFrames(0), 1673 mActiveTracks(&this->mLocalLog), 1674 // mStreamTypes[] initialized in constructor body 1675 mTracks(type == MIXER), 1676 mOutput(output), 1677 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false), 1678 mMixerStatus(MIXER_IDLE), 1679 mMixerStatusIgnoringFastTracks(MIXER_IDLE), 1680 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs), 1681 mBytesRemaining(0), 1682 mCurrentWriteLength(0), 1683 mUseAsyncWrite(false), 1684 mWriteAckSequence(0), 1685 mDrainSequence(0), 1686 mScreenState(AudioFlinger::mScreenState), 1687 // index 0 is reserved for normal mixer's submix 1688 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1), 1689 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false), 1690 mLeftVolFloat(-1.0), mRightVolFloat(-1.0) 1691 { 1692 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id); 1693 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName); 1694 1695 // Assumes constructor is called by AudioFlinger with it's mLock held, but 1696 // it would be safer to explicitly pass initial masterVolume/masterMute as 1697 // parameter. 1698 // 1699 // If the HAL we are using has support for master volume or master mute, 1700 // then do not attenuate or mute during mixing (just leave the volume at 1.0 1701 // and the mute set to false). 1702 mMasterVolume = audioFlinger->masterVolume_l(); 1703 mMasterMute = audioFlinger->masterMute_l(); 1704 if (mOutput && mOutput->audioHwDev) { 1705 if (mOutput->audioHwDev->canSetMasterVolume()) { 1706 mMasterVolume = 1.0; 1707 } 1708 1709 if (mOutput->audioHwDev->canSetMasterMute()) { 1710 mMasterMute = false; 1711 } 1712 } 1713 1714 readOutputParameters_l(); 1715 1716 // ++ operator does not compile 1717 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_FOR_POLICY_CNT; 1718 stream = (audio_stream_type_t) (stream + 1)) { 1719 mStreamTypes[stream].volume = 0.0f; 1720 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream); 1721 } 1722 // Audio patch volume is always max 1723 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f; 1724 mStreamTypes[AUDIO_STREAM_PATCH].mute = false; 1725 } 1726 1727 AudioFlinger::PlaybackThread::~PlaybackThread() 1728 { 1729 mAudioFlinger->unregisterWriter(mNBLogWriter); 1730 free(mSinkBuffer); 1731 free(mMixerBuffer); 1732 free(mEffectBuffer); 1733 } 1734 1735 void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args) 1736 { 1737 dumpInternals(fd, args); 1738 dumpTracks(fd, args); 1739 dumpEffectChains(fd, args); 1740 dprintf(fd, " Local log:\n"); 1741 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */); 1742 } 1743 1744 void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused) 1745 { 1746 String8 result; 1747 1748 result.appendFormat(" Stream volumes in dB: "); 1749 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) { 1750 const stream_type_t *st = &mStreamTypes[i]; 1751 if (i > 0) { 1752 result.appendFormat(", "); 1753 } 1754 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume)); 1755 if (st->mute) { 1756 result.append("M"); 1757 } 1758 } 1759 result.append("\n"); 1760 write(fd, result.string(), result.length()); 1761 result.clear(); 1762 1763 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way. 1764 FastTrackUnderruns underruns = getFastTrackUnderruns(0); 1765 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n", 1766 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty); 1767 1768 size_t numtracks = mTracks.size(); 1769 size_t numactive = mActiveTracks.size(); 1770 dprintf(fd, " %zu Tracks", numtracks); 1771 size_t numactiveseen = 0; 1772 const char *prefix = " "; 1773 if (numtracks) { 1774 dprintf(fd, " of which %zu are active\n", numactive); 1775 result.append(prefix); 1776 Track::appendDumpHeader(result); 1777 for (size_t i = 0; i < numtracks; ++i) { 1778 sp<Track> track = mTracks[i]; 1779 if (track != 0) { 1780 bool active = mActiveTracks.indexOf(track) >= 0; 1781 if (active) { 1782 numactiveseen++; 1783 } 1784 result.append(prefix); 1785 track->appendDump(result, active); 1786 } 1787 } 1788 } else { 1789 result.append("\n"); 1790 } 1791 if (numactiveseen != numactive) { 1792 // some tracks in the active list were not in the tracks list 1793 result.append(" The following tracks are in the active list but" 1794 " not in the track list\n"); 1795 result.append(prefix); 1796 Track::appendDumpHeader(result); 1797 for (size_t i = 0; i < numactive; ++i) { 1798 sp<Track> track = mActiveTracks[i]; 1799 if (mTracks.indexOf(track) < 0) { 1800 result.append(prefix); 1801 track->appendDump(result, true /* active */); 1802 } 1803 } 1804 } 1805 1806 write(fd, result.string(), result.size()); 1807 } 1808 1809 void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args) 1810 { 1811 dumpBase(fd, args); 1812 1813 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount); 1814 dprintf(fd, " Last write occurred (msecs): %llu\n", 1815 (unsigned long long) ns2ms(systemTime() - mLastWriteTime)); 1816 dprintf(fd, " Total writes: %d\n", mNumWrites); 1817 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites); 1818 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no"); 1819 dprintf(fd, " Suspend count: %d\n", mSuspended); 1820 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer); 1821 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer); 1822 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer); 1823 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask); 1824 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs); 1825 AudioStreamOut *output = mOutput; 1826 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE; 1827 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", 1828 output, flags, outputFlagsToString(flags).c_str()); 1829 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten); 1830 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames); 1831 if (mPipeSink.get() != nullptr) { 1832 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten()); 1833 } 1834 if (output != nullptr) { 1835 dprintf(fd, " Hal stream dump:\n"); 1836 (void)output->stream->dump(fd); 1837 } 1838 } 1839 1840 // Thread virtuals 1841 1842 void AudioFlinger::PlaybackThread::onFirstRef() 1843 { 1844 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO); 1845 } 1846 1847 // ThreadBase virtuals 1848 void AudioFlinger::PlaybackThread::preExit() 1849 { 1850 ALOGV(" preExit()"); 1851 // FIXME this is using hard-coded strings but in the future, this functionality will be 1852 // converted to use audio HAL extensions required to support tunneling 1853 status_t result = mOutput->stream->setParameters(String8("exiting=1")); 1854 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result); 1855 } 1856 1857 // PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held 1858 sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l( 1859 const sp<AudioFlinger::Client>& client, 1860 audio_stream_type_t streamType, 1861 const audio_attributes_t& attr, 1862 uint32_t *pSampleRate, 1863 audio_format_t format, 1864 audio_channel_mask_t channelMask, 1865 size_t *pFrameCount, 1866 size_t *pNotificationFrameCount, 1867 uint32_t notificationsPerBuffer, 1868 float speed, 1869 const sp<IMemory>& sharedBuffer, 1870 audio_session_t sessionId, 1871 audio_output_flags_t *flags, 1872 pid_t tid, 1873 uid_t uid, 1874 status_t *status, 1875 audio_port_handle_t portId) 1876 { 1877 size_t frameCount = *pFrameCount; 1878 size_t notificationFrameCount = *pNotificationFrameCount; 1879 sp<Track> track; 1880 status_t lStatus; 1881 audio_output_flags_t outputFlags = mOutput->flags; 1882 audio_output_flags_t requestedFlags = *flags; 1883 1884 if (*pSampleRate == 0) { 1885 *pSampleRate = mSampleRate; 1886 } 1887 uint32_t sampleRate = *pSampleRate; 1888 1889 // special case for FAST flag considered OK if fast mixer is present 1890 if (hasFastMixer()) { 1891 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST); 1892 } 1893 1894 // Check if requested flags are compatible with output stream flags 1895 if ((*flags & outputFlags) != *flags) { 1896 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)", 1897 *flags, outputFlags); 1898 *flags = (audio_output_flags_t)(*flags & outputFlags); 1899 } 1900 1901 // client expresses a preference for FAST, but we get the final say 1902 if (*flags & AUDIO_OUTPUT_FLAG_FAST) { 1903 if ( 1904 // PCM data 1905 audio_is_linear_pcm(format) && 1906 // TODO: extract as a data library function that checks that a computationally 1907 // expensive downmixer is not required: isFastOutputChannelConversion() 1908 (channelMask == mChannelMask || 1909 mChannelMask != AUDIO_CHANNEL_OUT_STEREO || 1910 (channelMask == AUDIO_CHANNEL_OUT_MONO 1911 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) && 1912 // hardware sample rate 1913 (sampleRate == mSampleRate) && 1914 // normal mixer has an associated fast mixer 1915 hasFastMixer() && 1916 // there are sufficient fast track slots available 1917 (mFastTrackAvailMask != 0) 1918 // FIXME test that MixerThread for this fast track has a capable output HAL 1919 // FIXME add a permission test also? 1920 ) { 1921 // static tracks can have any nonzero framecount, streaming tracks check against minimum. 1922 if (sharedBuffer == 0) { 1923 // read the fast track multiplier property the first time it is needed 1924 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit); 1925 if (ok != 0) { 1926 ALOGE("%s pthread_once failed: %d", __func__, ok); 1927 } 1928 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0 1929 } 1930 1931 // check compatibility with audio effects. 1932 { // scope for mLock 1933 Mutex::Autolock _l(mLock); 1934 for (audio_session_t session : { 1935 AUDIO_SESSION_OUTPUT_STAGE, 1936 AUDIO_SESSION_OUTPUT_MIX, 1937 sessionId, 1938 }) { 1939 sp<EffectChain> chain = getEffectChain_l(session); 1940 if (chain.get() != nullptr) { 1941 audio_output_flags_t old = *flags; 1942 chain->checkOutputFlagCompatibility(flags); 1943 if (old != *flags) { 1944 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x", 1945 (int)session, (int)old, (int)*flags); 1946 } 1947 } 1948 } 1949 } 1950 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0, 1951 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu", 1952 frameCount, mFrameCount); 1953 } else { 1954 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu " 1955 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x " 1956 "sampleRate=%u mSampleRate=%u " 1957 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x", 1958 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat, 1959 audio_is_linear_pcm(format), 1960 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask); 1961 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST); 1962 } 1963 } 1964 1965 if (!audio_has_proportional_frames(format)) { 1966 if (sharedBuffer != 0) { 1967 // Same comment as below about ignoring frameCount parameter for set() 1968 frameCount = sharedBuffer->size(); 1969 } else if (frameCount == 0) { 1970 frameCount = mNormalFrameCount; 1971 } 1972 if (notificationFrameCount != frameCount) { 1973 notificationFrameCount = frameCount; 1974 } 1975 } else if (sharedBuffer != 0) { 1976 // FIXME: Ensure client side memory buffers need 1977 // not have additional alignment beyond sample 1978 // (e.g. 16 bit stereo accessed as 32 bit frame). 1979 size_t alignment = audio_bytes_per_sample(format); 1980 if (alignment & 1) { 1981 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java). 1982 alignment = 1; 1983 } 1984 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask); 1985 size_t frameSize = channelCount * audio_bytes_per_sample(format); 1986 if (channelCount > 1) { 1987 // More than 2 channels does not require stronger alignment than stereo 1988 alignment <<= 1; 1989 } 1990 if (((uintptr_t)sharedBuffer->pointer() & (alignment - 1)) != 0) { 1991 ALOGE("Invalid buffer alignment: address %p, channel count %u", 1992 sharedBuffer->pointer(), channelCount); 1993 lStatus = BAD_VALUE; 1994 goto Exit; 1995 } 1996 1997 // When initializing a shared buffer AudioTrack via constructors, 1998 // there's no frameCount parameter. 1999 // But when initializing a shared buffer AudioTrack via set(), 2000 // there _is_ a frameCount parameter. We silently ignore it. 2001 frameCount = sharedBuffer->size() / frameSize; 2002 } else { 2003 size_t minFrameCount = 0; 2004 // For fast tracks we try to respect the application's request for notifications per buffer. 2005 if (*flags & AUDIO_OUTPUT_FLAG_FAST) { 2006 if (notificationsPerBuffer > 0) { 2007 // Avoid possible arithmetic overflow during multiplication. 2008 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) { 2009 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu", 2010 notificationsPerBuffer, mFrameCount); 2011 } else { 2012 minFrameCount = mFrameCount * notificationsPerBuffer; 2013 } 2014 } 2015 } else { 2016 // For normal PCM streaming tracks, update minimum frame count. 2017 // Buffer depth is forced to be at least 2 x the normal mixer frame count and 2018 // cover audio hardware latency. 2019 // This is probably too conservative, but legacy application code may depend on it. 2020 // If you change this calculation, also review the start threshold which is related. 2021 uint32_t latencyMs = latency_l(); 2022 if (latencyMs == 0) { 2023 ALOGE("Error when retrieving output stream latency"); 2024 lStatus = UNKNOWN_ERROR; 2025 goto Exit; 2026 } 2027 2028 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount, 2029 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/); 2030 2031 } 2032 if (frameCount < minFrameCount) { 2033 frameCount = minFrameCount; 2034 } 2035 } 2036 2037 // Make sure that application is notified with sufficient margin before underrun. 2038 // The client can divide the AudioTrack buffer into sub-buffers, 2039 // and expresses its desire to server as the notification frame count. 2040 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) { 2041 size_t maxNotificationFrames; 2042 if (*flags & AUDIO_OUTPUT_FLAG_FAST) { 2043 // notify every HAL buffer, regardless of the size of the track buffer 2044 maxNotificationFrames = mFrameCount; 2045 } else { 2046 // For normal tracks, use at least double-buffering if no sample rate conversion, 2047 // or at least triple-buffering if there is sample rate conversion 2048 const int nBuffering = sampleRate == mSampleRate ? 2 : 3; 2049 maxNotificationFrames = frameCount / nBuffering; 2050 // If client requested a fast track but this was denied, then use the smaller maximum. 2051 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) { 2052 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000; 2053 if (maxNotificationFrames > maxNotificationFramesFastDenied) { 2054 maxNotificationFrames = maxNotificationFramesFastDenied; 2055 } 2056 } 2057 } 2058 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) { 2059 if (notificationFrameCount == 0) { 2060 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu", 2061 maxNotificationFrames, frameCount); 2062 } else { 2063 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu", 2064 notificationFrameCount, maxNotificationFrames, frameCount); 2065 } 2066 notificationFrameCount = maxNotificationFrames; 2067 } 2068 } 2069 2070 *pFrameCount = frameCount; 2071 *pNotificationFrameCount = notificationFrameCount; 2072 2073 switch (mType) { 2074 2075 case DIRECT: 2076 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()? 2077 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) { 2078 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x " 2079 "for output %p with format %#x", 2080 sampleRate, format, channelMask, mOutput, mFormat); 2081 lStatus = BAD_VALUE; 2082 goto Exit; 2083 } 2084 } 2085 break; 2086 2087 case OFFLOAD: 2088 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) { 2089 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \"" 2090 "for output %p with format %#x", 2091 sampleRate, format, channelMask, mOutput, mFormat); 2092 lStatus = BAD_VALUE; 2093 goto Exit; 2094 } 2095 break; 2096 2097 default: 2098 if (!audio_is_linear_pcm(format)) { 2099 ALOGE("createTrack_l() Bad parameter: format %#x \"" 2100 "for output %p with format %#x", 2101 format, mOutput, mFormat); 2102 lStatus = BAD_VALUE; 2103 goto Exit; 2104 } 2105 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) { 2106 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate); 2107 lStatus = BAD_VALUE; 2108 goto Exit; 2109 } 2110 break; 2111 2112 } 2113 2114 lStatus = initCheck(); 2115 if (lStatus != NO_ERROR) { 2116 ALOGE("createTrack_l() audio driver not initialized"); 2117 goto Exit; 2118 } 2119 2120 { // scope for mLock 2121 Mutex::Autolock _l(mLock); 2122 2123 // all tracks in same audio session must share the same routing strategy otherwise 2124 // conflicts will happen when tracks are moved from one output to another by audio policy 2125 // manager 2126 uint32_t strategy = AudioSystem::getStrategyForStream(streamType); 2127 for (size_t i = 0; i < mTracks.size(); ++i) { 2128 sp<Track> t = mTracks[i]; 2129 if (t != 0 && t->isExternalTrack()) { 2130 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType()); 2131 if (sessionId == t->sessionId() && strategy != actual) { 2132 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u", 2133 strategy, actual); 2134 lStatus = BAD_VALUE; 2135 goto Exit; 2136 } 2137 } 2138 } 2139 2140 track = new Track(this, client, streamType, attr, sampleRate, format, 2141 channelMask, frameCount, 2142 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer, 2143 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId); 2144 2145 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY; 2146 if (lStatus != NO_ERROR) { 2147 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus); 2148 // track must be cleared from the caller as the caller has the AF lock 2149 goto Exit; 2150 } 2151 mTracks.add(track); 2152 2153 sp<EffectChain> chain = getEffectChain_l(sessionId); 2154 if (chain != 0) { 2155 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer()); 2156 track->setMainBuffer(chain->inBuffer()); 2157 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType())); 2158 chain->incTrackCnt(); 2159 } 2160 2161 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) { 2162 pid_t callingPid = IPCThreadState::self()->getCallingPid(); 2163 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful, 2164 // so ask activity manager to do this on our behalf 2165 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/); 2166 } 2167 } 2168 2169 lStatus = NO_ERROR; 2170 2171 Exit: 2172 *status = lStatus; 2173 return track; 2174 } 2175 2176 template<typename T> 2177 ssize_t AudioFlinger::PlaybackThread::Tracks<T>::add(const sp<T> &track) 2178 { 2179 const ssize_t index = mTracks.add(track); 2180 if (index >= 0) { 2181 // set name for track when adding. 2182 int name; 2183 if (mUnusedTrackNames.empty()) { 2184 name = mTracks.size() - 1; // new name {0 ... size-1}. 2185 } else { 2186 // reuse smallest name for deleted track. 2187 auto it = mUnusedTrackNames.begin(); 2188 name = *it; 2189 (void)mUnusedTrackNames.erase(it); 2190 } 2191 track->setName(name); 2192 } else { 2193 LOG_ALWAYS_FATAL("cannot add track"); 2194 } 2195 return index; 2196 } 2197 2198 template<typename T> 2199 ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track) 2200 { 2201 const int name = track->name(); 2202 const ssize_t index = mTracks.remove(track); 2203 if (index >= 0) { 2204 // invalidate name when removing from mTracks. 2205 LOG_ALWAYS_FATAL_IF(name < 0, "invalid name %d for track on mTracks", name); 2206 2207 if (mSaveDeletedTrackNames) { 2208 // We can't directly access mAudioMixer since the caller may be outside of threadLoop. 2209 // Instead, we add to mDeletedTrackNames which is solely used for mAudioMixer update, 2210 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer. 2211 mDeletedTrackNames.emplace(name); 2212 } 2213 2214 mUnusedTrackNames.emplace(name); 2215 track->setName(T::TRACK_NAME_PENDING); 2216 } else { 2217 LOG_ALWAYS_FATAL_IF(name >= 0, 2218 "valid name %d for track not in mTracks (returned %zd)", name, index); 2219 } 2220 return index; 2221 } 2222 2223 uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const 2224 { 2225 return latency; 2226 } 2227 2228 uint32_t AudioFlinger::PlaybackThread::latency() const 2229 { 2230 Mutex::Autolock _l(mLock); 2231 return latency_l(); 2232 } 2233 uint32_t AudioFlinger::PlaybackThread::latency_l() const 2234 { 2235 uint32_t latency; 2236 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) { 2237 return correctLatency_l(latency); 2238 } 2239 return 0; 2240 } 2241 2242 void AudioFlinger::PlaybackThread::setMasterVolume(float value) 2243 { 2244 Mutex::Autolock _l(mLock); 2245 // Don't apply master volume in SW if our HAL can do it for us. 2246 if (mOutput && mOutput->audioHwDev && 2247 mOutput->audioHwDev->canSetMasterVolume()) { 2248 mMasterVolume = 1.0; 2249 } else { 2250 mMasterVolume = value; 2251 } 2252 } 2253 2254 void AudioFlinger::PlaybackThread::setMasterMute(bool muted) 2255 { 2256 if (isDuplicating()) { 2257 return; 2258 } 2259 Mutex::Autolock _l(mLock); 2260 // Don't apply master mute in SW if our HAL can do it for us. 2261 if (mOutput && mOutput->audioHwDev && 2262 mOutput->audioHwDev->canSetMasterMute()) { 2263 mMasterMute = false; 2264 } else { 2265 mMasterMute = muted; 2266 } 2267 } 2268 2269 void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value) 2270 { 2271 Mutex::Autolock _l(mLock); 2272 mStreamTypes[stream].volume = value; 2273 broadcast_l(); 2274 } 2275 2276 void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted) 2277 { 2278 Mutex::Autolock _l(mLock); 2279 mStreamTypes[stream].mute = muted; 2280 broadcast_l(); 2281 } 2282 2283 float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const 2284 { 2285 Mutex::Autolock _l(mLock); 2286 return mStreamTypes[stream].volume; 2287 } 2288 2289 // addTrack_l() must be called with ThreadBase::mLock held 2290 status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track) 2291 { 2292 status_t status = ALREADY_EXISTS; 2293 2294 if (mActiveTracks.indexOf(track) < 0) { 2295 // the track is newly added, make sure it fills up all its 2296 // buffers before playing. This is to ensure the client will 2297 // effectively get the latency it requested. 2298 if (track->isExternalTrack()) { 2299 TrackBase::track_state state = track->mState; 2300 mLock.unlock(); 2301 status = AudioSystem::startOutput(mId, track->streamType(), 2302 track->sessionId()); 2303 mLock.lock(); 2304 // abort track was stopped/paused while we released the lock 2305 if (state != track->mState) { 2306 if (status == NO_ERROR) { 2307 mLock.unlock(); 2308 AudioSystem::stopOutput(mId, track->streamType(), 2309 track->sessionId()); 2310 mLock.lock(); 2311 } 2312 return INVALID_OPERATION; 2313 } 2314 // abort if start is rejected by audio policy manager 2315 if (status != NO_ERROR) { 2316 return PERMISSION_DENIED; 2317 } 2318 #ifdef ADD_BATTERY_DATA 2319 // to track the speaker usage 2320 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart); 2321 #endif 2322 } 2323 2324 // set retry count for buffer fill 2325 if (track->isOffloaded()) { 2326 if (track->isStopping_1()) { 2327 track->mRetryCount = kMaxTrackStopRetriesOffload; 2328 } else { 2329 track->mRetryCount = kMaxTrackStartupRetriesOffload; 2330 } 2331 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED; 2332 } else { 2333 track->mRetryCount = kMaxTrackStartupRetries; 2334 track->mFillingUpStatus = 2335 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING; 2336 } 2337 2338 track->mResetDone = false; 2339 track->mPresentationCompleteFrames = 0; 2340 mActiveTracks.add(track); 2341 sp<EffectChain> chain = getEffectChain_l(track->sessionId()); 2342 if (chain != 0) { 2343 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), 2344 track->sessionId()); 2345 chain->incActiveTrackCnt(); 2346 } 2347 2348 status = NO_ERROR; 2349 } 2350 2351 onAddNewTrack_l(); 2352 return status; 2353 } 2354 2355 bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track) 2356 { 2357 track->terminate(); 2358 // active tracks are removed by threadLoop() 2359 bool trackActive = (mActiveTracks.indexOf(track) >= 0); 2360 track->mState = TrackBase::STOPPED; 2361 if (!trackActive) { 2362 removeTrack_l(track); 2363 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) { 2364 track->mState = TrackBase::STOPPING_1; 2365 } 2366 2367 return trackActive; 2368 } 2369 2370 void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track) 2371 { 2372 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE); 2373 2374 String8 result; 2375 track->appendDump(result, false /* active */); 2376 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string()); 2377 2378 mTracks.remove(track); 2379 if (track->isFastTrack()) { 2380 int index = track->mFastIndex; 2381 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks); 2382 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index))); 2383 mFastTrackAvailMask |= 1 << index; 2384 // redundant as track is about to be destroyed, for dumpsys only 2385 track->mFastIndex = -1; 2386 } 2387 sp<EffectChain> chain = getEffectChain_l(track->sessionId()); 2388 if (chain != 0) { 2389 chain->decTrackCnt(); 2390 } 2391 } 2392 2393 String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys) 2394 { 2395 Mutex::Autolock _l(mLock); 2396 String8 out_s8; 2397 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) { 2398 return out_s8; 2399 } 2400 return String8(); 2401 } 2402 2403 void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) { 2404 sp<AudioIoDescriptor> desc = new AudioIoDescriptor(); 2405 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event); 2406 2407 desc->mIoHandle = mId; 2408 2409 switch (event) { 2410 case AUDIO_OUTPUT_OPENED: 2411 case AUDIO_OUTPUT_REGISTERED: 2412 case AUDIO_OUTPUT_CONFIG_CHANGED: 2413 desc->mPatch = mPatch; 2414 desc->mChannelMask = mChannelMask; 2415 desc->mSamplingRate = mSampleRate; 2416 desc->mFormat = mFormat; 2417 desc->mFrameCount = mNormalFrameCount; // FIXME see 2418 // AudioFlinger::frameCount(audio_io_handle_t) 2419 desc->mFrameCountHAL = mFrameCount; 2420 desc->mLatency = latency_l(); 2421 break; 2422 2423 case AUDIO_OUTPUT_CLOSED: 2424 default: 2425 break; 2426 } 2427 mAudioFlinger->ioConfigChanged(event, desc, pid); 2428 } 2429 2430 void AudioFlinger::PlaybackThread::onWriteReady() 2431 { 2432 mCallbackThread->resetWriteBlocked(); 2433 } 2434 2435 void AudioFlinger::PlaybackThread::onDrainReady() 2436 { 2437 mCallbackThread->resetDraining(); 2438 } 2439 2440 void AudioFlinger::PlaybackThread::onError() 2441 { 2442 mCallbackThread->setAsyncError(); 2443 } 2444 2445 void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence) 2446 { 2447 Mutex::Autolock _l(mLock); 2448 // reject out of sequence requests 2449 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) { 2450 mWriteAckSequence &= ~1; 2451 mWaitWorkCV.signal(); 2452 } 2453 } 2454 2455 void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence) 2456 { 2457 Mutex::Autolock _l(mLock); 2458 // reject out of sequence requests 2459 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) { 2460 mDrainSequence &= ~1; 2461 mWaitWorkCV.signal(); 2462 } 2463 } 2464 2465 void AudioFlinger::PlaybackThread::readOutputParameters_l() 2466 { 2467 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL 2468 mSampleRate = mOutput->getSampleRate(); 2469 mChannelMask = mOutput->getChannelMask(); 2470 if (!audio_is_output_channel(mChannelMask)) { 2471 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask); 2472 } 2473 if ((mType == MIXER || mType == DUPLICATING) 2474 && !isValidPcmSinkChannelMask(mChannelMask)) { 2475 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output", 2476 mChannelMask); 2477 } 2478 mChannelCount = audio_channel_count_from_out_mask(mChannelMask); 2479 2480 // Get actual HAL format. 2481 status_t result = mOutput->stream->getFormat(&mHALFormat); 2482 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result); 2483 // Get format from the shim, which will be different than the HAL format 2484 // if playing compressed audio over HDMI passthrough. 2485 mFormat = mOutput->getFormat(); 2486 if (!audio_is_valid_format(mFormat)) { 2487 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat); 2488 } 2489 if ((mType == MIXER || mType == DUPLICATING) 2490 && !isValidPcmSinkFormat(mFormat)) { 2491 LOG_FATAL("HAL format %#x not supported for mixed output", 2492 mFormat); 2493 } 2494 mFrameSize = mOutput->getFrameSize(); 2495 result = mOutput->stream->getBufferSize(&mBufferSize); 2496 LOG_ALWAYS_FATAL_IF(result != OK, 2497 "Error when retrieving output stream buffer size: %d", result); 2498 mFrameCount = mBufferSize / mFrameSize; 2499 if (mFrameCount & 15) { 2500 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames", 2501 mFrameCount); 2502 } 2503 2504 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) { 2505 if (mOutput->stream->setCallback(this) == OK) { 2506 mUseAsyncWrite = true; 2507 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this); 2508 } 2509 } 2510 2511 mHwSupportsPause = false; 2512 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) { 2513 bool supportsPause = false, supportsResume = false; 2514 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) { 2515 if (supportsPause && supportsResume) { 2516 mHwSupportsPause = true; 2517 } else if (supportsPause) { 2518 ALOGW("direct output implements pause but not resume"); 2519 } else if (supportsResume) { 2520 ALOGW("direct output implements resume but not pause"); 2521 } 2522 } 2523 } 2524 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) { 2525 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume"); 2526 } 2527 2528 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) { 2529 // For best precision, we use float instead of the associated output 2530 // device format (typically PCM 16 bit). 2531 2532 mFormat = AUDIO_FORMAT_PCM_FLOAT; 2533 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat); 2534 mBufferSize = mFrameSize * mFrameCount; 2535 2536 // TODO: We currently use the associated output device channel mask and sample rate. 2537 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads 2538 // (if a valid mask) to avoid premature downmix. 2539 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads 2540 // instead of the output device sample rate to avoid loss of high frequency information. 2541 // This may need to be updated as MixerThread/OutputTracks are added and not here. 2542 } 2543 2544 // Calculate size of normal sink buffer relative to the HAL output buffer size 2545 double multiplier = 1.0; 2546 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || 2547 kUseFastMixer == FastMixer_Dynamic)) { 2548 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000; 2549 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000; 2550 2551 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer 2552 minNormalFrameCount = (minNormalFrameCount + 15) & ~15; 2553 maxNormalFrameCount = maxNormalFrameCount & ~15; 2554 if (maxNormalFrameCount < minNormalFrameCount) { 2555 maxNormalFrameCount = minNormalFrameCount; 2556 } 2557 multiplier = (double) minNormalFrameCount / (double) mFrameCount; 2558 if (multiplier <= 1.0) { 2559 multiplier = 1.0; 2560 } else if (multiplier <= 2.0) { 2561 if (2 * mFrameCount <= maxNormalFrameCount) { 2562 multiplier = 2.0; 2563 } else { 2564 multiplier = (double) maxNormalFrameCount / (double) mFrameCount; 2565 } 2566 } else { 2567 multiplier = floor(multiplier); 2568 } 2569 } 2570 mNormalFrameCount = multiplier * mFrameCount; 2571 // round up to nearest 16 frames to satisfy AudioMixer 2572 if (mType == MIXER || mType == DUPLICATING) { 2573 mNormalFrameCount = (mNormalFrameCount + 15) & ~15; 2574 } 2575 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount, 2576 mNormalFrameCount); 2577 2578 // Check if we want to throttle the processing to no more than 2x normal rate 2579 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */); 2580 mThreadThrottleTimeMs = 0; 2581 mThreadThrottleEndMs = 0; 2582 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate); 2583 2584 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames. 2585 // Originally this was int16_t[] array, need to remove legacy implications. 2586 free(mSinkBuffer); 2587 mSinkBuffer = NULL; 2588 // For sink buffer size, we use the frame size from the downstream sink to avoid problems 2589 // with non PCM formats for compressed music, e.g. AAC, and Offload threads. 2590 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize; 2591 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize); 2592 2593 // We resize the mMixerBuffer according to the requirements of the sink buffer which 2594 // drives the output. 2595 free(mMixerBuffer); 2596 mMixerBuffer = NULL; 2597 if (mMixerBufferEnabled) { 2598 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT. 2599 mMixerBufferSize = mNormalFrameCount * mChannelCount 2600 * audio_bytes_per_sample(mMixerBufferFormat); 2601 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize); 2602 } 2603 free(mEffectBuffer); 2604 mEffectBuffer = NULL; 2605 if (mEffectBufferEnabled) { 2606 mEffectBufferFormat = EFFECT_BUFFER_FORMAT; 2607 mEffectBufferSize = mNormalFrameCount * mChannelCount 2608 * audio_bytes_per_sample(mEffectBufferFormat); 2609 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize); 2610 } 2611 2612 // force reconfiguration of effect chains and engines to take new buffer size and audio 2613 // parameters into account 2614 // Note that mLock is not held when readOutputParameters_l() is called from the constructor 2615 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't 2616 // matter. 2617 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains 2618 Vector< sp<EffectChain> > effectChains = mEffectChains; 2619 for (size_t i = 0; i < effectChains.size(); i ++) { 2620 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false); 2621 } 2622 } 2623 2624 void AudioFlinger::PlaybackThread::updateMetadata_l() 2625 { 2626 if (mOutput == nullptr || mOutput->stream == nullptr ) { 2627 return; // That should not happen 2628 } 2629 bool hasChanged = mActiveTracks.readAndClearHasChanged(); 2630 for (const sp<Track> &track : mActiveTracks) { 2631 // Do not short-circuit as all hasChanged states must be reset 2632 // as all the metadata are going to be sent 2633 hasChanged |= track->readAndClearHasChanged(); 2634 } 2635 if (!hasChanged) { 2636 return; // nothing to do 2637 } 2638 StreamOutHalInterface::SourceMetadata metadata; 2639 auto backInserter = std::back_inserter(metadata.tracks); 2640 for (const sp<Track> &track : mActiveTracks) { 2641 // No track is invalid as this is called after prepareTrack_l in the same critical section 2642 track->copyMetadataTo(backInserter); 2643 } 2644 sendMetadataToBackend_l(metadata); 2645 } 2646 2647 void AudioFlinger::PlaybackThread::sendMetadataToBackend_l( 2648 const StreamOutHalInterface::SourceMetadata& metadata) 2649 { 2650 mOutput->stream->updateSourceMetadata(metadata); 2651 }; 2652 2653 status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames) 2654 { 2655 if (halFrames == NULL || dspFrames == NULL) { 2656 return BAD_VALUE; 2657 } 2658 Mutex::Autolock _l(mLock); 2659 if (initCheck() != NO_ERROR) { 2660 return INVALID_OPERATION; 2661 } 2662 int64_t framesWritten = mBytesWritten / mFrameSize; 2663 *halFrames = framesWritten; 2664 2665 if (isSuspended()) { 2666 // return an estimation of rendered frames when the output is suspended 2667 size_t latencyFrames = (latency_l() * mSampleRate) / 1000; 2668 *dspFrames = (uint32_t) 2669 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0); 2670 return NO_ERROR; 2671 } else { 2672 status_t status; 2673 uint32_t frames; 2674 status = mOutput->getRenderPosition(&frames); 2675 *dspFrames = (size_t)frames; 2676 return status; 2677 } 2678 } 2679 2680 // hasAudioSession_l() must be called with ThreadBase::mLock held 2681 uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const 2682 { 2683 uint32_t result = 0; 2684 if (getEffectChain_l(sessionId) != 0) { 2685 result = EFFECT_SESSION; 2686 } 2687 2688 for (size_t i = 0; i < mTracks.size(); ++i) { 2689 sp<Track> track = mTracks[i]; 2690 if (sessionId == track->sessionId() && !track->isInvalid()) { 2691 result |= TRACK_SESSION; 2692 if (track->isFastTrack()) { 2693 result |= FAST_SESSION; 2694 } 2695 break; 2696 } 2697 } 2698 2699 return result; 2700 } 2701 2702 uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) 2703 { 2704 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that 2705 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected 2706 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) { 2707 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); 2708 } 2709 for (size_t i = 0; i < mTracks.size(); i++) { 2710 sp<Track> track = mTracks[i]; 2711 if (sessionId == track->sessionId() && !track->isInvalid()) { 2712 return AudioSystem::getStrategyForStream(track->streamType()); 2713 } 2714 } 2715 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC); 2716 } 2717 2718 2719 AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const 2720 { 2721 Mutex::Autolock _l(mLock); 2722 return mOutput; 2723 } 2724 2725 AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput() 2726 { 2727 Mutex::Autolock _l(mLock); 2728 AudioStreamOut *output = mOutput; 2729 mOutput = NULL; 2730 // FIXME FastMixer might also have a raw ptr to mOutputSink; 2731 // must push a NULL and wait for ack 2732 mOutputSink.clear(); 2733 mPipeSink.clear(); 2734 mNormalSink.clear(); 2735 return output; 2736 } 2737 2738 // this method must always be called either with ThreadBase mLock held or inside the thread loop 2739 sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const 2740 { 2741 if (mOutput == NULL) { 2742 return NULL; 2743 } 2744 return mOutput->stream; 2745 } 2746 2747 uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const 2748 { 2749 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000); 2750 } 2751 2752 status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event) 2753 { 2754 if (!isValidSyncEvent(event)) { 2755 return BAD_VALUE; 2756 } 2757 2758 Mutex::Autolock _l(mLock); 2759 2760 for (size_t i = 0; i < mTracks.size(); ++i) { 2761 sp<Track> track = mTracks[i]; 2762 if (event->triggerSession() == track->sessionId()) { 2763 (void) track->setSyncEvent(event); 2764 return NO_ERROR; 2765 } 2766 } 2767 2768 return NAME_NOT_FOUND; 2769 } 2770 2771 bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const 2772 { 2773 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE; 2774 } 2775 2776 void AudioFlinger::PlaybackThread::threadLoop_removeTracks( 2777 const Vector< sp<Track> >& tracksToRemove) 2778 { 2779 size_t count = tracksToRemove.size(); 2780 if (count > 0) { 2781 for (size_t i = 0 ; i < count ; i++) { 2782 const sp<Track>& track = tracksToRemove.itemAt(i); 2783 if (track->isExternalTrack()) { 2784 AudioSystem::stopOutput(mId, track->streamType(), 2785 track->sessionId()); 2786 #ifdef ADD_BATTERY_DATA 2787 // to track the speaker usage 2788 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop); 2789 #endif 2790 if (track->isTerminated()) { 2791 AudioSystem::releaseOutput(mId, track->streamType(), 2792 track->sessionId()); 2793 } 2794 } 2795 } 2796 } 2797 } 2798 2799 void AudioFlinger::PlaybackThread::checkSilentMode_l() 2800 { 2801 if (!mMasterMute) { 2802 char value[PROPERTY_VALUE_MAX]; 2803 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) { 2804 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX"); 2805 return; 2806 } 2807 if (property_get("ro.audio.silent", value, "0") > 0) { 2808 char *endptr; 2809 unsigned long ul = strtoul(value, &endptr, 0); 2810 if (*endptr == '\0' && ul != 0) { 2811 ALOGD("Silence is golden"); 2812 // The setprop command will not allow a property to be changed after 2813 // the first time it is set, so we don't have to worry about un-muting. 2814 setMasterMute_l(true); 2815 } 2816 } 2817 } 2818 } 2819 2820 // shared by MIXER and DIRECT, overridden by DUPLICATING 2821 ssize_t AudioFlinger::PlaybackThread::threadLoop_write() 2822 { 2823 LOG_HIST_TS(); 2824 mInWrite = true; 2825 ssize_t bytesWritten; 2826 const size_t offset = mCurrentWriteLength - mBytesRemaining; 2827 2828 // If an NBAIO sink is present, use it to write the normal mixer's submix 2829 if (mNormalSink != 0) { 2830 2831 const size_t count = mBytesRemaining / mFrameSize; 2832 2833 ATRACE_BEGIN("write"); 2834 // update the setpoint when AudioFlinger::mScreenState changes 2835 uint32_t screenState = AudioFlinger::mScreenState; 2836 if (screenState != mScreenState) { 2837 mScreenState = screenState; 2838 MonoPipe *pipe = (MonoPipe *)mPipeSink.get(); 2839 if (pipe != NULL) { 2840 pipe->setAvgFrames((mScreenState & 1) ? 2841 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2); 2842 } 2843 } 2844 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count); 2845 ATRACE_END(); 2846 if (framesWritten > 0) { 2847 bytesWritten = framesWritten * mFrameSize; 2848 } else { 2849 bytesWritten = framesWritten; 2850 } 2851 // otherwise use the HAL / AudioStreamOut directly 2852 } else { 2853 // Direct output and offload threads 2854 2855 if (mUseAsyncWrite) { 2856 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request"); 2857 mWriteAckSequence += 2; 2858 mWriteAckSequence |= 1; 2859 ALOG_ASSERT(mCallbackThread != 0); 2860 mCallbackThread->setWriteBlocked(mWriteAckSequence); 2861 } 2862 // FIXME We should have an implementation of timestamps for direct output threads. 2863 // They are used e.g for multichannel PCM playback over HDMI. 2864 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining); 2865 2866 if (mUseAsyncWrite && 2867 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) { 2868 // do not wait for async callback in case of error of full write 2869 mWriteAckSequence &= ~1; 2870 ALOG_ASSERT(mCallbackThread != 0); 2871 mCallbackThread->setWriteBlocked(mWriteAckSequence); 2872 } 2873 } 2874 2875 mNumWrites++; 2876 mInWrite = false; 2877 mStandby = false; 2878 return bytesWritten; 2879 } 2880 2881 void AudioFlinger::PlaybackThread::threadLoop_drain() 2882 { 2883 bool