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