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