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 #pragma once 19 20 // ADD_BATTERY_DATA AUDIO_WATCHDOG FAST_THREAD_STATISTICS STATE_QUEUE_DUMP TEE_SINK 21 #include "Configuration.h" 22 #include "IAfThread.h" 23 #include "IAfTrack.h" 24 25 #include <android-base/macros.h> // DISALLOW_COPY_AND_ASSIGN 26 #include <android/os/IPowerManager.h> 27 #include <afutils/AudioWatchdog.h> 28 #include <afutils/NBAIO_Tee.h> 29 #include <audio_utils/Balance.h> 30 #include <audio_utils/SimpleLog.h> 31 #include <datapath/ThreadMetrics.h> 32 #include <fastpath/FastCapture.h> 33 #include <fastpath/FastMixer.h> 34 #include <mediautils/Synchronization.h> 35 #include <mediautils/ThreadSnapshot.h> 36 #include <timing/MonotonicFrameCounter.h> 37 #include <utils/Log.h> 38 39 namespace android { 40 41 class AsyncCallbackThread; 42 43 class ThreadBase : public virtual IAfThreadBase, public Thread { 44 public: 45 static const char *threadTypeToString(type_t type); 46 47 // ThreadBase_ThreadLoop is a virtual mutex (always nullptr) that 48 // guards methods and variables that ONLY run and are accessed 49 // on the single threaded threadLoop(). 50 // 51 // As access is by a single thread, the variables are thread safe. 52 static audio_utils::mutex* ThreadBase_ThreadLoop; 53 afThreadCallback()54 IAfThreadCallback* afThreadCallback() const final { return mAfThreadCallback.get(); } 55 56 ThreadBase(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id, 57 type_t type, bool systemReady, bool isOut); 58 ~ThreadBase() override; 59 60 status_t readyToRun() final; 61 void clearPowerManager() final EXCLUDES_ThreadBase_Mutex; 62 63 // base for record and playback 64 enum { 65 CFG_EVENT_IO, 66 CFG_EVENT_PRIO, 67 CFG_EVENT_SET_PARAMETER, 68 CFG_EVENT_CREATE_AUDIO_PATCH, 69 CFG_EVENT_RELEASE_AUDIO_PATCH, 70 CFG_EVENT_UPDATE_OUT_DEVICE, 71 CFG_EVENT_RESIZE_BUFFER, 72 CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS, 73 CFG_EVENT_HAL_LATENCY_MODES_CHANGED, 74 }; 75 76 class ConfigEventData: public RefBase { 77 public: 78 virtual void dump(char *buffer, size_t size) = 0; 79 protected: 80 ConfigEventData() = default; 81 }; 82 83 // Config event sequence by client if status needed (e.g binder thread calling setParameters()): 84 // 1. create SetParameterConfigEvent. This sets mWaitStatus in config event 85 // 2. Lock mutex() 86 // 3. Call sendConfigEvent_l(): Append to mConfigEvents and mWaitWorkCV.signal 87 // 4. sendConfigEvent_l() reads status from event->mStatus; 88 // 5. sendConfigEvent_l() returns status 89 // 6. Unlock 90 // 91 // Parameter sequence by server: threadLoop calling processConfigEvents_l(): 92 // 1. Lock mutex() 93 // 2. If there is an entry in mConfigEvents proceed ... 94 // 3. Read first entry in mConfigEvents 95 // 4. Remove first entry from mConfigEvents 96 // 5. Process 97 // 6. Set event->mStatus 98 // 7. event->mCondition.notify_one() 99 // 8. Unlock 100 101 class ConfigEvent: public RefBase { 102 public: dump(char * buffer,size_t size)103 void dump(char *buffer, size_t size) { 104 snprintf(buffer, size, "Event type: %d\n", mType); 105 if (mData != nullptr) { 106 snprintf(buffer, size, "Data:\n"); 107 mData->dump(buffer, size); 108 } 109 } 110 mutex()111 audio_utils::mutex& mutex() const RETURN_CAPABILITY(audio_utils::ConfigEvent_Mutex) { 112 return mMutex; 113 } 114 const int mType; // event type e.g. CFG_EVENT_IO 115 // mutex associated with mCondition 116 mutable audio_utils::mutex mMutex{audio_utils::MutexOrder::kConfigEvent_Mutex}; 117 audio_utils::condition_variable mCondition; // condition for status return 118 119 // NO_THREAD_SAFETY_ANALYSIS Can we add GUARDED_BY? 120 status_t mStatus; // status communicated to sender 121 122 bool mWaitStatus GUARDED_BY(mutex()); // true if sender is waiting for status 123 // true if must wait for system ready to enter event queue 124 bool mRequiresSystemReady GUARDED_BY(mutex()); 125 126 // NO_THREAD_SAFETY_ANALYSIS Can we add GUARDED_BY? 127 sp<ConfigEventData> mData; // event specific parameter data 128 129 protected: 130 explicit ConfigEvent(int type, bool requiresSystemReady = false) : mType(type)131 mType(type), mStatus(NO_ERROR), mWaitStatus(false), 132 mRequiresSystemReady(requiresSystemReady), mData(NULL) {} 133 }; 134 135 class IoConfigEventData : public ConfigEventData { 136 public: IoConfigEventData(audio_io_config_event_t event,pid_t pid,audio_port_handle_t portId)137 IoConfigEventData(audio_io_config_event_t event, pid_t pid, 138 audio_port_handle_t portId) : 139 mEvent(event), mPid(pid), mPortId(portId) {} 140 dump(char * buffer,size_t size)141 virtual void dump(char *buffer, size_t size) { 142 snprintf(buffer, size, "- IO event: event %d\n", mEvent); 143 } 144 145 const audio_io_config_event_t mEvent; 146 const pid_t mPid; 147 const audio_port_handle_t mPortId; 148 }; 149 150 class IoConfigEvent : public ConfigEvent { 151 public: IoConfigEvent(audio_io_config_event_t event,pid_t pid,audio_port_handle_t portId)152 IoConfigEvent(audio_io_config_event_t event, pid_t pid, audio_port_handle_t portId) : 153 ConfigEvent(CFG_EVENT_IO) { 154 mData = new IoConfigEventData(event, pid, portId); 155 } 156 }; 157 158 class PrioConfigEventData : public ConfigEventData { 159 public: PrioConfigEventData(pid_t pid,pid_t tid,int32_t prio,bool forApp)160 PrioConfigEventData(pid_t pid, pid_t tid, int32_t prio, bool forApp) : 161 mPid(pid), mTid(tid), mPrio(prio), mForApp(forApp) {} 162 dump(char * buffer,size_t size)163 virtual void dump(char *buffer, size_t size) { 164 snprintf(buffer, size, "- Prio event: pid %d, tid %d, prio %d, for app? %d\n", 165 mPid, mTid, mPrio, mForApp); 166 } 167 168 const pid_t mPid; 169 const pid_t mTid; 170 const int32_t mPrio; 171 const bool mForApp; 172 }; 173 174 class PrioConfigEvent : public ConfigEvent { 175 public: PrioConfigEvent(pid_t pid,pid_t tid,int32_t prio,bool forApp)176 PrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp) : 177 ConfigEvent(CFG_EVENT_PRIO, true) { 178 mData = new PrioConfigEventData(pid, tid, prio, forApp); 179 } 180 }; 181 182 class SetParameterConfigEventData : public ConfigEventData { 183 public: SetParameterConfigEventData(const String8 & keyValuePairs)184 explicit SetParameterConfigEventData(const String8& keyValuePairs) : 185 mKeyValuePairs(keyValuePairs) {} 186 dump(char * buffer,size_t size)187 virtual void dump(char *buffer, size_t size) { 188 snprintf(buffer, size, "- KeyValue: %s\n", mKeyValuePairs.c_str()); 189 } 190 191 const String8 mKeyValuePairs; 192 }; 193 194 class SetParameterConfigEvent : public ConfigEvent { 195 public: SetParameterConfigEvent(const String8 & keyValuePairs)196 explicit SetParameterConfigEvent(const String8& keyValuePairs) : 197 ConfigEvent(CFG_EVENT_SET_PARAMETER) { 198 mData = new SetParameterConfigEventData(keyValuePairs); 199 mWaitStatus = true; 200 } 201 }; 202 203 class CreateAudioPatchConfigEventData : public ConfigEventData { 204 public: CreateAudioPatchConfigEventData(const struct audio_patch patch,audio_patch_handle_t handle)205 CreateAudioPatchConfigEventData(const struct audio_patch patch, 206 audio_patch_handle_t handle) : 207 mPatch(patch), mHandle(handle) {} 208 dump(char * buffer,size_t size)209 virtual void dump(char *buffer, size_t size) { 210 snprintf(buffer, size, "- Patch handle: %u\n", mHandle); 211 } 212 213 const struct audio_patch mPatch; 214 audio_patch_handle_t mHandle; // cannot be const 215 }; 216 217 class CreateAudioPatchConfigEvent : public ConfigEvent { 218 public: CreateAudioPatchConfigEvent(const struct audio_patch patch,audio_patch_handle_t handle)219 CreateAudioPatchConfigEvent(const struct audio_patch patch, 220 audio_patch_handle_t handle) : 221 ConfigEvent(CFG_EVENT_CREATE_AUDIO_PATCH) { 222 mData = new CreateAudioPatchConfigEventData(patch, handle); 223 mWaitStatus = true; 224 } 225 }; 226 227 class ReleaseAudioPatchConfigEventData : public ConfigEventData { 228 public: ReleaseAudioPatchConfigEventData(const audio_patch_handle_t handle)229 explicit ReleaseAudioPatchConfigEventData(const audio_patch_handle_t handle) : 230 mHandle(handle) {} 231 dump(char * buffer,size_t size)232 virtual void dump(char *buffer, size_t size) { 233 snprintf(buffer, size, "- Patch handle: %u\n", mHandle); 234 } 235 236 const audio_patch_handle_t mHandle; 237 }; 238 239 class ReleaseAudioPatchConfigEvent : public ConfigEvent { 240 public: ReleaseAudioPatchConfigEvent(const audio_patch_handle_t handle)241 explicit ReleaseAudioPatchConfigEvent(const audio_patch_handle_t handle) : 242 ConfigEvent(CFG_EVENT_RELEASE_AUDIO_PATCH) { 243 mData = new ReleaseAudioPatchConfigEventData(handle); 244 mWaitStatus = true; 245 } 246 }; 247 248 class UpdateOutDevicesConfigEventData : public ConfigEventData { 249 public: UpdateOutDevicesConfigEventData(const DeviceDescriptorBaseVector & outDevices)250 explicit UpdateOutDevicesConfigEventData(const DeviceDescriptorBaseVector& outDevices) : 251 mOutDevices(outDevices) {} 252 dump(char * buffer,size_t size)253 virtual void dump(char *buffer, size_t size) { 254 snprintf(buffer, size, "- Devices: %s", android::toString(mOutDevices).c_str()); 255 } 256 257 const DeviceDescriptorBaseVector mOutDevices; 258 }; 259 260 class UpdateOutDevicesConfigEvent : public ConfigEvent { 261 public: UpdateOutDevicesConfigEvent(const DeviceDescriptorBaseVector & outDevices)262 explicit UpdateOutDevicesConfigEvent(const DeviceDescriptorBaseVector& outDevices) : 263 ConfigEvent(CFG_EVENT_UPDATE_OUT_DEVICE) { 264 mData = new UpdateOutDevicesConfigEventData(outDevices); 265 } 266 }; 267 268 class ResizeBufferConfigEventData : public ConfigEventData { 269 public: ResizeBufferConfigEventData(int32_t maxSharedAudioHistoryMs)270 explicit ResizeBufferConfigEventData(int32_t maxSharedAudioHistoryMs) : 271 mMaxSharedAudioHistoryMs(maxSharedAudioHistoryMs) {} 272 dump(char * buffer,size_t size)273 virtual void dump(char *buffer, size_t size) { 274 snprintf(buffer, size, "- mMaxSharedAudioHistoryMs: %d", mMaxSharedAudioHistoryMs); 275 } 276 277 const int32_t mMaxSharedAudioHistoryMs; 278 }; 279 280 class ResizeBufferConfigEvent : public ConfigEvent { 281 public: ResizeBufferConfigEvent(int32_t maxSharedAudioHistoryMs)282 explicit ResizeBufferConfigEvent(int32_t maxSharedAudioHistoryMs) : 283 ConfigEvent(CFG_EVENT_RESIZE_BUFFER) { 284 mData = new ResizeBufferConfigEventData(maxSharedAudioHistoryMs); 285 } 286 }; 287 288 class CheckOutputStageEffectsEvent : public ConfigEvent { 289 public: CheckOutputStageEffectsEvent()290 CheckOutputStageEffectsEvent() : 291 ConfigEvent(CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS) { 292 } 293 }; 294 295 class HalLatencyModesChangedEvent : public ConfigEvent { 296 public: HalLatencyModesChangedEvent()297 HalLatencyModesChangedEvent() : 298 ConfigEvent(CFG_EVENT_HAL_LATENCY_MODES_CHANGED) { 299 } 300 }; 301 302 303 class PMDeathRecipient : public IBinder::DeathRecipient { 304 public: PMDeathRecipient(const wp<ThreadBase> & thread)305 explicit PMDeathRecipient(const wp<ThreadBase>& thread) : mThread(thread) {} 306 307 // IBinder::DeathRecipient 308 void binderDied(const wp<IBinder>& who) final; 309 310 private: 311 DISALLOW_COPY_AND_ASSIGN(PMDeathRecipient); 312 313 const wp<ThreadBase> mThread; 314 }; 315 type()316 type_t type() const final { return mType; } isDuplicating()317 bool isDuplicating() const final { return (mType == DUPLICATING); } id()318 audio_io_handle_t id() const final { return mId;} 319 sampleRate()320 uint32_t sampleRate() const final { return mSampleRate; } channelMask()321 audio_channel_mask_t channelMask() const final { return mChannelMask; } mixerChannelMask()322 audio_channel_mask_t mixerChannelMask() const override { return mChannelMask; } format()323 audio_format_t format() const final { return mHALFormat; } channelCount()324 uint32_t channelCount() const final { return mChannelCount; } hapticChannelMask()325 audio_channel_mask_t hapticChannelMask() const override { return AUDIO_CHANNEL_NONE; } hapticChannelCount()326 uint32_t hapticChannelCount() const override { return 0; } latency_l()327 uint32_t latency_l() const override { return 0; } // NO_THREAD_SAFETY_ANALYSIS setVolumeForOutput_l(float,float)328 void setVolumeForOutput_l(float /* left */, float /* right */) const override 329 REQUIRES(mutex()) {} 330 331 // Return's the HAL's frame count i.e. fast mixer buffer size. frameCountHAL()332 size_t frameCountHAL() const final { return mFrameCount; } frameSize()333 size_t frameSize() const final { return mFrameSize; } 334 335 // Should be "virtual status_t requestExitAndWait()" and override same 336 // method in Thread, but Thread::requestExitAndWait() is not yet virtual. 337 void exit() final EXCLUDES_ThreadBase_Mutex; 338 status_t setParameters(const String8& keyValuePairs) final EXCLUDES_ThreadBase_Mutex; 339 340 // sendConfigEvent_l() must be called with ThreadBase::mutex() held 341 // Can temporarily release the lock if waiting for a reply from 342 // processConfigEvents_l(). 343 status_t sendConfigEvent_l(sp<ConfigEvent>& event) REQUIRES(mutex()); 344 void sendIoConfigEvent(audio_io_config_event_t event, pid_t pid = 0, 345 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final EXCLUDES_ThreadBase_Mutex; 346 void sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid = 0, 347 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final REQUIRES(mutex()); 348 void sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp) final 349 EXCLUDES_ThreadBase_Mutex; 350 void sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio, bool forApp) final 351 REQUIRES(mutex()); 352 status_t sendSetParameterConfigEvent_l(const String8& keyValuePair) final REQUIRES(mutex()); 353 status_t sendCreateAudioPatchConfigEvent(const struct audio_patch* patch, 354 audio_patch_handle_t* handle) final EXCLUDES_ThreadBase_Mutex; 355 status_t sendReleaseAudioPatchConfigEvent(audio_patch_handle_t handle) final 356 EXCLUDES_ThreadBase_Mutex; 357 status_t sendUpdateOutDeviceConfigEvent( 358 const DeviceDescriptorBaseVector& outDevices) final EXCLUDES_ThreadBase_Mutex; 359 void sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs) final REQUIRES(mutex()); 360 void sendCheckOutputStageEffectsEvent() final EXCLUDES_ThreadBase_Mutex; 361 void sendCheckOutputStageEffectsEvent_l() final REQUIRES(mutex()); 362 void sendHalLatencyModesChangedEvent_l() final REQUIRES(mutex()); 363 364 void processConfigEvents_l() final REQUIRES(mutex()); setCheckOutputStageEffects()365 void setCheckOutputStageEffects() override {} 366 void updateOutDevices(const DeviceDescriptorBaseVector& outDevices) override; 367 void toAudioPortConfig(struct audio_port_config* config) override; 368 void resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs) override REQUIRES(mutex()); 369 370 // see note at declaration of mStandby, mOutDevice and mInDevice inStandby()371 bool inStandby() const override { return mStandby; } outDeviceTypes_l()372 const DeviceTypeSet outDeviceTypes_l() const final REQUIRES(mutex()) { 373 return getAudioDeviceTypes(mOutDeviceTypeAddrs); 374 } inDeviceType_l()375 audio_devices_t inDeviceType_l() const final REQUIRES(mutex()) { 376 return mInDeviceTypeAddr.mType; 377 } getDeviceTypes_l()378 DeviceTypeSet getDeviceTypes_l() const final REQUIRES(mutex()) { 379 return isOutput() ? outDeviceTypes_l() : DeviceTypeSet({inDeviceType_l()}); 380 } 381 outDeviceTypeAddrs()382 const AudioDeviceTypeAddrVector& outDeviceTypeAddrs() const final { 383 return mOutDeviceTypeAddrs; 384 } inDeviceTypeAddr()385 const AudioDeviceTypeAddr& inDeviceTypeAddr() const final { 386 return mInDeviceTypeAddr; 387 } 388 isOutput()389 bool isOutput() const final { return mIsOut; } 390 isOffloadOrMmap()391 bool isOffloadOrMmap() const final { 392 switch (mType) { 393 case OFFLOAD: 394 case MMAP_PLAYBACK: 395 case MMAP_CAPTURE: 396 return true; 397 default: 398 return false; 399 } 400 } 401 402 sp<IAfEffectHandle> createEffect_l( 403 const sp<Client>& client, 404 const sp<media::IEffectClient>& effectClient, 405 int32_t priority, 406 audio_session_t sessionId, 407 effect_descriptor_t *desc, 408 int *enabled, 409 status_t *status /*non-NULL*/, 410 bool pinned, 411 bool probe, 412 bool notifyFramesProcessed) final 413 REQUIRES(audio_utils::AudioFlinger_Mutex); 414 415 // return values for hasAudioSession (bit field) 416 enum effect_state { 417 EFFECT_SESSION = 0x1, // the audio session corresponds to at least one 418 // effect 419 TRACK_SESSION = 0x2, // the audio session corresponds to at least one 420 // track 421 FAST_SESSION = 0x4, // the audio session corresponds to at least one 422 // fast track 423 SPATIALIZED_SESSION = 0x8, // the audio session corresponds to at least one 424 // spatialized track 425 BIT_PERFECT_SESSION = 0x10 // the audio session corresponds to at least one 426 // bit-perfect track 427 }; 428 429 // get effect chain corresponding to session Id. 430 sp<IAfEffectChain> getEffectChain(audio_session_t sessionId) const final; 431 // same as getEffectChain() but must be called with ThreadBase mutex locked 432 sp<IAfEffectChain> getEffectChain_l(audio_session_t sessionId) const final REQUIRES(mutex()); 433 std::vector<int> getEffectIds_l(audio_session_t sessionId) const final REQUIRES(mutex()); 434 435 // lock all effect chains Mutexes. Must be called before releasing the 436 // ThreadBase mutex before processing the mixer and effects. This guarantees the 437 // integrity of the chains during the process. 438 // Also sets the parameter 'effectChains' to current value of mEffectChains. 439 void lockEffectChains_l(Vector<sp<IAfEffectChain>>& effectChains) final 440 REQUIRES(audio_utils::ThreadBase_Mutex) ACQUIRE(audio_utils::EffectChain_Mutex); 441 // unlock effect chains after process 442 void unlockEffectChains(const Vector<sp<IAfEffectChain>>& effectChains) final 443 RELEASE(audio_utils::EffectChain_Mutex); 444 // get a copy of mEffectChains vector getEffectChains_l()445 Vector<sp<IAfEffectChain>> getEffectChains_l() const final REQUIRES(mutex()) { 446 return mEffectChains; 447 } 448 // set audio mode to all effect chains 449 void setMode(audio_mode_t mode) final; 450 // get effect module with corresponding ID on specified audio session 451 sp<IAfEffectModule> getEffect(audio_session_t sessionId, int effectId) const final; 452 sp<IAfEffectModule> getEffect_l(audio_session_t sessionId, int effectId) const final 453 REQUIRES(mutex()); 454 // add and effect module. Also creates the effect chain is none exists for 455 // the effects audio session. Only called in a context of moving an effect 456 // from one thread to another 457 status_t addEffect_ll(const sp<IAfEffectModule>& effect) final 458 REQUIRES(audio_utils::AudioFlinger_Mutex, mutex()); 459 // remove and effect module. Also removes the effect chain is this was the last 460 // effect 461 void removeEffect_l(const sp<IAfEffectModule>& effect, bool release = false) final 462 REQUIRES(mutex()); 463 // disconnect an effect handle from module and destroy module if last handle 464 void disconnectEffectHandle(IAfEffectHandle* handle, bool unpinIfLast) final; 465 // detach all tracks connected to an auxiliary effect detachAuxEffect_l(int)466 void detachAuxEffect_l(int /* effectId */) override REQUIRES(mutex()) {} 467 // TODO(b/291317898) - remove hasAudioSession_l below. 468 uint32_t hasAudioSession_l(audio_session_t sessionId) const override REQUIRES(mutex()) = 0; hasAudioSession(audio_session_t sessionId)469 uint32_t hasAudioSession(audio_session_t sessionId) const final EXCLUDES_ThreadBase_Mutex { 470 audio_utils::lock_guard _l(mutex()); 471 return hasAudioSession_l(sessionId); 472 } 473 474 template <typename T> hasAudioSession_l(audio_session_t sessionId,const T & tracks)475 uint32_t hasAudioSession_l(audio_session_t sessionId, const T& tracks) const 476 REQUIRES(mutex()) { 477 uint32_t result = 0; 478 if (getEffectChain_l(sessionId) != 0) { 479 result = EFFECT_SESSION; 480 } 481 for (size_t i = 0; i < tracks.size(); ++i) { 482 const sp<IAfTrackBase>& track = tracks[i]; 483 if (sessionId == track->sessionId() 484 && !track->isInvalid() // not yet removed from tracks. 485 && !track->isTerminated()) { 486 result |= TRACK_SESSION; 487 if (track->isFastTrack()) { 488 result |= FAST_SESSION; // caution, only represents first track. 489 } 490 if (track->isSpatialized()) { 491 result |= SPATIALIZED_SESSION; // caution, only first track. 492 } 493 if (track->isBitPerfect()) { 494 result |= BIT_PERFECT_SESSION; 495 } 496 break; 497 } 498 } 499 return result; 500 } 501 502 // the value returned by default implementation is not important as the 503 // strategy is only meaningful for PlaybackThread which implements this method getStrategyForSession_l(audio_session_t)504 product_strategy_t getStrategyForSession_l( 505 audio_session_t /* sessionId */) const override REQUIRES(mutex()){ 506 return static_cast<product_strategy_t>(0); 507 } 508 509 // check if some effects must be suspended/restored when an effect is enabled 510 // or disabled 511 void checkSuspendOnEffectEnabled(bool enabled, 512 audio_session_t sessionId, 513 bool threadLocked) final; 514 515 516 // Return a reference to a per-thread heap which can be used to allocate IMemory 517 // objects that will be read-only to client processes, read/write to mediaserver, 518 // and shared by all client processes of the thread. 519 // The heap is per-thread rather than common across all threads, because 520 // clients can't be trusted not to modify the offset of the IMemory they receive. 521 // If a thread does not have such a heap, this method returns 0. readOnlyHeap()522 sp<MemoryDealer> readOnlyHeap() const override { return nullptr; } 523 pipeMemory()524 sp<IMemory> pipeMemory() const override { return nullptr; } 525 526 void systemReady() final EXCLUDES_ThreadBase_Mutex; 527 528 void broadcast_l() final REQUIRES(mutex()); 529 isTimestampCorrectionEnabled_l()530 bool isTimestampCorrectionEnabled_l() const override REQUIRES(mutex()) { return false; } 531 isMsdDevice()532 bool isMsdDevice() const final { return mIsMsdDevice; } 533 534 void dump(int fd, const Vector<String16>& args) override; 535 536 // deliver stats to mediametrics. 537 void sendStatistics(bool force) final 538 REQUIRES(ThreadBase_ThreadLoop) EXCLUDES_ThreadBase_Mutex; 539 mutex()540 audio_utils::mutex& mutex() const final RETURN_CAPABILITY(audio_utils::ThreadBase_Mutex) { 541 return mMutex; 542 } 543 mutable audio_utils::mutex mMutex{audio_utils::MutexOrder::kThreadBase_Mutex}; 544 545 void onEffectEnable(const sp<IAfEffectModule>& effect) final EXCLUDES_ThreadBase_Mutex; 546 void onEffectDisable() final EXCLUDES_ThreadBase_Mutex; 547 548 // invalidateTracksForAudioSession_l must be called with holding mutex(). invalidateTracksForAudioSession_l(audio_session_t)549 void invalidateTracksForAudioSession_l(audio_session_t /* sessionId */) const override 550 REQUIRES(mutex()) {} 551 // Invalidate all the tracks with the given audio session. invalidateTracksForAudioSession(audio_session_t sessionId)552 void invalidateTracksForAudioSession(audio_session_t sessionId) const final 553 EXCLUDES_ThreadBase_Mutex { 554 audio_utils::lock_guard _l(mutex()); 555 invalidateTracksForAudioSession_l(sessionId); 556 } 557 558 template <typename T> invalidateTracksForAudioSession_l(audio_session_t sessionId,const T & tracks)559 void invalidateTracksForAudioSession_l(audio_session_t sessionId, 560 const T& tracks) const REQUIRES(mutex()) { 561 for (size_t i = 0; i < tracks.size(); ++i) { 562 const sp<IAfTrackBase>& track = tracks[i]; 563 if (sessionId == track->sessionId()) { 564 track->invalidate(); 565 } 566 } 567 } 568 569 void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) override 570 REQUIRES(audio_utils::AudioFlinger_Mutex); 571 void stopMelComputation_l() override 572 REQUIRES(audio_utils::AudioFlinger_Mutex); 573 574 protected: 575 576 // entry describing an effect being suspended in mSuspendedSessions keyed vector 577 class SuspendedSessionDesc : public RefBase { 578 public: SuspendedSessionDesc()579 SuspendedSessionDesc() : mRefCount(0) {} 580 581 int mRefCount; // number of active suspend requests 582 effect_uuid_t mType; // effect type UUID 583 }; 584 585 void acquireWakeLock() EXCLUDES_ThreadBase_Mutex; 586 virtual void acquireWakeLock_l() REQUIRES(mutex()); 587 void releaseWakeLock() EXCLUDES_ThreadBase_Mutex; 588 void releaseWakeLock_l() REQUIRES(mutex()); 589 void updateWakeLockUids_l(const SortedVector<uid_t> &uids) REQUIRES(mutex()); 590 void getPowerManager_l() REQUIRES(mutex()); 591 // suspend or restore effects of the specified type (or all if type is NULL) 592 // on a given session. The number of suspend requests is counted and restore 593 // occurs when all suspend requests are cancelled. 594 void setEffectSuspended_l(const effect_uuid_t *type, 595 bool suspend, 596 audio_session_t sessionId) final REQUIRES(mutex()); 597 // updated mSuspendedSessions when an effect is suspended or restored 598 void updateSuspendedSessions_l(const effect_uuid_t *type, 599 bool suspend, 600 audio_session_t sessionId) REQUIRES(mutex()); 601 // check if some effects must be suspended when an effect chain is added 602 void checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain) REQUIRES(mutex()); 603 604 /** 605 * waitWhileThreadBusy_l() serves as a mutex gate, which does not allow 606 * progress beyond the method while the PlaybackThread is busy (see setThreadBusy_l()). 607 * During the wait, the ThreadBase_Mutex is temporarily unlocked. 608 * 609 * This implementation uses a condition variable. Alternative methods to gate 610 * the thread may use a second mutex (i.e. entry based on scoped_lock(mutex, gating_mutex)), 611 * but those have less flexibility and more lock order issues. 612 * 613 * Current usage by Track::destroy(), Track::start(), Track::stop(), Track::pause(), 614 * and Track::flush() block this way, and the primary caller is through TrackHandle 615 * with no other mutexes held. 616 * 617 * Special tracks like PatchTrack and OutputTrack may also hold the another thread's 618 * ThreadBase_Mutex during this time. No other mutex is held. 619 */ 620 waitWhileThreadBusy_l(audio_utils::unique_lock & ul)621 void waitWhileThreadBusy_l(audio_utils::unique_lock& ul) final REQUIRES(mutex()) { 622 // the wait returns immediately if the predicate is satisfied. 623 mThreadBusyCv.wait(ul, [&]{ return mThreadBusy == false;}); 624 } 625 setThreadBusy_l(bool busy)626 void setThreadBusy_l(bool busy) REQUIRES(mutex()) { 627 if (busy == mThreadBusy) return; 628 mThreadBusy = busy; 629 if (busy == true) return; // no need to wake threads if we become busy. 630 mThreadBusyCv.notify_all(); 631 } 632 633 // sends the metadata of the active tracks to the HAL 634 struct MetadataUpdate { 635 std::vector<playback_track_metadata_v7_t> playbackMetadataUpdate; 636 std::vector<record_track_metadata_v7_t> recordMetadataUpdate; 637 }; 638 // NO_THREAD_SAFETY_ANALYSIS, updateMetadata_l() should include ThreadBase_ThreadLoop 639 // but MmapThread::start() -> exitStandby_l() -> updateMetadata_l() prevents this. 640 virtual MetadataUpdate updateMetadata_l() REQUIRES(mutex()) = 0; 641 642 String16 getWakeLockTag(); 643 preExit()644 virtual void preExit() EXCLUDES_ThreadBase_Mutex {} setMasterMono_l(bool mono __unused)645 virtual void setMasterMono_l(bool mono __unused) REQUIRES(mutex()) {} requireMonoBlend()646 virtual bool requireMonoBlend() { return false; } 647 648 // called within the threadLoop to obtain timestamp from the HAL. threadloop_getHalTimestamp_l(ExtendedTimestamp * timestamp __unused)649 virtual status_t threadloop_getHalTimestamp_l( 650 ExtendedTimestamp *timestamp __unused) const 651 REQUIRES(mutex(), ThreadBase_ThreadLoop) { 652 return INVALID_OPERATION; 653 } 654 public: 655 // TODO(b/291317898) organize with publics 656 product_strategy_t getStrategyForStream(audio_stream_type_t stream) const; 657 protected: 658 onHalLatencyModesChanged_l()659 virtual void onHalLatencyModesChanged_l() REQUIRES(mutex()) {} 660 dumpInternals_l(int fd __unused,const Vector<String16> & args __unused)661 virtual void dumpInternals_l(int fd __unused, const Vector<String16>& args __unused) 662 REQUIRES(mutex()) {} dumpTracks_l(int fd __unused,const Vector<String16> & args __unused)663 virtual void dumpTracks_l(int fd __unused, const Vector<String16>& args __unused) 664 REQUIRES(mutex()) {} 665 666 const type_t mType; 667 668 // Used by parameters, config events, addTrack_l, exit 669 audio_utils::condition_variable mWaitWorkCV; 670 671 const sp<IAfThreadCallback> mAfThreadCallback; 672 ThreadMetrics mThreadMetrics; 673 const bool mIsOut; 674 675 // mThreadBusy is checked under the ThreadBase_Mutex to ensure that 676 // TrackHandle operations do not proceed while the ThreadBase is busy 677 // with the track. mThreadBusy is only true if the track is active. 678 // 679 bool mThreadBusy = false; // GUARDED_BY(ThreadBase_Mutex) but read in lambda. 680 audio_utils::condition_variable mThreadBusyCv; 681 682 // updated by PlaybackThread::readOutputParameters_l() or 683 // RecordThread::readInputParameters_l() 684 uint32_t mSampleRate; 685 size_t mFrameCount; // output HAL, direct output, record 686 audio_channel_mask_t mChannelMask; 687 uint32_t mChannelCount; 688 size_t mFrameSize; 689 // not HAL frame size, this is for output sink (to pipe to fast mixer) 690 audio_format_t mFormat; // Source format for Recording and 691 // Sink format for Playback. 692 // Sink format may be different than 693 // HAL format if Fastmixer is used. 694 audio_format_t mHALFormat; 695 size_t mBufferSize; // HAL buffer size for read() or write() 696 697 // output device types and addresses 698 AudioDeviceTypeAddrVector mOutDeviceTypeAddrs GUARDED_BY(mutex()); 699 AudioDeviceTypeAddr mInDeviceTypeAddr GUARDED_BY(mutex()); // input device type and address 700 Vector<sp<ConfigEvent>> mConfigEvents GUARDED_BY(mutex()); 701 702 // events awaiting system ready 703 Vector<sp<ConfigEvent>> mPendingConfigEvents GUARDED_BY(mutex()); 704 705 // These fields are written and read by thread itself without lock or barrier, 706 // and read by other threads without lock or barrier via standby(), outDeviceTypes() 707 // and inDeviceType(). 708 // Because of the absence of a lock or barrier, any other thread that reads 709 // these fields must use the information in isolation, or be prepared to deal 710 // with possibility that it might be inconsistent with other information. 711 bool mStandby; // Whether thread is currently in standby. 712 713 // NO_THREAD_SAFETY_ANALYSIS - mPatch and mAudioSource should be guarded by mutex(). 714 struct audio_patch mPatch; 715 audio_source_t mAudioSource; 716 717 const audio_io_handle_t mId; 718 Vector<sp<IAfEffectChain>> mEffectChains GUARDED_BY(mutex()); 719 720 static const int kThreadNameLength = 16; // prctl(PR_SET_NAME) limit 721 char mThreadName[kThreadNameLength]; // guaranteed NUL-terminated 722 sp<os::IPowerManager> mPowerManager GUARDED_BY(mutex()); 723 sp<IBinder> mWakeLockToken GUARDED_BY(mutex()); 724 const sp<PMDeathRecipient> mDeathRecipient; 725 // list of suspended effects per session and per type. The first (outer) vector is 726 // keyed by session ID, the second (inner) by type UUID timeLow field 727 // Updated by updateSuspendedSessions_l() only. 728 KeyedVector< audio_session_t, KeyedVector< int, sp<SuspendedSessionDesc> > > 729 mSuspendedSessions; 730 // TODO: add comment and adjust size as needed 731 static const size_t kLogSize = 4 * 1024; 732 sp<NBLog::Writer> mNBLogWriter; 733 bool mSystemReady; 734 735 // NO_THREAD_SAFETY_ANALYSIS - mTimestamp and mTimestampVerifier should be 736 // accessed under mutex for the RecordThread. 737 ExtendedTimestamp mTimestamp; 738 TimestampVerifier<int64_t /* frame count */, int64_t /* time ns */> mTimestampVerifier; 739 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush 740 // TODO: add confirmation checks: 741 // 1) DIRECT threads and linear PCM format really resets to 0? 742 // 2) Is frame count really valid if not linear pcm? 743 // 3) Are all 64 bits of position returned, not just lowest 32 bits? 744 // Timestamp corrected device should be a single device. 745 746 audio_devices_t mTimestampCorrectedDevice = AUDIO_DEVICE_NONE; // CONST set in ctor 747 748 // ThreadLoop statistics per iteration. 749 std::atomic<int64_t> mLastIoBeginNs = -1; // set in threadLoop, read by dump() 750 int64_t mLastIoEndNs GUARDED_BY(ThreadBase_ThreadLoop) = -1; 751 752 // ThreadSnapshot is thread-safe (internally locked) 753 mediautils::ThreadSnapshot mThreadSnapshot; 754 GUARDED_BY(mutex ())755 audio_utils::Statistics<double> mIoJitterMs GUARDED_BY(mutex()) {0.995 /* alpha */}; GUARDED_BY(mutex ())756 audio_utils::Statistics<double> mProcessTimeMs GUARDED_BY(mutex()) {0.995 /* alpha */}; 757 758 // NO_THREAD_SAFETY_ANALYSIS GUARDED_BY(mutex()) 759 audio_utils::Statistics<double> mLatencyMs{0.995 /* alpha */}; 760 audio_utils::Statistics<double> mMonopipePipeDepthStats{0.999 /* alpha */}; 761 762 // Save the last count when we delivered statistics to mediametrics. 763 int64_t mLastRecordedTimestampVerifierN = 0; 764 int64_t mLastRecordedTimeNs = 0; // BOOTTIME to include suspend. 765 766 bool mIsMsdDevice = false; 767 // A condition that must be evaluated by the thread loop has changed and 768 // we must not wait for async write callback in the thread loop before evaluating it 769 bool mSignalPending; 770 771 #ifdef TEE_SINK 772 NBAIO_Tee mTee; 773 #endif 774 // ActiveTracks is a sorted vector of track type T representing the 775 // active tracks of threadLoop() to be considered by the locked prepare portion. 776 // ActiveTracks should be accessed with the ThreadBase lock held. 777 // 778 // During processing and I/O, the threadLoop does not hold the lock; 779 // hence it does not directly use ActiveTracks. Care should be taken 780 // to hold local strong references or defer removal of tracks 781 // if the threadLoop may still be accessing those tracks due to mix, etc. 782 // 783 // This class updates power information appropriately. 784 // 785 786 template <typename T> 787 class ActiveTracks { 788 public: 789 explicit ActiveTracks(SimpleLog *localLog = nullptr) 790 : mActiveTracksGeneration(0) 791 , mLastActiveTracksGeneration(0) 792 , mLocalLog(localLog) 793 { } 794 ~ActiveTracks()795 ~ActiveTracks() { 796 ALOGW_IF(!mActiveTracks.isEmpty(), 797 "ActiveTracks should be empty in destructor"); 798 } 799 // returns the last track added (even though it may have been 800 // subsequently removed from ActiveTracks). 801 // 802 // Used for DirectOutputThread to ensure a flush is called when transitioning 803 // to a new track (even though it may be on the same session). 804 // Used for OffloadThread to ensure that volume and mixer state is 805 // taken from the latest track added. 806 // 807 // The latest track is saved with a weak pointer to prevent keeping an 808 // otherwise useless track alive. Thus the function will return nullptr 809 // if the latest track has subsequently been removed and destroyed. getLatest()810 sp<T> getLatest() { 811 return mLatestActiveTrack.promote(); 812 } 813 814 // SortedVector methods 815 ssize_t add(const sp<T> &track); 816 ssize_t remove(const sp<T> &track); size()817 size_t size() const { 818 return mActiveTracks.size(); 819 } isEmpty()820 bool isEmpty() const { 821 return mActiveTracks.isEmpty(); 822 } indexOf(const sp<T> & item)823 ssize_t indexOf(const sp<T>& item) const { 824 return mActiveTracks.indexOf(item); 825 } 826 sp<T> operator[](size_t index) const { 827 return mActiveTracks[index]; 828 } begin()829 typename SortedVector<sp<T>>::iterator begin() { 830 return mActiveTracks.begin(); 831 } end()832 typename SortedVector<sp<T>>::iterator end() { 833 return mActiveTracks.end(); 834 } 835 836 // Due to Binder recursion optimization, clear() and updatePowerState() 837 // cannot be called from a Binder thread because they may call back into 838 // the original calling process (system server) for BatteryNotifier 839 // (which requires a Java environment that may not be present). 840 // Hence, call clear() and updatePowerState() only from the 841 // ThreadBase thread. 842 void clear(); 843 // periodically called in the threadLoop() to update power state uids. 844 void updatePowerState_l(const sp<ThreadBase>& thread, bool force = false) 845 REQUIRES(audio_utils::ThreadBase_Mutex); 846 847 /** @return true if one or move active tracks was added or removed since the 848 * last time this function was called or the vector was created. 849 * true if volume of one of active tracks was changed. 850 */ 851 bool readAndClearHasChanged(); 852 853 /** Force updating track metadata to audio HAL stream next time 854 * readAndClearHasChanged() is called. 855 */ setHasChanged()856 void setHasChanged() { mHasChanged = true; } 857 858 private: 859 void logTrack(const char *funcName, const sp<T> &track) const; 860 getWakeLockUids()861 SortedVector<uid_t> getWakeLockUids() { 862 SortedVector<uid_t> wakeLockUids; 863 for (const sp<T> &track : mActiveTracks) { 864 wakeLockUids.add(track->uid()); 865 } 866 return wakeLockUids; // moved by underlying SharedBuffer 867 } 868 869 SortedVector<sp<T>> mActiveTracks; 870 int mActiveTracksGeneration; 871 int mLastActiveTracksGeneration; 872 wp<T> mLatestActiveTrack; // latest track added to ActiveTracks 873 SimpleLog * const mLocalLog; 874 // If the vector has changed since last call to readAndClearHasChanged 875 bool mHasChanged = false; 876 }; 877 878 SimpleLog mLocalLog; // locked internally 879 880 private: 881 void dumpBase_l(int fd, const Vector<String16>& args) REQUIRES(mutex()); 882 void dumpEffectChains_l(int fd, const Vector<String16>& args) REQUIRES(mutex()); 883 }; 884 885 // --- PlaybackThread --- 886 class PlaybackThread : public ThreadBase, public virtual IAfPlaybackThread, 887 public StreamOutHalInterfaceCallback, 888 public virtual VolumeInterface, public StreamOutHalInterfaceEventCallback { 889 public: asIAfPlaybackThread()890 sp<IAfPlaybackThread> asIAfPlaybackThread() final { 891 return sp<IAfPlaybackThread>::fromExisting(this); 892 } 893 894 // retry count before removing active track in case of underrun on offloaded thread: 895 // we need to make sure that AudioTrack client has enough time to send large buffers 896 //FIXME may be more appropriate if expressed in time units. Need to revise how underrun is 897 // handled for offloaded tracks 898 static const int8_t kMaxTrackRetriesOffload = 20; 899 static const int8_t kMaxTrackStartupRetriesOffload = 100; 900 static constexpr uint32_t kMaxTracksPerUid = 40; 901 static constexpr size_t kMaxTracks = 256; 902 903 // Maximum delay (in nanoseconds) for upcoming buffers in suspend mode, otherwise 904 // if delay is greater, the estimated time for timeLoopNextNs is reset. 905 // This allows for catch-up to be done for small delays, while resetting the estimate 906 // for initial conditions or large delays. 907 static const nsecs_t kMaxNextBufferDelayNs = 100000000; 908 909 PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output, 910 audio_io_handle_t id, type_t type, bool systemReady, 911 audio_config_base_t *mixerConfig = nullptr); 912 ~PlaybackThread() override; 913 914 // Thread virtuals 915 bool threadLoop() final REQUIRES(ThreadBase_ThreadLoop) EXCLUDES_ThreadBase_Mutex; 916 917 // RefBase 918 void onFirstRef() override; 919 920 status_t checkEffectCompatibility_l( 921 const effect_descriptor_t* desc, audio_session_t sessionId) final REQUIRES(mutex()); 922 addOutputTrack_l(const sp<IAfTrack> & track)923 void addOutputTrack_l(const sp<IAfTrack>& track) final REQUIRES(mutex()) { 924 mTracks.add(track); 925 } 926 927 protected: 928 // Code snippets that were lifted up out of threadLoop() 929 virtual void threadLoop_mix() REQUIRES(ThreadBase_ThreadLoop) = 0; 930 virtual void threadLoop_sleepTime() REQUIRES(ThreadBase_ThreadLoop) = 0; 931 virtual ssize_t threadLoop_write() REQUIRES(ThreadBase_ThreadLoop); 932 virtual void threadLoop_drain() REQUIRES(ThreadBase_ThreadLoop); 933 virtual void threadLoop_standby() REQUIRES(ThreadBase_ThreadLoop); 934 virtual void threadLoop_exit() REQUIRES(ThreadBase_ThreadLoop); 935 virtual void threadLoop_removeTracks(const Vector<sp<IAfTrack>>& tracksToRemove) 936 REQUIRES(ThreadBase_ThreadLoop); 937 938 // prepareTracks_l reads and writes mActiveTracks, and returns 939 // the pending set of tracks to remove via Vector 'tracksToRemove'. The caller 940 // is responsible for clearing or destroying this Vector later on, when it 941 // is safe to do so. That will drop the final ref count and destroy the tracks. 942 virtual mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove) 943 REQUIRES(mutex(), ThreadBase_ThreadLoop) = 0; 944 945 void removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove) REQUIRES(mutex()); 946 status_t handleVoipVolume_l(float *volume) REQUIRES(mutex()); 947 948 // StreamOutHalInterfaceCallback implementation 949 virtual void onWriteReady(); 950 virtual void onDrainReady(); 951 virtual void onError(bool /*isHardError*/); 952 953 public: // AsyncCallbackThread 954 void resetWriteBlocked(uint32_t sequence); 955 void resetDraining(uint32_t sequence); 956 protected: 957 958 virtual bool waitingAsyncCallback(); 959 virtual bool waitingAsyncCallback_l() REQUIRES(mutex()); 960 virtual bool shouldStandby_l() REQUIRES(mutex(), ThreadBase_ThreadLoop); 961 virtual void onAddNewTrack_l() REQUIRES(mutex()); 962 public: // AsyncCallbackThread 963 void onAsyncError(bool isHardError); // error reported by AsyncCallbackThread 964 protected: 965 // StreamHalInterfaceCodecFormatCallback implementation 966 void onCodecFormatChanged( 967 const std::vector<uint8_t>& metadataBs) final; 968 969 // ThreadBase virtuals 970 void preExit() final EXCLUDES_ThreadBase_Mutex; 971 keepWakeLock()972 virtual bool keepWakeLock() const { return true; } acquireWakeLock_l()973 virtual void acquireWakeLock_l() REQUIRES(mutex()) { 974 ThreadBase::acquireWakeLock_l(); 975 mActiveTracks.updatePowerState_l(this, true /* force */); 976 } 977 checkOutputStageEffects()978 virtual void checkOutputStageEffects() 979 REQUIRES(ThreadBase_ThreadLoop) EXCLUDES_ThreadBase_Mutex {} setHalLatencyMode_l()980 virtual void setHalLatencyMode_l() {} 981 982 983 void dumpInternals_l(int fd, const Vector<String16>& args) override REQUIRES(mutex()); 984 void dumpTracks_l(int fd, const Vector<String16>& args) final REQUIRES(mutex()); 985 986 public: 987 initCheck()988 status_t initCheck() const final { return mOutput == nullptr ? NO_INIT : NO_ERROR; } 989 990 // return estimated latency in milliseconds, as reported by HAL 991 uint32_t latency() const final; 992 // same, but lock must already be held 993 uint32_t latency_l() const final /* REQUIRES(mutex()) */; // NO_THREAD_SAFETY_ANALYSIS 994 995 // VolumeInterface 996 void setMasterVolume(float value) final; 997 void setMasterBalance(float balance) override EXCLUDES_ThreadBase_Mutex; 998 void setMasterMute(bool muted) final; 999 void setStreamVolume(audio_stream_type_t stream, float value) final EXCLUDES_ThreadBase_Mutex; 1000 void setStreamMute(audio_stream_type_t stream, bool muted) final EXCLUDES_ThreadBase_Mutex; 1001 float streamVolume(audio_stream_type_t stream) const final EXCLUDES_ThreadBase_Mutex; 1002 void setVolumeForOutput_l(float left, float right) const final; 1003 1004 sp<IAfTrack> createTrack_l( 1005 const sp<Client>& client, 1006 audio_stream_type_t streamType, 1007 const audio_attributes_t& attr, 1008 uint32_t *sampleRate, 1009 audio_format_t format, 1010 audio_channel_mask_t channelMask, 1011 size_t *pFrameCount, 1012 size_t *pNotificationFrameCount, 1013 uint32_t notificationsPerBuffer, 1014 float speed, 1015 const sp<IMemory>& sharedBuffer, 1016 audio_session_t sessionId, 1017 audio_output_flags_t *flags, 1018 pid_t creatorPid, 1019 const AttributionSourceState& attributionSource, 1020 pid_t tid, 1021 status_t *status /*non-NULL*/, 1022 audio_port_handle_t portId, 1023 const sp<media::IAudioTrackCallback>& callback, 1024 bool isSpatialized, 1025 bool isBitPerfect, 1026 audio_output_flags_t* afTrackFlags) final 1027 REQUIRES(audio_utils::AudioFlinger_Mutex); 1028 isTrackActive(const sp<IAfTrack> & track)1029 bool isTrackActive(const sp<IAfTrack>& track) const final { 1030 return mActiveTracks.indexOf(track) >= 0; 1031 } 1032 getOutput_l()1033 AudioStreamOut* getOutput_l() const final REQUIRES(mutex()) { return mOutput; } 1034 AudioStreamOut* getOutput() const final EXCLUDES_ThreadBase_Mutex; 1035 AudioStreamOut* clearOutput() final EXCLUDES_ThreadBase_Mutex; 1036 1037 // NO_THREAD_SAFETY_ANALYSIS -- probably needs a lock. 1038 sp<StreamHalInterface> stream() const final; 1039 1040 // suspend(), restore(), and isSuspended() are implemented atomically. suspend()1041 void suspend() final { ++mSuspended; } restore()1042 void restore() final { 1043 // if restore() is done without suspend(), get back into 1044 // range so that the next suspend() will operate correctly 1045 while (true) { 1046 int32_t suspended = mSuspended; 1047 if (suspended <= 0) { 1048 ALOGW("%s: invalid mSuspended %d <= 0", __func__, suspended); 1049 return; 1050 } 1051 const int32_t desired = suspended - 1; 1052 if (mSuspended.compare_exchange_weak(suspended, desired)) return; 1053 } 1054 } isSuspended()1055 bool isSuspended() const final { return mSuspended > 0; } 1056 1057 String8 getParameters(const String8& keys) EXCLUDES_ThreadBase_Mutex; 1058 1059 // Hold either the AudioFlinger::mutex or the ThreadBase::mutex 1060 void ioConfigChanged_l(audio_io_config_event_t event, pid_t pid = 0, 1061 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final; 1062 status_t getRenderPosition(uint32_t* halFrames, uint32_t* dspFrames) const final 1063 EXCLUDES_ThreadBase_Mutex; 1064 // Consider also removing and passing an explicit mMainBuffer initialization 1065 // parameter to AF::IAfTrack::Track(). sinkBuffer()1066 float* sinkBuffer() const final { 1067 return reinterpret_cast<float *>(mSinkBuffer); }; 1068 1069 void detachAuxEffect_l(int effectId) final REQUIRES(mutex()); 1070 1071 status_t attachAuxEffect(const sp<IAfTrack>& track, int EffectId) final 1072 EXCLUDES_ThreadBase_Mutex; 1073 status_t attachAuxEffect_l(const sp<IAfTrack>& track, int EffectId) final REQUIRES(mutex()); 1074 1075 status_t addEffectChain_l(const sp<IAfEffectChain>& chain) final REQUIRES(mutex()); 1076 size_t removeEffectChain_l(const sp<IAfEffectChain>& chain) final REQUIRES(mutex()); hasAudioSession_l(audio_session_t sessionId)1077 uint32_t hasAudioSession_l(audio_session_t sessionId) const final REQUIRES(mutex()) { 1078 return ThreadBase::hasAudioSession_l(sessionId, mTracks); 1079 } 1080 product_strategy_t getStrategyForSession_l(audio_session_t sessionId) const final 1081 REQUIRES(mutex()); 1082 1083 1084 status_t setSyncEvent(const sp<audioflinger::SyncEvent>& event) final 1085 EXCLUDES_ThreadBase_Mutex; 1086 // could be static. 1087 bool isValidSyncEvent(const sp<audioflinger::SyncEvent>& event) const final; 1088 1089 // Does this require the AudioFlinger mutex as well? 1090 bool invalidateTracks_l(audio_stream_type_t streamType) final 1091 REQUIRES(mutex()); 1092 bool invalidateTracks_l(std::set<audio_port_handle_t>& portIds) final 1093 REQUIRES(mutex()); 1094 void invalidateTracks(audio_stream_type_t streamType) override; 1095 // Invalidate tracks by a set of port ids. The port id will be removed from 1096 // the given set if the corresponding track is found and invalidated. 1097 void invalidateTracks(std::set<audio_port_handle_t>& portIds) override 1098 EXCLUDES_ThreadBase_Mutex; 1099 frameCount()1100 size_t frameCount() const final { return mNormalFrameCount; } 1101 mixerChannelMask()1102 audio_channel_mask_t mixerChannelMask() const final { 1103 return mMixerChannelMask; 1104 } 1105 1106 status_t getTimestamp_l(AudioTimestamp& timestamp) final 1107 REQUIRES(mutex(), ThreadBase_ThreadLoop); 1108 1109 void addPatchTrack(const sp<IAfPatchTrack>& track) final EXCLUDES_ThreadBase_Mutex; 1110 void deletePatchTrack(const sp<IAfPatchTrack>& track) final EXCLUDES_ThreadBase_Mutex; 1111 1112 // NO_THREAD_SAFETY_ANALYSIS - fix this to use atomics. 1113 void toAudioPortConfig(struct audio_port_config* config) final; 1114 1115 // Return the asynchronous signal wait time. computeWaitTimeNs_l()1116 int64_t computeWaitTimeNs_l() const override REQUIRES(mutex()) { return INT64_MAX; } 1117 // returns true if the track is allowed to be added to the thread. isTrackAllowed_l(audio_channel_mask_t channelMask __unused,audio_format_t format __unused,audio_session_t sessionId __unused,uid_t uid)1118 bool isTrackAllowed_l( 1119 audio_channel_mask_t channelMask __unused, 1120 audio_format_t format __unused, 1121 audio_session_t sessionId __unused, 1122 uid_t uid) const override REQUIRES(mutex()) { 1123 return trackCountForUid_l(uid) < PlaybackThread::kMaxTracksPerUid 1124 && mTracks.size() < PlaybackThread::kMaxTracks; 1125 } 1126 isTimestampCorrectionEnabled_l()1127 bool isTimestampCorrectionEnabled_l() const final REQUIRES(mutex()) { 1128 return audio_is_output_devices(mTimestampCorrectedDevice) 1129 && outDeviceTypes_l().count(mTimestampCorrectedDevice) != 0; 1130 } 1131 1132 // NO_THREAD_SAFETY_ANALYSIS - fix this to be atomic. isStreamInitialized()1133 bool isStreamInitialized() const final { 1134 return !(mOutput == nullptr || mOutput->stream == nullptr); 1135 } 1136 hapticChannelMask()1137 audio_channel_mask_t hapticChannelMask() const final { 1138 return mHapticChannelMask; 1139 } 1140 hapticChannelCount()1141 uint32_t hapticChannelCount() const final { 1142 return mHapticChannelCount; 1143 } 1144 supportsHapticPlayback()1145 bool supportsHapticPlayback() const final { 1146 return (mHapticChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE; 1147 } 1148 setDownStreamPatch(const struct audio_patch * patch)1149 void setDownStreamPatch(const struct audio_patch* patch) final EXCLUDES_ThreadBase_Mutex { 1150 audio_utils::lock_guard _l(mutex()); 1151 mDownStreamPatch = *patch; 1152 } 1153 1154 IAfTrack* getTrackById_l(audio_port_handle_t trackId) final REQUIRES(mutex()); 1155 hasMixer()1156 bool hasMixer() const final { 1157 return mType == MIXER || mType == DUPLICATING || mType == SPATIALIZER; 1158 } 1159 setRequestedLatencyMode(audio_latency_mode_t)1160 status_t setRequestedLatencyMode( 1161 audio_latency_mode_t /* mode */) override { return INVALID_OPERATION; } 1162 getSupportedLatencyModes(std::vector<audio_latency_mode_t> *)1163 status_t getSupportedLatencyModes( 1164 std::vector<audio_latency_mode_t>* /* modes */) override { 1165 return INVALID_OPERATION; 1166 } 1167 setBluetoothVariableLatencyEnabled(bool)1168 status_t setBluetoothVariableLatencyEnabled(bool /* enabled */) override{ 1169 return INVALID_OPERATION; 1170 } 1171 1172 void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) override 1173 REQUIRES(audio_utils::AudioFlinger_Mutex); 1174 void stopMelComputation_l() override 1175 REQUIRES(audio_utils::AudioFlinger_Mutex); 1176 setStandby()1177 void setStandby() final EXCLUDES_ThreadBase_Mutex { 1178 audio_utils::lock_guard _l(mutex()); 1179 setStandby_l(); 1180 } 1181 setStandby_l()1182 void setStandby_l() final REQUIRES(mutex()) { 1183 mStandby = true; 1184 mHalStarted = false; 1185 mKernelPositionOnStandby = 1186 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]; 1187 } 1188 waitForHalStart()1189 bool waitForHalStart() final EXCLUDES_ThreadBase_Mutex { 1190 audio_utils::unique_lock _l(mutex()); 1191 static const nsecs_t kWaitHalTimeoutNs = seconds(2); 1192 nsecs_t endWaitTimetNs = systemTime() + kWaitHalTimeoutNs; 1193 while (!mHalStarted) { 1194 nsecs_t timeNs = systemTime(); 1195 if (timeNs >= endWaitTimetNs) { 1196 break; 1197 } 1198 nsecs_t waitTimeLeftNs = endWaitTimetNs - timeNs; 1199 mWaitHalStartCV.wait_for(_l, std::chrono::nanoseconds(waitTimeLeftNs)); 1200 } 1201 return mHalStarted; 1202 } 1203 setTracksInternalMute(std::map<audio_port_handle_t,bool> *)1204 void setTracksInternalMute(std::map<audio_port_handle_t, bool>* /* tracksInternalMute */) 1205 override EXCLUDES_ThreadBase_Mutex { 1206 // Do nothing. It is only used for bit perfect thread 1207 } 1208 protected: 1209 // updated by readOutputParameters_l() 1210 size_t mNormalFrameCount; // normal mixer and effects 1211 1212 // throttle the thread processing 1213 bool mThreadThrottle GUARDED_BY(ThreadBase_ThreadLoop); 1214 1215 // throttle time for MIXER threads - atomic as read by dump() 1216 std::atomic<uint32_t> mThreadThrottleTimeMs; 1217 1218 // notify once per throttling 1219 uint32_t mThreadThrottleEndMs GUARDED_BY(ThreadBase_ThreadLoop); 1220 1221 // half the buffer size in milliseconds 1222 uint32_t mHalfBufferMs GUARDED_BY(ThreadBase_ThreadLoop); 1223 1224 void* mSinkBuffer; // frame size aligned sink buffer 1225 1226 // TODO: 1227 // Rearrange the buffer info into a struct/class with 1228 // clear, copy, construction, destruction methods. 1229 // 1230 // mSinkBuffer also has associated with it: 1231 // 1232 // mSinkBufferSize: Sink Buffer Size 1233 // mFormat: Sink Buffer Format 1234 1235 // Mixer Buffer (mMixerBuffer*) 1236 // 1237 // In the case of floating point or multichannel data, which is not in the 1238 // sink format, it is required to accumulate in a higher precision or greater channel count 1239 // buffer before downmixing or data conversion to the sink buffer. 1240 1241 // Set to "true" to enable the Mixer Buffer otherwise mixer output goes to sink buffer. 1242 bool mMixerBufferEnabled GUARDED_BY(ThreadBase_ThreadLoop); 1243 1244 // Storage, 32 byte aligned (may make this alignment a requirement later). 1245 // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames. 1246 void* mMixerBuffer GUARDED_BY(ThreadBase_ThreadLoop); 1247 1248 // Size of mMixerBuffer in bytes: mNormalFrameCount * #channels * sampsize. 1249 size_t mMixerBufferSize GUARDED_BY(ThreadBase_ThreadLoop); 1250 1251 // The audio format of mMixerBuffer. Set to AUDIO_FORMAT_PCM_(FLOAT|16_BIT) only. 1252 audio_format_t mMixerBufferFormat GUARDED_BY(ThreadBase_ThreadLoop); 1253 1254 // An internal flag set to true by MixerThread::prepareTracks_l() 1255 // when mMixerBuffer contains valid data after mixing. 1256 bool mMixerBufferValid GUARDED_BY(ThreadBase_ThreadLoop); 1257 1258 // Effects Buffer (mEffectsBuffer*) 1259 // 1260 // In the case of effects data, which is not in the sink format, 1261 // it is required to accumulate in a different buffer before data conversion 1262 // to the sink buffer. 1263 1264 // Set to "true" to enable the Effects Buffer otherwise effects output goes to sink buffer. 1265 bool mEffectBufferEnabled; 1266 // NO_THREAD_SAFETY_ANALYSIS: Spatializer access this in addEffectChain_l() 1267 1268 // Storage, 32 byte aligned (may make this alignment a requirement later). 1269 // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames. 1270 void* mEffectBuffer; 1271 // NO_THREAD_SAFETY_ANALYSIS: Spatializer access this in addEffectChain_l() 1272 1273 // Size of mEffectsBuffer in bytes: mNormalFrameCount * #channels * sampsize. 1274 size_t mEffectBufferSize; 1275 // NO_THREAD_SAFETY_ANALYSIS: Spatializer access this in addEffectChain_l() 1276 1277 // The audio format of mEffectsBuffer. Set to AUDIO_FORMAT_PCM_16_BIT only. 1278 // NO_THREAD_SAFETY_ANALYSIS: Spatializer access this in addEffectChain_l() 1279 audio_format_t mEffectBufferFormat; 1280 1281 // An internal flag set to true by MixerThread::prepareTracks_l() 1282 // when mEffectsBuffer contains valid data after mixing. 1283 // 1284 // When this is set, all mixer data is routed into the effects buffer 1285 // for any processing (including output processing). 1286 bool mEffectBufferValid GUARDED_BY(ThreadBase_ThreadLoop); 1287 1288 // Set to "true" to enable when data has already copied to sink 1289 bool mHasDataCopiedToSinkBuffer GUARDED_BY(ThreadBase_ThreadLoop) = false; 1290 1291 // Frame size aligned buffer used as input and output to all post processing effects 1292 // except the Spatializer in a SPATIALIZER thread. Non spatialized tracks are mixed into 1293 // this buffer so that post processing effects can be applied. 1294 void* mPostSpatializerBuffer GUARDED_BY(mutex()) = nullptr; 1295 1296 // Size of mPostSpatializerBuffer in bytes 1297 size_t mPostSpatializerBufferSize GUARDED_BY(mutex()); 1298 1299 // suspend count, > 0 means suspended. While suspended, the thread continues to pull from 1300 // tracks and mix, but doesn't write to HAL. A2DP and SCO HAL implementations can't handle 1301 // concurrent use of both of them, so Audio Policy Service suspends one of the threads to 1302 // workaround that restriction. 1303 // 'volatile' means accessed via atomic operations and no lock. 1304 std::atomic<int32_t> mSuspended; 1305 1306 int64_t mBytesWritten; 1307 std::atomic<int64_t> mFramesWritten; // not reset on standby 1308 int64_t mLastFramesWritten = -1; // track changes in timestamp 1309 // server frames written. 1310 int64_t mSuspendedFrames; // not reset on standby 1311 1312 // mHapticChannelMask and mHapticChannelCount will only be valid when the thread support 1313 // haptic playback. 1314 audio_channel_mask_t mHapticChannelMask = AUDIO_CHANNEL_NONE; 1315 uint32_t mHapticChannelCount = 0; 1316 1317 audio_channel_mask_t mMixerChannelMask = AUDIO_CHANNEL_NONE; 1318 1319 // mMasterMute is in both PlaybackThread and in AudioFlinger. When a 1320 // PlaybackThread needs to find out if master-muted, it checks it's local 1321 // copy rather than the one in AudioFlinger. This optimization saves a lock. 1322 bool mMasterMute GUARDED_BY(mutex()); setMasterMute_l(bool muted)1323 void setMasterMute_l(bool muted) REQUIRES(mutex()) { mMasterMute = muted; } 1324 discontinuityForStandbyOrFlush()1325 auto discontinuityForStandbyOrFlush() const { // call on threadLoop or with lock. 1326 return ((mType == DIRECT && !audio_is_linear_pcm(mFormat)) 1327 || mType == OFFLOAD) 1328 ? mTimestampVerifier.DISCONTINUITY_MODE_ZERO 1329 : mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS; 1330 } 1331 1332 ActiveTracks<IAfTrack> mActiveTracks; 1333 1334 // Time to sleep between cycles when: 1335 virtual uint32_t activeSleepTimeUs() const; // mixer state MIXER_TRACKS_ENABLED 1336 virtual uint32_t idleSleepTimeUs() const = 0; // mixer state MIXER_IDLE 1337 virtual uint32_t suspendSleepTimeUs() const = 0; // audio policy manager suspended us 1338 // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write() 1339 // No sleep in standby mode; waits on a condition 1340 1341 // Code snippets that are temporarily lifted up out of threadLoop() until the merge 1342 1343 // consider unification with MMapThread 1344 virtual void checkSilentMode_l() final REQUIRES(mutex()); 1345 1346 // Non-trivial for DUPLICATING only saveOutputTracks()1347 virtual void saveOutputTracks() REQUIRES(ThreadBase_ThreadLoop) {} clearOutputTracks()1348 virtual void clearOutputTracks() REQUIRES(ThreadBase_ThreadLoop) {} 1349 1350 // Cache various calculated values, at threadLoop() entry and after a parameter change 1351 virtual void cacheParameters_l() REQUIRES(mutex(), ThreadBase_ThreadLoop); setCheckOutputStageEffects()1352 void setCheckOutputStageEffects() override { 1353 mCheckOutputStageEffects.store(true); 1354 } 1355 1356 virtual uint32_t correctLatency_l(uint32_t latency) const REQUIRES(mutex()); 1357 1358 virtual status_t createAudioPatch_l(const struct audio_patch *patch, 1359 audio_patch_handle_t *handle) REQUIRES(mutex()); 1360 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle) 1361 REQUIRES(mutex()); 1362 1363 // NO_THREAD_SAFETY_ANALYSIS - fix this to use atomics usesHwAvSync()1364 bool usesHwAvSync() const final { return mType == DIRECT && mOutput != nullptr 1365 && mHwSupportsPause 1366 && (mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC); } 1367 1368 uint32_t trackCountForUid_l(uid_t uid) const; 1369 invalidateTracksForAudioSession_l(audio_session_t sessionId)1370 void invalidateTracksForAudioSession_l( 1371 audio_session_t sessionId) const override REQUIRES(mutex()) { 1372 ThreadBase::invalidateTracksForAudioSession_l(sessionId, mTracks); 1373 } 1374 1375 DISALLOW_COPY_AND_ASSIGN(PlaybackThread); 1376 1377 status_t addTrack_l(const sp<IAfTrack>& track) final REQUIRES(mutex()); 1378 bool destroyTrack_l(const sp<IAfTrack>& track) final REQUIRES(mutex()); 1379 1380 void removeTrack_l(const sp<IAfTrack>& track) REQUIRES(mutex()); 1381 std::set<audio_port_handle_t> getTrackPortIds_l() REQUIRES(mutex()); 1382 std::set<audio_port_handle_t> getTrackPortIds(); 1383 1384 void readOutputParameters_l() REQUIRES(mutex()); 1385 MetadataUpdate updateMetadata_l() final REQUIRES(mutex()); 1386 virtual void sendMetadataToBackend_l(const StreamOutHalInterface::SourceMetadata& metadata) 1387 REQUIRES(mutex()) ; 1388 1389 void collectTimestamps_l() REQUIRES(mutex(), ThreadBase_ThreadLoop); 1390 1391 // The Tracks class manages tracks added and removed from the Thread. 1392 template <typename T> 1393 class Tracks { 1394 public: Tracks(bool saveDeletedTrackIds)1395 explicit Tracks(bool saveDeletedTrackIds) : 1396 mSaveDeletedTrackIds(saveDeletedTrackIds) { } 1397 1398 // SortedVector methods add(const sp<T> & track)1399 ssize_t add(const sp<T> &track) { 1400 const ssize_t index = mTracks.add(track); 1401 LOG_ALWAYS_FATAL_IF(index < 0, "cannot add track"); 1402 return index; 1403 } 1404 ssize_t remove(const sp<T> &track); size()1405 size_t size() const { 1406 return mTracks.size(); 1407 } isEmpty()1408 bool isEmpty() const { 1409 return mTracks.isEmpty(); 1410 } indexOf(const sp<T> & item)1411 ssize_t indexOf(const sp<T> &item) { 1412 return mTracks.indexOf(item); 1413 } 1414 sp<T> operator[](size_t index) const { 1415 return mTracks[index]; 1416 } begin()1417 typename SortedVector<sp<T>>::iterator begin() { 1418 return mTracks.begin(); 1419 } end()1420 typename SortedVector<sp<T>>::iterator end() { 1421 return mTracks.end(); 1422 } 1423 processDeletedTrackIds(const std::function<void (int)> & f)1424 size_t processDeletedTrackIds(const std::function<void(int)>& f) { 1425 for (const int trackId : mDeletedTrackIds) { 1426 f(trackId); 1427 } 1428 return mDeletedTrackIds.size(); 1429 } 1430 clearDeletedTrackIds()1431 void clearDeletedTrackIds() { mDeletedTrackIds.clear(); } 1432 1433 private: 1434 // Tracks pending deletion for MIXER type threads 1435 const bool mSaveDeletedTrackIds; // true to enable tracking 1436 std::set<int> mDeletedTrackIds; 1437 1438 SortedVector<sp<T>> mTracks; // wrapped SortedVector. 1439 }; 1440 1441 Tracks<IAfTrack> mTracks; 1442 1443 stream_type_t mStreamTypes[AUDIO_STREAM_CNT]; 1444 1445 AudioStreamOut *mOutput; 1446 1447 float mMasterVolume; 1448 std::atomic<float> mMasterBalance{}; 1449 audio_utils::Balance mBalance; 1450 int mNumWrites; 1451 int mNumDelayedWrites; 1452 bool mInWrite; 1453 1454 // FIXME rename these former local variables of threadLoop to standard "m" names 1455 nsecs_t mStandbyTimeNs; 1456 size_t mSinkBufferSize; 1457 1458 // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l() 1459 uint32_t mActiveSleepTimeUs; 1460 uint32_t mIdleSleepTimeUs; 1461 1462 uint32_t mSleepTimeUs; 1463 1464 // mixer status returned by prepareTracks_l() 1465 mixer_state mMixerStatus GUARDED_BY(ThreadBase_ThreadLoop); // current cycle 1466 // previous cycle when in prepareTracks_l() 1467 mixer_state mMixerStatusIgnoringFastTracks GUARDED_BY(ThreadBase_ThreadLoop); 1468 // FIXME or a separate ready state per track 1469 1470 // FIXME move these declarations into the specific sub-class that needs them 1471 // MIXER only 1472 uint32_t sleepTimeShift GUARDED_BY(ThreadBase_ThreadLoop); 1473 1474 // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value 1475 nsecs_t mStandbyDelayNs; // GUARDED_BY(mutex()); 1476 1477 // MIXER only 1478 nsecs_t maxPeriod; 1479 1480 // DUPLICATING only 1481 uint32_t writeFrames; 1482 1483 size_t mBytesRemaining GUARDED_BY(ThreadBase_ThreadLoop); 1484 size_t mCurrentWriteLength GUARDED_BY(ThreadBase_ThreadLoop); 1485 bool mUseAsyncWrite; 1486 // mWriteAckSequence contains current write sequence on bits 31-1. The write sequence is 1487 // incremented each time a write(), a flush() or a standby() occurs. 1488 // Bit 0 is set when a write blocks and indicates a callback is expected. 1489 // Bit 0 is reset by the async callback thread calling resetWriteBlocked(). Out of sequence 1490 // callbacks are ignored. 1491 uint32_t mWriteAckSequence; 1492 // mDrainSequence contains current drain sequence on bits 31-1. The drain sequence is 1493 // incremented each time a drain is requested or a flush() or standby() occurs. 1494 // Bit 0 is set when the drain() command is called at the HAL and indicates a callback is 1495 // expected. 1496 // Bit 0 is reset by the async callback thread calling resetDraining(). Out of sequence 1497 // callbacks are ignored. 1498 uint32_t mDrainSequence; 1499 1500 sp<AsyncCallbackThread> mCallbackThread; 1501 audioTrackCbMutex()1502 audio_utils::mutex& audioTrackCbMutex() const { return mAudioTrackCbMutex; } 1503 mutable audio_utils::mutex mAudioTrackCbMutex{ 1504 audio_utils::MutexOrder::kPlaybackThread_AudioTrackCbMutex}; 1505 // Record of IAudioTrackCallback 1506 std::map<sp<IAfTrack>, sp<media::IAudioTrackCallback>> mAudioTrackCallbacks; 1507 1508 // The HAL output sink is treated as non-blocking, but current implementation is blocking 1509 sp<NBAIO_Sink> mOutputSink; 1510 // If a fast mixer is present, the blocking pipe sink, otherwise clear 1511 sp<NBAIO_Sink> mPipeSink; 1512 // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink 1513 sp<NBAIO_Sink> mNormalSink; 1514 1515 uint32_t mScreenState; // cached copy of gScreenState 1516 // TODO: add comment and adjust size as needed 1517 static const size_t kFastMixerLogSize = 8 * 1024; 1518 sp<NBLog::Writer> mFastMixerNBLogWriter; 1519 1520 // Downstream patch latency, available if mDownstreamLatencyStatMs.getN() > 0. 1521 audio_utils::Statistics<double> mDownstreamLatencyStatMs{0.999}; 1522 1523 // output stream start detection based on render position returned by the kernel 1524 // condition signalled when the output stream has started 1525 audio_utils::condition_variable mWaitHalStartCV; 1526 // true when the output stream render position has moved, reset to false in standby 1527 bool mHalStarted = false; 1528 // last kernel render position saved when entering standby 1529 int64_t mKernelPositionOnStandby = 0; 1530 1531 public: getFastTrackUnderruns(size_t)1532 FastTrackUnderruns getFastTrackUnderruns(size_t /* fastIndex */) const override 1533 { return {}; } framesWritten()1534 const std::atomic<int64_t>& framesWritten() const final { return mFramesWritten; } 1535 1536 protected: 1537 // accessed by both binder threads and within threadLoop(), lock on mutex needed fastTrackAvailMask_l()1538 uint32_t& fastTrackAvailMask_l() final REQUIRES(mutex()) { return mFastTrackAvailMask; } 1539 uint32_t mFastTrackAvailMask; // bit i set if fast track [i] is available 1540 bool mHwSupportsPause; 1541 bool mHwPaused; 1542 bool mFlushPending; 1543 // volumes last sent to audio HAL with stream->setVolume() 1544 float mLeftVolFloat; 1545 float mRightVolFloat; 1546 1547 // audio patch used by the downstream software patch. 1548 // Only used if ThreadBase::mIsMsdDevice is true. 1549 struct audio_patch mDownStreamPatch; 1550 1551 std::atomic_bool mCheckOutputStageEffects{}; 1552 1553 1554 // Provides periodic checking for timestamp advancement for underrun detection. 1555 class IsTimestampAdvancing { 1556 public: 1557 // The timestamp will not be checked any faster than the specified time. IsTimestampAdvancing(nsecs_t minimumTimeBetweenChecksNs)1558 explicit IsTimestampAdvancing(nsecs_t minimumTimeBetweenChecksNs) 1559 : mMinimumTimeBetweenChecksNs(minimumTimeBetweenChecksNs) 1560 { 1561 clear(); 1562 } 1563 // Check if the presentation position has advanced in the last periodic time. 1564 bool check(AudioStreamOut * output); 1565 // Clear the internal state when the playback state changes for the output 1566 // stream. 1567 void clear(); 1568 private: 1569 // The minimum time between timestamp checks. 1570 const nsecs_t mMinimumTimeBetweenChecksNs; 1571 // Add differential check on the timestamps to see if there is a change in the 1572 // timestamp frame position between the last call to check. 1573 uint64_t mPreviousPosition; 1574 // The time at which the last check occurred, to ensure we don't check too 1575 // frequently, giving the Audio HAL enough time to update its timestamps. 1576 nsecs_t mPreviousNs; 1577 // The valued is latched so we don't check timestamps too frequently. 1578 bool mLatchedValue; 1579 }; 1580 IsTimestampAdvancing mIsTimestampAdvancing; 1581 flushHw_l()1582 virtual void flushHw_l() { 1583 mIsTimestampAdvancing.clear(); 1584 } 1585 }; 1586 1587 class MixerThread : public PlaybackThread, 1588 public StreamOutHalInterfaceLatencyModeCallback { 1589 public: 1590 MixerThread(const sp<IAfThreadCallback>& afThreadCallback, 1591 AudioStreamOut* output, 1592 audio_io_handle_t id, 1593 bool systemReady, 1594 type_t type = MIXER, 1595 audio_config_base_t *mixerConfig = nullptr); 1596 ~MixerThread() override; 1597 1598 // RefBase 1599 void onFirstRef() override; 1600 1601 // StreamOutHalInterfaceLatencyModeCallback 1602 void onRecommendedLatencyModeChanged( 1603 std::vector<audio_latency_mode_t> modes) final; 1604 1605 // Thread virtuals 1606 1607 bool checkForNewParameter_l(const String8& keyValuePair, status_t& status) final 1608 REQUIRES(mutex()); 1609 1610 bool isTrackAllowed_l( 1611 audio_channel_mask_t channelMask, audio_format_t format, 1612 audio_session_t sessionId, uid_t uid) const final REQUIRES(mutex()); 1613 protected: 1614 mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove) override 1615 REQUIRES(mutex(), ThreadBase_ThreadLoop); 1616 uint32_t idleSleepTimeUs() const final; 1617 uint32_t suspendSleepTimeUs() const final; 1618 void cacheParameters_l() override REQUIRES(mutex(), ThreadBase_ThreadLoop); 1619 acquireWakeLock_l()1620 void acquireWakeLock_l() final REQUIRES(mutex()) { 1621 PlaybackThread::acquireWakeLock_l(); 1622 if (hasFastMixer()) { 1623 mFastMixer->setBoottimeOffset( 1624 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME]); 1625 } 1626 } 1627 1628 void dumpInternals_l(int fd, const Vector<String16>& args) override REQUIRES(mutex()); 1629 1630 // threadLoop snippets 1631 ssize_t threadLoop_write() override REQUIRES(ThreadBase_ThreadLoop); 1632 void threadLoop_standby() override REQUIRES(ThreadBase_ThreadLoop); 1633 void threadLoop_mix() override REQUIRES(ThreadBase_ThreadLoop); 1634 void threadLoop_sleepTime() override REQUIRES(ThreadBase_ThreadLoop); 1635 uint32_t correctLatency_l(uint32_t latency) const final REQUIRES(mutex()); 1636 1637 status_t createAudioPatch_l( 1638 const struct audio_patch* patch, audio_patch_handle_t* handle) 1639 final REQUIRES(mutex()); 1640 status_t releaseAudioPatch_l(const audio_patch_handle_t handle) final REQUIRES(mutex()); 1641 1642 AudioMixer* mAudioMixer; // normal mixer 1643 1644 // Support low latency mode by default as unless explicitly indicated by the audio HAL 1645 // we assume the audio path is compatible with the head tracking latency requirements 1646 std::vector<audio_latency_mode_t> mSupportedLatencyModes = {AUDIO_LATENCY_MODE_LOW}; 1647 // default to invalid value to force first update to the audio HAL 1648 audio_latency_mode_t mSetLatencyMode = 1649 (audio_latency_mode_t)AUDIO_LATENCY_MODE_INVALID; 1650 1651 // Bluetooth Variable latency control logic is enabled or disabled for this thread 1652 std::atomic_bool mBluetoothLatencyModesEnabled; 1653 1654 private: 1655 // one-time initialization, no locks required 1656 sp<FastMixer> mFastMixer; // non-0 if there is also a fast mixer 1657 sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread 1658 1659 // contents are not guaranteed to be consistent, no locks required 1660 FastMixerDumpState mFastMixerDumpState; 1661 #ifdef STATE_QUEUE_DUMP 1662 StateQueueObserverDump mStateQueueObserverDump; 1663 StateQueueMutatorDump mStateQueueMutatorDump; 1664 #endif 1665 AudioWatchdogDump mAudioWatchdogDump; 1666 1667 // accessible only within the threadLoop(), no locks required 1668 // mFastMixer->sq() // for mutating and pushing state 1669 int32_t mFastMixerFutex GUARDED_BY(ThreadBase_ThreadLoop); // for cold idle 1670 1671 std::atomic_bool mMasterMono; 1672 public: hasFastMixer()1673 virtual bool hasFastMixer() const { return mFastMixer != 0; } getFastTrackUnderruns(size_t fastIndex)1674 virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const { 1675 ALOG_ASSERT(fastIndex < FastMixerState::sMaxFastTracks); 1676 return mFastMixerDumpState.mTracks[fastIndex].mUnderruns; 1677 } 1678 threadloop_getHalTimestamp_l(ExtendedTimestamp * timestamp)1679 status_t threadloop_getHalTimestamp_l( 1680 ExtendedTimestamp *timestamp) const override 1681 REQUIRES(mutex(), ThreadBase_ThreadLoop) { 1682 if (mNormalSink.get() != nullptr) { 1683 return mNormalSink->getTimestamp(*timestamp); 1684 } 1685 return INVALID_OPERATION; 1686 } 1687 1688 status_t getSupportedLatencyModes( 1689 std::vector<audio_latency_mode_t>* modes) override; 1690 1691 status_t setBluetoothVariableLatencyEnabled(bool enabled) override; 1692 1693 protected: setMasterMono_l(bool mono)1694 virtual void setMasterMono_l(bool mono) { 1695 mMasterMono.store(mono); 1696 if (mFastMixer != nullptr) { /* hasFastMixer() */ 1697 mFastMixer->setMasterMono(mMasterMono); 1698 } 1699 } 1700 // the FastMixer performs mono blend if it exists. 1701 // Blending with limiter is not idempotent, 1702 // and blending without limiter is idempotent but inefficient to do twice. requireMonoBlend()1703 virtual bool requireMonoBlend() { return mMasterMono.load() && !hasFastMixer(); } 1704 setMasterBalance(float balance)1705 void setMasterBalance(float balance) override EXCLUDES_ThreadBase_Mutex { 1706 mMasterBalance.store(balance); 1707 if (hasFastMixer()) { 1708 mFastMixer->setMasterBalance(balance); 1709 } 1710 } 1711 1712 void updateHalSupportedLatencyModes_l() REQUIRES(mutex()); 1713 void onHalLatencyModesChanged_l() override REQUIRES(mutex()); 1714 void setHalLatencyMode_l() override REQUIRES(mutex()); 1715 }; 1716 1717 class DirectOutputThread : public PlaybackThread, public virtual IAfDirectOutputThread { 1718 public: 1719 asIAfDirectOutputThread()1720 sp<IAfDirectOutputThread> asIAfDirectOutputThread() final { 1721 return sp<IAfDirectOutputThread>::fromExisting(this); 1722 } 1723 DirectOutputThread(const sp<IAfThreadCallback> & afThreadCallback,AudioStreamOut * output,audio_io_handle_t id,bool systemReady,const audio_offload_info_t & offloadInfo)1724 DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output, 1725 audio_io_handle_t id, bool systemReady, 1726 const audio_offload_info_t& offloadInfo) 1727 : DirectOutputThread(afThreadCallback, output, id, DIRECT, systemReady, offloadInfo) { } 1728 1729 ~DirectOutputThread() override; 1730 1731 status_t selectPresentation(int presentationId, int programId) final; 1732 1733 // Thread virtuals 1734 1735 virtual bool checkForNewParameter_l(const String8& keyValuePair, 1736 status_t& status) REQUIRES(mutex()); 1737 1738 void flushHw_l() override REQUIRES(mutex(), ThreadBase_ThreadLoop); 1739 1740 void setMasterBalance(float balance) override EXCLUDES_ThreadBase_Mutex; 1741 1742 protected: 1743 virtual uint32_t activeSleepTimeUs() const; 1744 virtual uint32_t idleSleepTimeUs() const; 1745 virtual uint32_t suspendSleepTimeUs() const; 1746 virtual void cacheParameters_l() REQUIRES(mutex(), ThreadBase_ThreadLoop); 1747 1748 void dumpInternals_l(int fd, const Vector<String16>& args) override REQUIRES(mutex()); 1749 1750 // threadLoop snippets 1751 virtual mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove) 1752 REQUIRES(mutex(), ThreadBase_ThreadLoop); 1753 virtual void threadLoop_mix() REQUIRES(ThreadBase_ThreadLoop); 1754 virtual void threadLoop_sleepTime() REQUIRES(ThreadBase_ThreadLoop); 1755 virtual void threadLoop_exit() REQUIRES(ThreadBase_ThreadLoop); 1756 virtual bool shouldStandby_l() REQUIRES(mutex()); 1757 1758 virtual void onAddNewTrack_l() REQUIRES(mutex()); 1759 1760 const audio_offload_info_t mOffloadInfo; 1761 1762 audioflinger::MonotonicFrameCounter mMonotonicFrameCounter; // for VolumeShaper 1763 bool mVolumeShaperActive = false; 1764 1765 DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output, 1766 audio_io_handle_t id, ThreadBase::type_t type, bool systemReady, 1767 const audio_offload_info_t& offloadInfo); 1768 void processVolume_l(IAfTrack *track, bool lastTrack) REQUIRES(mutex()); isTunerStream()1769 bool isTunerStream() const { return (mOffloadInfo.content_id > 0); } 1770 1771 // prepareTracks_l() tells threadLoop_mix() the name of the single active track 1772 sp<IAfTrack> mActiveTrack; 1773 1774 wp<IAfTrack> mPreviousTrack; // used to detect track switch 1775 1776 // This must be initialized for initial condition of mMasterBalance = 0 (disabled). 1777 float mMasterBalanceLeft = 1.f; 1778 float mMasterBalanceRight = 1.f; 1779 1780 public: hasFastMixer()1781 virtual bool hasFastMixer() const { return false; } 1782 1783 virtual int64_t computeWaitTimeNs_l() const override REQUIRES(mutex()); 1784 threadloop_getHalTimestamp_l(ExtendedTimestamp * timestamp)1785 status_t threadloop_getHalTimestamp_l(ExtendedTimestamp *timestamp) const override { 1786 // For DIRECT and OFFLOAD threads, query the output sink directly. 1787 if (mOutput != nullptr) { 1788 uint64_t uposition64; 1789 struct timespec time; 1790 if (mOutput->getPresentationPosition( 1791 &uposition64, &time) == OK) { 1792 timestamp->mPosition[ExtendedTimestamp::LOCATION_KERNEL] 1793 = (int64_t)uposition64; 1794 timestamp->mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] 1795 = audio_utils_ns_from_timespec(&time); 1796 return NO_ERROR; 1797 } 1798 } 1799 return INVALID_OPERATION; 1800 } 1801 }; 1802 1803 class OffloadThread : public DirectOutputThread { 1804 public: 1805 1806 OffloadThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output, 1807 audio_io_handle_t id, bool systemReady, 1808 const audio_offload_info_t& offloadInfo); ~OffloadThread()1809 virtual ~OffloadThread() {}; 1810 void flushHw_l() final REQUIRES(mutex(), ThreadBase_ThreadLoop); 1811 1812 protected: 1813 // threadLoop snippets 1814 mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove) final 1815 REQUIRES(mutex(), ThreadBase_ThreadLoop); 1816 void threadLoop_exit() final REQUIRES(ThreadBase_ThreadLoop); 1817 1818 bool waitingAsyncCallback() final; 1819 bool waitingAsyncCallback_l() final REQUIRES(mutex()); 1820 void invalidateTracks(audio_stream_type_t streamType) final EXCLUDES_ThreadBase_Mutex; 1821 void invalidateTracks(std::set<audio_port_handle_t>& portIds) final EXCLUDES_ThreadBase_Mutex; 1822 keepWakeLock()1823 bool keepWakeLock() const final { return (mKeepWakeLock || (mDrainSequence & 1)); } 1824 1825 private: 1826 size_t mPausedWriteLength; // length in bytes of write interrupted by pause 1827 size_t mPausedBytesRemaining; // bytes still waiting in mixbuffer after resume 1828 bool mKeepWakeLock; // keep wake lock while waiting for write callback 1829 }; 1830 1831 class AsyncCallbackThread : public Thread { 1832 public: 1833 explicit AsyncCallbackThread(const wp<PlaybackThread>& playbackThread); 1834 1835 // Thread virtuals 1836 bool threadLoop() final; 1837 1838 // RefBase 1839 void onFirstRef() final; 1840 1841 void exit(); 1842 void setWriteBlocked(uint32_t sequence); 1843 void resetWriteBlocked(); 1844 void setDraining(uint32_t sequence); 1845 void resetDraining(); 1846 void setAsyncError(bool isHardError); 1847 1848 private: 1849 const wp<PlaybackThread> mPlaybackThread; 1850 // mWriteAckSequence corresponds to the last write sequence passed by the offload thread via 1851 // setWriteBlocked(). The sequence is shifted one bit to the left and the lsb is used 1852 // to indicate that the callback has been received via resetWriteBlocked() 1853 uint32_t mWriteAckSequence; 1854 // mDrainSequence corresponds to the last drain sequence passed by the offload thread via 1855 // setDraining(). The sequence is shifted one bit to the left and the lsb is used 1856 // to indicate that the callback has been received via resetDraining() 1857 uint32_t mDrainSequence; 1858 audio_utils::condition_variable mWaitWorkCV; 1859 mutable audio_utils::mutex mMutex{audio_utils::MutexOrder::kAsyncCallbackThread_Mutex}; 1860 enum AsyncError { ASYNC_ERROR_NONE, ASYNC_ERROR_SOFT, ASYNC_ERROR_HARD }; 1861 AsyncError mAsyncError; 1862 mutex()1863 audio_utils::mutex& mutex() const RETURN_CAPABILITY(audio_utils::AsyncCallbackThread_Mutex) { 1864 return mMutex; 1865 } 1866 }; 1867 1868 class DuplicatingThread : public MixerThread, public IAfDuplicatingThread { 1869 public: 1870 DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback, 1871 IAfPlaybackThread* mainThread, 1872 audio_io_handle_t id, bool systemReady); 1873 ~DuplicatingThread() override; 1874 asIAfDuplicatingThread()1875 sp<IAfDuplicatingThread> asIAfDuplicatingThread() final { 1876 return sp<IAfDuplicatingThread>::fromExisting(this); 1877 } 1878 1879 // Thread virtuals 1880 void addOutputTrack(IAfPlaybackThread* thread) final EXCLUDES_ThreadBase_Mutex; 1881 void removeOutputTrack(IAfPlaybackThread* thread) final EXCLUDES_ThreadBase_Mutex; waitTimeMs()1882 uint32_t waitTimeMs() const final { return mWaitTimeMs; } 1883 1884 void sendMetadataToBackend_l( 1885 const StreamOutHalInterface::SourceMetadata& metadata) final REQUIRES(mutex()); 1886 protected: 1887 virtual uint32_t activeSleepTimeUs() const; 1888 void dumpInternals_l(int fd, const Vector<String16>& args) final REQUIRES(mutex()); 1889 1890 private: 1891 bool outputsReady() REQUIRES(ThreadBase_ThreadLoop); 1892 protected: 1893 // threadLoop snippets 1894 void threadLoop_mix() final REQUIRES(ThreadBase_ThreadLoop); 1895 void threadLoop_sleepTime() final REQUIRES(ThreadBase_ThreadLoop); 1896 ssize_t threadLoop_write() final REQUIRES(ThreadBase_ThreadLoop); 1897 void threadLoop_standby() final REQUIRES(ThreadBase_ThreadLoop); 1898 void threadLoop_exit() final REQUIRES(ThreadBase_ThreadLoop); 1899 void cacheParameters_l() final REQUIRES(mutex(), ThreadBase_ThreadLoop); 1900 1901 private: 1902 // called from threadLoop, addOutputTrack, removeOutputTrack 1903 void updateWaitTime_l() REQUIRES(mutex()); 1904 protected: 1905 void saveOutputTracks() final REQUIRES(mutex(), ThreadBase_ThreadLoop); 1906 void clearOutputTracks() final REQUIRES(mutex(), ThreadBase_ThreadLoop); 1907 private: 1908 1909 uint32_t mWaitTimeMs; 1910 // NO_THREAD_SAFETY_ANALYSIS GUARDED_BY(ThreadBase_ThreadLoop) 1911 SortedVector <sp<IAfOutputTrack>> outputTracks; 1912 SortedVector <sp<IAfOutputTrack>> mOutputTracks GUARDED_BY(mutex()); 1913 public: hasFastMixer()1914 virtual bool hasFastMixer() const { return false; } threadloop_getHalTimestamp_l(ExtendedTimestamp * timestamp)1915 status_t threadloop_getHalTimestamp_l( 1916 ExtendedTimestamp *timestamp) const override REQUIRES(mutex()) { 1917 if (mOutputTracks.size() > 0) { 1918 // forward the first OutputTrack's kernel information for timestamp. 1919 const ExtendedTimestamp trackTimestamp = 1920 mOutputTracks[0]->getClientProxyTimestamp(); 1921 if (trackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] > 0) { 1922 timestamp->mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = 1923 trackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]; 1924 timestamp->mPosition[ExtendedTimestamp::LOCATION_KERNEL] = 1925 trackTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]; 1926 return OK; // discard server timestamp - that's ignored. 1927 } 1928 } 1929 return INVALID_OPERATION; 1930 } 1931 }; 1932 1933 class SpatializerThread : public MixerThread { 1934 public: 1935 SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback, 1936 AudioStreamOut* output, 1937 audio_io_handle_t id, 1938 bool systemReady, 1939 audio_config_base_t *mixerConfig); 1940 hasFastMixer()1941 bool hasFastMixer() const final { return false; } 1942 1943 status_t setRequestedLatencyMode(audio_latency_mode_t mode) final EXCLUDES_ThreadBase_Mutex; 1944 1945 protected: 1946 void checkOutputStageEffects() final 1947 REQUIRES(ThreadBase_ThreadLoop) EXCLUDES_ThreadBase_Mutex; 1948 void setHalLatencyMode_l() final REQUIRES(mutex()); 1949 1950 void threadLoop_exit() final REQUIRES(ThreadBase_ThreadLoop); 1951 1952 private: 1953 // Do not request a specific mode by default 1954 audio_latency_mode_t mRequestedLatencyMode = AUDIO_LATENCY_MODE_FREE; 1955 1956 sp<IAfEffectHandle> mFinalDownMixer; 1957 }; 1958 1959 // record thread 1960 class RecordThread : public IAfRecordThread, public ThreadBase 1961 { 1962 friend class ResamplerBufferProvider; 1963 public: asIAfRecordThread()1964 sp<IAfRecordThread> asIAfRecordThread() final { 1965 return sp<IAfRecordThread>::fromExisting(this); 1966 } 1967 1968 RecordThread(const sp<IAfThreadCallback>& afThreadCallback, 1969 AudioStreamIn *input, 1970 audio_io_handle_t id, 1971 bool systemReady 1972 ); 1973 ~RecordThread() override; 1974 1975 // no addTrack_l ? 1976 void destroyTrack_l(const sp<IAfRecordTrack>& track) final REQUIRES(mutex()); 1977 void removeTrack_l(const sp<IAfRecordTrack>& track) final REQUIRES(mutex()); 1978 1979 // Thread virtuals 1980 bool threadLoop() final REQUIRES(ThreadBase_ThreadLoop) EXCLUDES_ThreadBase_Mutex; 1981 void preExit() final EXCLUDES_ThreadBase_Mutex; 1982 1983 // RefBase 1984 void onFirstRef() final EXCLUDES_ThreadBase_Mutex; 1985 initCheck()1986 status_t initCheck() const final { return mInput == nullptr ? NO_INIT : NO_ERROR; } 1987 readOnlyHeap()1988 sp<MemoryDealer> readOnlyHeap() const final { return mReadOnlyHeap; } 1989 pipeMemory()1990 sp<IMemory> pipeMemory() const final { return mPipeMemory; } 1991 1992 sp<IAfRecordTrack> createRecordTrack_l( 1993 const sp<Client>& client, 1994 const audio_attributes_t& attr, 1995 uint32_t *pSampleRate, 1996 audio_format_t format, 1997 audio_channel_mask_t channelMask, 1998 size_t *pFrameCount, 1999 audio_session_t sessionId, 2000 size_t *pNotificationFrameCount, 2001 pid_t creatorPid, 2002 const AttributionSourceState& attributionSource, 2003 audio_input_flags_t *flags, 2004 pid_t tid, 2005 status_t *status /*non-NULL*/, 2006 audio_port_handle_t portId, 2007 int32_t maxSharedAudioHistoryMs) final 2008 REQUIRES(audio_utils::AudioFlinger_Mutex) EXCLUDES_ThreadBase_Mutex; 2009 2010 status_t start(IAfRecordTrack* recordTrack, 2011 AudioSystem::sync_event_t event, 2012 audio_session_t triggerSession) final EXCLUDES_ThreadBase_Mutex; 2013 2014 // ask the thread to stop the specified track, and 2015 // return true if the caller should then do it's part of the stopping process 2016 bool stop(IAfRecordTrack* recordTrack) final EXCLUDES_ThreadBase_Mutex; getInput()2017 AudioStreamIn* getInput() const final { return mInput; } 2018 AudioStreamIn* clearInput() final; 2019 2020 // TODO(b/291317898) Unify with IAfThreadBase 2021 virtual sp<StreamHalInterface> stream() const; 2022 2023 2024 virtual bool checkForNewParameter_l(const String8& keyValuePair, 2025 status_t& status) REQUIRES(mutex()); cacheParameters_l()2026 virtual void cacheParameters_l() REQUIRES(mutex(), ThreadBase_ThreadLoop) {} 2027 virtual String8 getParameters(const String8& keys) EXCLUDES_ThreadBase_Mutex; 2028 2029 // Hold either the AudioFlinger::mutex or the ThreadBase::mutex 2030 void ioConfigChanged_l(audio_io_config_event_t event, pid_t pid = 0, 2031 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final; 2032 virtual status_t createAudioPatch_l(const struct audio_patch *patch, 2033 audio_patch_handle_t *handle) REQUIRES(mutex()); 2034 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle) REQUIRES(mutex()); 2035 void updateOutDevices(const DeviceDescriptorBaseVector& outDevices) override 2036 EXCLUDES_ThreadBase_Mutex; 2037 void resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs) override REQUIRES(mutex()); 2038 2039 void addPatchTrack(const sp<IAfPatchRecord>& record) final EXCLUDES_ThreadBase_Mutex; 2040 void deletePatchTrack(const sp<IAfPatchRecord>& record) final EXCLUDES_ThreadBase_Mutex; 2041 2042 void readInputParameters_l() REQUIRES(mutex()); 2043 uint32_t getInputFramesLost() const final EXCLUDES_ThreadBase_Mutex; 2044 2045 virtual status_t addEffectChain_l(const sp<IAfEffectChain>& chain) REQUIRES(mutex()); 2046 virtual size_t removeEffectChain_l(const sp<IAfEffectChain>& chain) REQUIRES(mutex()); hasAudioSession_l(audio_session_t sessionId)2047 uint32_t hasAudioSession_l(audio_session_t sessionId) const override REQUIRES(mutex()) { 2048 return ThreadBase::hasAudioSession_l(sessionId, mTracks); 2049 } 2050 2051 // Return the set of unique session IDs across all tracks. 2052 // The keys are the session IDs, and the associated values are meaningless. 2053 // FIXME replace by Set [and implement Bag/Multiset for other uses]. 2054 KeyedVector<audio_session_t, bool> sessionIds() const; 2055 2056 status_t setSyncEvent(const sp<audioflinger::SyncEvent>& event) override 2057 EXCLUDES_ThreadBase_Mutex; 2058 bool isValidSyncEvent(const sp<audioflinger::SyncEvent>& event) const override; 2059 2060 static void syncStartEventCallback(const wp<audioflinger::SyncEvent>& event); 2061 frameCount()2062 virtual size_t frameCount() const { return mFrameCount; } hasFastCapture()2063 bool hasFastCapture() const final { return mFastCapture != 0; } 2064 virtual void toAudioPortConfig(struct audio_port_config *config); 2065 2066 virtual status_t checkEffectCompatibility_l(const effect_descriptor_t *desc, 2067 audio_session_t sessionId) REQUIRES(mutex()); 2068 acquireWakeLock_l()2069 virtual void acquireWakeLock_l() REQUIRES(mutex()) { 2070 ThreadBase::acquireWakeLock_l(); 2071 mActiveTracks.updatePowerState_l(this, true /* force */); 2072 } 2073 2074 void checkBtNrec() final EXCLUDES_ThreadBase_Mutex; 2075 2076 // Sets the UID records silence 2077 void setRecordSilenced(audio_port_handle_t portId, bool silenced) final 2078 EXCLUDES_ThreadBase_Mutex; 2079 2080 status_t getActiveMicrophones( 2081 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const final 2082 EXCLUDES_ThreadBase_Mutex; 2083 status_t setPreferredMicrophoneDirection(audio_microphone_direction_t direction) final 2084 EXCLUDES_ThreadBase_Mutex; 2085 status_t setPreferredMicrophoneFieldDimension(float zoom) final EXCLUDES_ThreadBase_Mutex; 2086 2087 MetadataUpdate updateMetadata_l() override REQUIRES(mutex()); 2088 fastTrackAvailable()2089 bool fastTrackAvailable() const final { return mFastTrackAvail; } setFastTrackAvailable(bool available)2090 void setFastTrackAvailable(bool available) final { mFastTrackAvail = available; } 2091 isTimestampCorrectionEnabled_l()2092 bool isTimestampCorrectionEnabled_l() const override REQUIRES(mutex()) { 2093 // checks popcount for exactly one device. 2094 // Is currently disabled. Before enabling, 2095 // verify compressed record timestamps. 2096 return audio_is_input_device(mTimestampCorrectedDevice) 2097 && inDeviceType_l() == mTimestampCorrectedDevice; 2098 } 2099 2100 status_t shareAudioHistory(const std::string& sharedAudioPackageName, 2101 audio_session_t sharedSessionId = AUDIO_SESSION_NONE, 2102 int64_t sharedAudioStartMs = -1) final EXCLUDES_ThreadBase_Mutex; 2103 status_t shareAudioHistory_l(const std::string& sharedAudioPackageName, 2104 audio_session_t sharedSessionId = AUDIO_SESSION_NONE, 2105 int64_t sharedAudioStartMs = -1) REQUIRES(mutex()); 2106 void resetAudioHistory_l() final REQUIRES(mutex()); 2107 isStreamInitialized()2108 bool isStreamInitialized() const final { 2109 return !(mInput == nullptr || mInput->stream == nullptr); 2110 } 2111 2112 protected: 2113 void dumpInternals_l(int fd, const Vector<String16>& args) override REQUIRES(mutex()); 2114 void dumpTracks_l(int fd, const Vector<String16>& args) override REQUIRES(mutex()); 2115 2116 private: 2117 // Enter standby if not already in standby, and set mStandby flag 2118 void standbyIfNotAlreadyInStandby(); 2119 2120 // Call the HAL standby method unconditionally, and don't change mStandby flag 2121 void inputStandBy(); 2122 2123 void checkBtNrec_l() REQUIRES(mutex()); 2124 2125 int32_t getOldestFront_l() REQUIRES(mutex()); 2126 void updateFronts_l(int32_t offset) REQUIRES(mutex()); 2127 2128 AudioStreamIn *mInput; 2129 Source *mSource; 2130 SortedVector <sp<IAfRecordTrack>> mTracks; 2131 // mActiveTracks has dual roles: it indicates the current active track(s), and 2132 // is used together with mStartStopCV to indicate start()/stop() progress 2133 ActiveTracks<IAfRecordTrack> mActiveTracks; 2134 2135 audio_utils::condition_variable mStartStopCV; 2136 2137 // resampler converts input at HAL Hz to output at AudioRecord client Hz 2138 void *mRsmpInBuffer; // size = mRsmpInFramesOA 2139 size_t mRsmpInFrames; // size of resampler input in frames 2140 size_t mRsmpInFramesP2;// size rounded up to a power-of-2 2141 size_t mRsmpInFramesOA;// mRsmpInFramesP2 + over-allocation 2142 2143 // rolling index that is never cleared 2144 int32_t mRsmpInRear; // last filled frame + 1 2145 2146 // For dumpsys 2147 const sp<MemoryDealer> mReadOnlyHeap; 2148 2149 // one-time initialization, no locks required 2150 sp<FastCapture> mFastCapture; // non-0 if there is also 2151 // a fast capture 2152 2153 // FIXME audio watchdog thread 2154 2155 // contents are not guaranteed to be consistent, no locks required 2156 FastCaptureDumpState mFastCaptureDumpState; 2157 #ifdef STATE_QUEUE_DUMP 2158 // FIXME StateQueue observer and mutator dump fields 2159 #endif 2160 // FIXME audio watchdog dump 2161 2162 // accessible only within the threadLoop(), no locks required 2163 // mFastCapture->sq() // for mutating and pushing state 2164 int32_t mFastCaptureFutex; // for cold idle 2165 2166 // The HAL input source is treated as non-blocking, 2167 // but current implementation is blocking 2168 sp<NBAIO_Source> mInputSource; 2169 // The source for the normal capture thread to read from: mInputSource or mPipeSource 2170 sp<NBAIO_Source> mNormalSource; 2171 // If a fast capture is present, the non-blocking pipe sink written to by fast capture, 2172 // otherwise clear 2173 sp<NBAIO_Sink> mPipeSink; 2174 // If a fast capture is present, the non-blocking pipe source read by normal thread, 2175 // otherwise clear 2176 sp<NBAIO_Source> mPipeSource; 2177 // Depth of pipe from fast capture to normal thread and fast clients, always power of 2 2178 size_t mPipeFramesP2; 2179 // If a fast capture is present, the Pipe as IMemory, otherwise clear 2180 sp<IMemory> mPipeMemory; 2181 2182 // TODO: add comment and adjust size as needed 2183 static const size_t kFastCaptureLogSize = 4 * 1024; 2184 sp<NBLog::Writer> mFastCaptureNBLogWriter; 2185 2186 bool mFastTrackAvail; // true if fast track available 2187 // common state to all record threads 2188 std::atomic_bool mBtNrecSuspended; 2189 2190 int64_t mFramesRead = 0; // continuous running counter. 2191 2192 DeviceDescriptorBaseVector mOutDevices; 2193 2194 int32_t mMaxSharedAudioHistoryMs = 0; 2195 std::string mSharedAudioPackageName = {}; 2196 int32_t mSharedAudioStartFrames = -1; 2197 audio_session_t mSharedAudioSessionId = AUDIO_SESSION_NONE; 2198 }; 2199 2200 class MmapThread : public ThreadBase, public virtual IAfMmapThread 2201 { 2202 public: 2203 MmapThread(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id, 2204 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, 2205 bool isOut); 2206 configure(const audio_attributes_t * attr,audio_stream_type_t streamType,audio_session_t sessionId,const sp<MmapStreamCallback> & callback,audio_port_handle_t deviceId,audio_port_handle_t portId)2207 void configure(const audio_attributes_t* attr, 2208 audio_stream_type_t streamType, 2209 audio_session_t sessionId, 2210 const sp<MmapStreamCallback>& callback, 2211 audio_port_handle_t deviceId, 2212 audio_port_handle_t portId) override EXCLUDES_ThreadBase_Mutex { 2213 audio_utils::lock_guard l(mutex()); 2214 configure_l(attr, streamType, sessionId, callback, deviceId, portId); 2215 } 2216 2217 void configure_l(const audio_attributes_t* attr, 2218 audio_stream_type_t streamType, 2219 audio_session_t sessionId, 2220 const sp<MmapStreamCallback>& callback, 2221 audio_port_handle_t deviceId, 2222 audio_port_handle_t portId) REQUIRES(mutex()); 2223 2224 void disconnect() final EXCLUDES_ThreadBase_Mutex; 2225 2226 // MmapStreamInterface for adapter. 2227 status_t createMmapBuffer(int32_t minSizeFrames, struct audio_mmap_buffer_info* info) final 2228 EXCLUDES_ThreadBase_Mutex; 2229 status_t getMmapPosition(struct audio_mmap_position* position) const override 2230 EXCLUDES_ThreadBase_Mutex; 2231 status_t start(const AudioClient& client, 2232 const audio_attributes_t *attr, 2233 audio_port_handle_t* handle) final EXCLUDES_ThreadBase_Mutex; 2234 status_t stop(audio_port_handle_t handle) final EXCLUDES_ThreadBase_Mutex; 2235 status_t standby() final EXCLUDES_ThreadBase_Mutex; 2236 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) const 2237 EXCLUDES_ThreadBase_Mutex = 0; 2238 status_t reportData(const void* buffer, size_t frameCount) override EXCLUDES_ThreadBase_Mutex; 2239 2240 // RefBase 2241 void onFirstRef() final; 2242 2243 // Thread virtuals 2244 bool threadLoop() final REQUIRES(ThreadBase_ThreadLoop) EXCLUDES_ThreadBase_Mutex; 2245 2246 // Not in ThreadBase 2247 virtual void threadLoop_exit() final REQUIRES(ThreadBase_ThreadLoop); 2248 virtual void threadLoop_standby() final REQUIRES(ThreadBase_ThreadLoop); shouldStandby_l()2249 virtual bool shouldStandby_l() final REQUIRES(mutex()){ return false; } 2250 virtual status_t exitStandby_l() REQUIRES(mutex()); 2251 initCheck()2252 status_t initCheck() const final { return mHalStream == nullptr ? NO_INIT : NO_ERROR; } frameCount()2253 size_t frameCount() const final { return mFrameCount; } 2254 bool checkForNewParameter_l(const String8& keyValuePair, status_t& status) 2255 final REQUIRES(mutex()); 2256 String8 getParameters(const String8& keys) final EXCLUDES_ThreadBase_Mutex; 2257 void ioConfigChanged_l(audio_io_config_event_t event, pid_t pid = 0, 2258 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final 2259 /* holds either AF::mutex or TB::mutex */; 2260 void readHalParameters_l() REQUIRES(mutex()); cacheParameters_l()2261 void cacheParameters_l() final REQUIRES(mutex(), ThreadBase_ThreadLoop) {} 2262 status_t createAudioPatch_l( 2263 const struct audio_patch* patch, audio_patch_handle_t* handle) final 2264 REQUIRES(mutex()); 2265 status_t releaseAudioPatch_l(const audio_patch_handle_t handle) final 2266 REQUIRES(mutex()); 2267 // NO_THREAD_SAFETY_ANALYSIS 2268 void toAudioPortConfig(struct audio_port_config* config) override; 2269 stream()2270 sp<StreamHalInterface> stream() const final { return mHalStream; } 2271 status_t addEffectChain_l(const sp<IAfEffectChain>& chain) final REQUIRES(mutex()); 2272 size_t removeEffectChain_l(const sp<IAfEffectChain>& chain) final REQUIRES(mutex()); 2273 status_t checkEffectCompatibility_l( 2274 const effect_descriptor_t *desc, audio_session_t sessionId) final REQUIRES(mutex()); 2275 hasAudioSession_l(audio_session_t sessionId)2276 uint32_t hasAudioSession_l(audio_session_t sessionId) const override REQUIRES(mutex()) { 2277 // Note: using mActiveTracks as no mTracks here. 2278 return ThreadBase::hasAudioSession_l(sessionId, mActiveTracks); 2279 } 2280 status_t setSyncEvent(const sp<audioflinger::SyncEvent>& event) final; 2281 bool isValidSyncEvent(const sp<audioflinger::SyncEvent>& event) const final; 2282 checkSilentMode_l()2283 virtual void checkSilentMode_l() REQUIRES(mutex()) {} // cannot be const (RecordThread) processVolume_l()2284 virtual void processVolume_l() REQUIRES(mutex()) {} 2285 void checkInvalidTracks_l() REQUIRES(mutex()); 2286 2287 // Not in ThreadBase streamType_l()2288 virtual audio_stream_type_t streamType_l() const REQUIRES(mutex()) { 2289 return AUDIO_STREAM_DEFAULT; 2290 } invalidateTracks(audio_stream_type_t)2291 virtual void invalidateTracks(audio_stream_type_t /* streamType */) 2292 EXCLUDES_ThreadBase_Mutex {} invalidateTracks(std::set<audio_port_handle_t> &)2293 void invalidateTracks(std::set<audio_port_handle_t>& /* portIds */) override 2294 EXCLUDES_ThreadBase_Mutex {} 2295 2296 // Sets the UID records silence setRecordSilenced(audio_port_handle_t,bool)2297 void setRecordSilenced( 2298 audio_port_handle_t /* portId */, bool /* silenced */) override 2299 EXCLUDES_ThreadBase_Mutex {} 2300 isStreamInitialized()2301 bool isStreamInitialized() const override { return false; } 2302 setClientSilencedState_l(audio_port_handle_t portId,bool silenced)2303 void setClientSilencedState_l(audio_port_handle_t portId, bool silenced) REQUIRES(mutex()) { 2304 mClientSilencedStates[portId] = silenced; 2305 } 2306 eraseClientSilencedState_l(audio_port_handle_t portId)2307 size_t eraseClientSilencedState_l(audio_port_handle_t portId) REQUIRES(mutex()) { 2308 return mClientSilencedStates.erase(portId); 2309 } 2310 isClientSilenced_l(audio_port_handle_t portId)2311 bool isClientSilenced_l(audio_port_handle_t portId) const REQUIRES(mutex()) { 2312 const auto it = mClientSilencedStates.find(portId); 2313 return it != mClientSilencedStates.end() ? it->second : false; 2314 } 2315 setClientSilencedIfExists_l(audio_port_handle_t portId,bool silenced)2316 void setClientSilencedIfExists_l(audio_port_handle_t portId, bool silenced) 2317 REQUIRES(mutex()) { 2318 const auto it = mClientSilencedStates.find(portId); 2319 if (it != mClientSilencedStates.end()) { 2320 it->second = silenced; 2321 } 2322 } 2323 2324 protected: 2325 void dumpInternals_l(int fd, const Vector<String16>& args) override REQUIRES(mutex()); 2326 void dumpTracks_l(int fd, const Vector<String16>& args) final REQUIRES(mutex()); 2327 2328 /** 2329 * @brief mDeviceId current device port unique identifier 2330 */ 2331 audio_port_handle_t mDeviceId GUARDED_BY(mutex()) = AUDIO_PORT_HANDLE_NONE; 2332 2333 audio_attributes_t mAttr GUARDED_BY(mutex()); 2334 audio_session_t mSessionId GUARDED_BY(mutex()); 2335 audio_port_handle_t mPortId GUARDED_BY(mutex()); 2336 2337 wp<MmapStreamCallback> mCallback GUARDED_BY(mutex()); 2338 sp<StreamHalInterface> mHalStream; // NO_THREAD_SAFETY_ANALYSIS 2339 sp<DeviceHalInterface> mHalDevice GUARDED_BY(mutex()); 2340 AudioHwDevice* const mAudioHwDev GUARDED_BY(mutex()); 2341 ActiveTracks<IAfMmapTrack> mActiveTracks GUARDED_BY(mutex()); 2342 float mHalVolFloat GUARDED_BY(mutex()); 2343 std::map<audio_port_handle_t, bool> mClientSilencedStates GUARDED_BY(mutex()); 2344 2345 int32_t mNoCallbackWarningCount GUARDED_BY(mutex()); 2346 static constexpr int32_t kMaxNoCallbackWarnings = 5; 2347 }; 2348 2349 class MmapPlaybackThread : public MmapThread, public IAfMmapPlaybackThread, 2350 public virtual VolumeInterface { 2351 public: 2352 MmapPlaybackThread(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id, 2353 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady); 2354 asIAfMmapPlaybackThread()2355 sp<IAfMmapPlaybackThread> asIAfMmapPlaybackThread() final { 2356 return sp<IAfMmapPlaybackThread>::fromExisting(this); 2357 } 2358 2359 void configure(const audio_attributes_t* attr, 2360 audio_stream_type_t streamType, 2361 audio_session_t sessionId, 2362 const sp<MmapStreamCallback>& callback, 2363 audio_port_handle_t deviceId, 2364 audio_port_handle_t portId) final EXCLUDES_ThreadBase_Mutex; 2365 2366 AudioStreamOut* clearOutput() final EXCLUDES_ThreadBase_Mutex; 2367 2368 // VolumeInterface 2369 void setMasterVolume(float value) final; 2370 // Needs implementation? setMasterBalance(float)2371 void setMasterBalance(float /* value */) final EXCLUDES_ThreadBase_Mutex {} 2372 void setMasterMute(bool muted) final EXCLUDES_ThreadBase_Mutex; 2373 void setStreamVolume(audio_stream_type_t stream, float value) final EXCLUDES_ThreadBase_Mutex; 2374 void setStreamMute(audio_stream_type_t stream, bool muted) final EXCLUDES_ThreadBase_Mutex; 2375 float streamVolume(audio_stream_type_t stream) const final EXCLUDES_ThreadBase_Mutex; 2376 setMasterMute_l(bool muted)2377 void setMasterMute_l(bool muted) REQUIRES(mutex()) { mMasterMute = muted; } 2378 2379 void invalidateTracks(audio_stream_type_t streamType) final EXCLUDES_ThreadBase_Mutex; 2380 void invalidateTracks(std::set<audio_port_handle_t>& portIds) final EXCLUDES_ThreadBase_Mutex; 2381 streamType_l()2382 audio_stream_type_t streamType_l() const final REQUIRES(mutex()) { 2383 return mStreamType; 2384 } 2385 void checkSilentMode_l() final REQUIRES(mutex()); 2386 void processVolume_l() final REQUIRES(mutex()); 2387 2388 MetadataUpdate updateMetadata_l() final REQUIRES(mutex()); 2389 2390 void toAudioPortConfig(struct audio_port_config* config) final; 2391 2392 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) const final; 2393 isStreamInitialized()2394 bool isStreamInitialized() const final { 2395 return !(mOutput == nullptr || mOutput->stream == nullptr); 2396 } 2397 2398 status_t reportData(const void* buffer, size_t frameCount) final; 2399 2400 void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) final 2401 REQUIRES(audio_utils::AudioFlinger_Mutex); 2402 void stopMelComputation_l() final 2403 REQUIRES(audio_utils::AudioFlinger_Mutex); 2404 2405 protected: 2406 void dumpInternals_l(int fd, const Vector<String16>& args) final REQUIRES(mutex()); streamVolume_l()2407 float streamVolume_l() const REQUIRES(mutex()) { 2408 return mStreamTypes[mStreamType].volume; 2409 } streamMuted_l()2410 bool streamMuted_l() const REQUIRES(mutex()) { 2411 return mStreamTypes[mStreamType].mute; 2412 } 2413 2414 stream_type_t mStreamTypes[AUDIO_STREAM_CNT] GUARDED_BY(mutex()); 2415 audio_stream_type_t mStreamType GUARDED_BY(mutex()); 2416 float mMasterVolume GUARDED_BY(mutex()); 2417 bool mMasterMute GUARDED_BY(mutex()); 2418 AudioStreamOut* mOutput; // NO_THREAD_SAFETY_ANALYSIS 2419 2420 mediautils::atomic_sp<audio_utils::MelProcessor> mMelProcessor; // locked internally 2421 }; 2422 2423 class MmapCaptureThread : public MmapThread, public IAfMmapCaptureThread 2424 { 2425 public: 2426 MmapCaptureThread(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id, 2427 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady); 2428 asIAfMmapCaptureThread()2429 sp<IAfMmapCaptureThread> asIAfMmapCaptureThread() final { 2430 return sp<IAfMmapCaptureThread>::fromExisting(this); 2431 } 2432 2433 AudioStreamIn* clearInput() final EXCLUDES_ThreadBase_Mutex; 2434 2435 status_t exitStandby_l() REQUIRES(mutex()) final; 2436 2437 MetadataUpdate updateMetadata_l() final REQUIRES(mutex()); 2438 void processVolume_l() final REQUIRES(mutex()); 2439 void setRecordSilenced(audio_port_handle_t portId, bool silenced) final 2440 EXCLUDES_ThreadBase_Mutex; 2441 2442 void toAudioPortConfig(struct audio_port_config* config) final; 2443 2444 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) const final; 2445 isStreamInitialized()2446 bool isStreamInitialized() const final { 2447 return !(mInput == nullptr || mInput->stream == nullptr); 2448 } 2449 2450 protected: 2451 2452 AudioStreamIn* mInput; // NO_THREAD_SAFETY_ANALYSIS 2453 }; 2454 2455 class BitPerfectThread : public MixerThread { 2456 public: 2457 BitPerfectThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut *output, 2458 audio_io_handle_t id, bool systemReady); 2459 2460 void setTracksInternalMute(std::map<audio_port_handle_t, bool>* tracksInternalMuted) 2461 final EXCLUDES_ThreadBase_Mutex; 2462 2463 protected: 2464 mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove) final 2465 REQUIRES(mutex(), ThreadBase_ThreadLoop); 2466 void threadLoop_mix() final REQUIRES(ThreadBase_ThreadLoop); 2467 2468 private: 2469 sp<IAfTrack> getTrackToStreamBitPerfectly_l() REQUIRES(mutex()); 2470 2471 // These variables are only accessed on the threadLoop; hence need no mutex. 2472 bool mIsBitPerfect GUARDED_BY(ThreadBase_ThreadLoop) = false; 2473 float mVolumeLeft GUARDED_BY(ThreadBase_ThreadLoop) = 0.f; 2474 float mVolumeRight GUARDED_BY(ThreadBase_ThreadLoop) = 0.f; 2475 }; 2476 2477 } // namespace android 2478