AudioFlinger: Create Thread callback

Test: atest AudioTrackTest AudioRecordTest
Test: Camera YouTube
Bug: 291012167
Bug: 291319167
Merged-In: I82024cc2bebe56282224efb4ffda1f5dcc513702
Change-Id: I82024cc2bebe56282224efb4ffda1f5dcc513702
diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp
index 61a543d..298a7dd 100644
--- a/services/audioflinger/AudioFlinger.cpp
+++ b/services/audioflinger/AudioFlinger.cpp
@@ -528,7 +528,7 @@
 }
 
 // getDefaultVibratorInfo_l must be called with AudioFlinger lock held.
-std::optional<media::AudioVibratorInfo> AudioFlinger::getDefaultVibratorInfo_l() {
+std::optional<media::AudioVibratorInfo> AudioFlinger::getDefaultVibratorInfo_l() const {
     if (mAudioVibratorInfos.empty()) {
         return {};
     }
@@ -4662,7 +4662,7 @@
     return status;
 }
 
-bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
+bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l() const
 NO_THREAD_SAFETY_ANALYSIS  // thread lock for getEffectChain_l.
 {
     if (mGlobalEffectEnableTime != 0 &&
diff --git a/services/audioflinger/AudioFlinger.h b/services/audioflinger/AudioFlinger.h
index 2e0519c..cbaef15 100644
--- a/services/audioflinger/AudioFlinger.h
+++ b/services/audioflinger/AudioFlinger.h
@@ -122,9 +122,6 @@
 #include "Client.h"
 #include "ResamplerBufferProvider.h"
 
-// TODO(b/291319167) remove me when AudioFlinger class not directly used by subcomponents
-namespace android { class AudioFlinger; }
-
 // include AudioFlinger component interfaces
 #include "IAfPatchPanel.h"  // this should be listed before other IAf* interfaces.
 #include "IAfEffect.h"
@@ -167,24 +164,17 @@
     , public IAfDeviceEffectManagerCallback
     , public IAfMelReporterCallback
     , public IAfPatchPanelCallback
+    , public IAfThreadCallback
 {
     friend class sp<AudioFlinger>;
-    // TODO(b/291319167) Create interface and remove friends.
-    // TODO(b/291012167) replace the Thread friends with an interface.
-    friend class DirectOutputThread;
-    friend class MixerThread;
-    friend class MmapPlaybackThread;
-    friend class MmapThread;
-    friend class PlaybackThread;
-    friend class RecordThread;
-    friend class ThreadBase;
-
 public:
     static void instantiate() ANDROID_API;
 
     static AttributionSourceState checkAttributionSourcePackage(
         const AttributionSourceState& attributionSource);
 
+private:
+
     // ---- begin IAudioFlinger interface
 
     status_t dump(int fd, const Vector<String16>& args) final;
@@ -324,7 +314,7 @@
 
     status_t getMmapPolicyInfos(
             media::audio::common::AudioMMapPolicyType policyType,
-            std::vector<media::audio::common::AudioMMapPolicyInfo>* policyInfos) override;
+            std::vector<media::audio::common::AudioMMapPolicyInfo>* policyInfos) final;
 
     int32_t getAAudioMixerBurstCount() const final;
 
@@ -373,6 +363,7 @@
 
     // ---- begin IAfDeviceEffectManagerCallback interface
 
+    // also used by IAfThreadCallback
     bool isAudioPolicyReady() const final { return mAudioPolicyReady.load(); }
     // below also used by IAfMelReporterCallback, IAfPatchPanelCallback
     const sp<PatchCommandThread>& getPatchCommandThread() final { return mPatchCommandThread; }
@@ -385,6 +376,7 @@
 
     // ---- begin IAfMelReporterCallback interface
 
+    // below also used by IAfThreadCallback
     Mutex& mutex() const final { return mLock; }
     sp<IAfThreadBase> checkOutputThread_l(audio_io_handle_t ioHandle) const final REQUIRES(mLock);
 
@@ -425,13 +417,62 @@
 
     // ---- end of IAfPatchPanelCallback interface
 
+    // ----- begin IAfThreadCallback interface
+
+    bool isNonOffloadableGlobalEffectEnabled_l() const final;
+    bool btNrecIsOff() const final { return mBtNrecIsOff.load(); }
+    float masterVolume_l() const final;
+    bool masterMute_l() const final;
+    float getMasterBalance_l() const;
+    // no range check, AudioFlinger::mLock held
+    bool streamMute_l(audio_stream_type_t stream) const final { return mStreamTypes[stream].mute; }
+    audio_mode_t getMode() const final { return mMode; }
+    bool isLowRamDevice() const final { return mIsLowRamDevice; }
+
+    std::optional<media::AudioVibratorInfo> getDefaultVibratorInfo_l() const final;
+    const sp<IAfPatchPanel>& getPatchPanel() const final { return mPatchPanel; }
+    const sp<MelReporter>& getMelReporter() const final { return mMelReporter; }
+    const sp<EffectsFactoryHalInterface>& getEffectsFactoryHal() const final {
+        return mEffectsFactoryHal;
+    }
+    sp<IAudioManager> getOrCreateAudioManager() final;
+
+    // Called when the last effect handle on an effect instance is removed. If this
+    // effect belongs to an effect chain in mOrphanEffectChains, the chain is updated
+    // and removed from mOrphanEffectChains if it does not contain any effect.
+    // Return true if the effect was found in mOrphanEffectChains, false otherwise.
+    bool updateOrphanEffectChains(const sp<IAfEffectModule>& effect) final;
+
+    status_t moveEffectChain_l(audio_session_t sessionId,
+            IAfPlaybackThread* srcThread, IAfPlaybackThread* dstThread) final;
+
+    // This is a helper that is called during incoming binder calls.
+    // Requests media.log to start merging log buffers
+    void requestLogMerge() final;
+    sp<NBLog::Writer> newWriter_l(size_t size, const char *name) final;
+    void unregisterWriter(const sp<NBLog::Writer>& writer) final;
+
+    sp<audioflinger::SyncEvent> createSyncEvent(AudioSystem::sync_event_t type,
+            audio_session_t triggerSession,
+            audio_session_t listenerSession,
+            const audioflinger::SyncEventCallback& callBack,
+            const wp<IAfTrackBase>& cookie) final;
+
+    void ioConfigChanged(audio_io_config_event_t event,
+            const sp<AudioIoDescriptor>& ioDesc,
+            pid_t pid = 0) final;
+    void onNonOffloadableGlobalEffectEnable() final;
+    void onSupportedLatencyModesChanged(
+            audio_io_handle_t output, const std::vector<audio_latency_mode_t>& modes) final;
+
+    // ---- end of IAfThreadCallback interface
+
     /* List available audio ports and their attributes */
     status_t listAudioPorts(unsigned int* num_ports, struct audio_port* ports) const;
 
-    sp<NBLog::Writer>   newWriter_l(size_t size, const char *name);
-    void                unregisterWriter(const sp<NBLog::Writer>& writer);
     sp<EffectsFactoryHalInterface> getEffectsFactory();
 
+public:
     status_t openMmapStream(MmapStreamInterface::stream_direction_t direction,
                             const audio_attributes_t *attr,
                             audio_config_base_t *config,
@@ -446,8 +487,6 @@
         const sp<os::ExternalVibration>& externalVibration);
     static void onExternalVibrationStop(const sp<os::ExternalVibration>& externalVibration);
 
-    std::optional<media::AudioVibratorInfo> getDefaultVibratorInfo_l();
-
 private:
     // FIXME The 400 is temporarily too high until a leak of writers in media.log is fixed.
     static const size_t kLogMemorySize = 400 * 1024;
@@ -457,38 +496,6 @@
     Vector< sp<NBLog::Writer> > mUnregisteredWriters;
     Mutex               mUnregisteredWritersLock;
 
-public:
-    // Life cycle of gAudioFlinger and AudioFlinger:
-    //
-    // AudioFlinger is created once and survives until audioserver crashes
-    // irrespective of sp<> and wp<> as it is refcounted by ServiceManager and we
-    // don't issue a ServiceManager::tryUnregisterService().
-    //
-    // gAudioFlinger is an atomic pointer set on AudioFlinger::onFirstRef().
-    // After this is set, it is safe to obtain a wp<> or sp<> from it as the
-    // underlying object does not go away.
-    //
-    // Note: For most inner classes, it is acceptable to hold a reference to the outer
-    // AudioFlinger instance as creation requires AudioFlinger to exist in the first place.
-    //
-    // An atomic here ensures underlying writes have completed before setting
-    // the pointer. Access by memory_order_seq_cst.
-    //
-
-    static inline std::atomic<AudioFlinger *> gAudioFlinger = nullptr;
-
-    sp<audioflinger::SyncEvent> createSyncEvent(AudioSystem::sync_event_t type,
-                                        audio_session_t triggerSession,
-                                        audio_session_t listenerSession,
-                                        const audioflinger::SyncEventCallback& callBack,
-                                        const wp<IAfTrackBase>& cookie);
-
-    bool        btNrecIsOff() const { return mBtNrecIsOff.load(); }
-
-private:
-
-               audio_mode_t getMode() const { return mMode; }
-
                             AudioFlinger() ANDROID_API;
     ~AudioFlinger() override;
 
@@ -507,6 +514,10 @@
     // FCC_2 <= channels <= AudioMixer::MAX_NUM_CHANNELS.
     static const bool kEnableExtendedChannels = true;
 
+public:
+    // Remove this when Oboeservice is updated to obtain handle directly.
+    static inline std::atomic<AudioFlinger*> gAudioFlinger = nullptr;
+
     // Returns true if channel mask is permitted for the PCM sink in the MixerThread
     static inline bool isValidPcmSinkChannelMask(audio_channel_mask_t channelMask) {
         switch (audio_channel_mask_get_representation(channelMask)) {
@@ -565,7 +576,7 @@
 
     // Internal dump utilities.
     static const int kDumpLockTimeoutNs = 1 * NANOS_PER_SECOND;
-public:
+
     // TODO(b/291319167) extract to afutils
     static bool dumpTryLock(Mutex& mutex);
 private:
@@ -631,10 +642,6 @@
 
     const sp<MediaLogNotifier> mMediaLogNotifier;
 
-    // This is a helper that is called during incoming binder calls.
-    // Requests media.log to start merging log buffers
-    void requestLogMerge();
-
     // Find io handle by session id.
     // Preference is given to an io handle with a matching effect chain to session id.
     // If none found, AUDIO_IO_HANDLE_NONE is returned.
@@ -665,15 +672,6 @@
     void closeOutputFinish(const sp<IAfPlaybackThread>& thread);
     void closeInputFinish(const sp<IAfRecordThread>& thread);
 
-              // no range check, AudioFlinger::mLock held
-              bool streamMute_l(audio_stream_type_t stream) const
-                                { return mStreamTypes[stream].mute; }
-              void ioConfigChanged(audio_io_config_event_t event,
-                                   const sp<AudioIoDescriptor>& ioDesc,
-                                   pid_t pid = 0);
-              void onSupportedLatencyModesChanged(
-                    audio_io_handle_t output, const std::vector<audio_latency_mode_t>& modes);
-
               // Allocate an audio_unique_id_t.
               // Specific types are audio_io_handle_t, audio_session_t, effect ID (int),
               // audio_module_handle_t, and audio_patch_handle_t.
@@ -685,12 +683,9 @@
               //       Thus it may fail by returning an ID of the wrong sign,
               //       or by returning a non-unique ID.
               // This is the internal API.  For the binder API see newAudioUniqueId().
-    // used by IAfDeviceEffectManagerCallback, IAfPatchPanelCallback
+    // used by IAfDeviceEffectManagerCallback, IAfPatchPanelCallback, IAfThreadCallback
     audio_unique_id_t nextUniqueId(audio_unique_id_use_t use) final;
 
-              status_t moveEffectChain_l(audio_session_t sessionId,
-            IAfPlaybackThread* srcThread, IAfPlaybackThread* dstThread);
-
               // return thread associated with primary hardware device, or NULL
               DeviceTypeSet primaryOutputDevice_l() const;
 
@@ -706,11 +701,6 @@
                       IAfPlaybackThread* thread,
                       const std::vector<audio_io_handle_t>& secondaryOutputs) const;
 
-public:
-    // TODO(b/291319167) cluster together
-                bool isNonOffloadableGlobalEffectEnabled_l();
-private:
-                void onNonOffloadableGlobalEffectEnable();
                 bool isSessionAcquired_l(audio_session_t audioSession);
 
                 // Store an effect chain to mOrphanEffectChains keyed vector.
@@ -724,14 +714,7 @@
                 // Get an effect chain for the specified session in mOrphanEffectChains and remove
                 // it if found. Returns 0 if not found (this is the most common case).
                 sp<IAfEffectChain> getOrphanEffectChain_l(audio_session_t session);
-                // Called when the last effect handle on an effect instance is removed. If this
-                // effect belongs to an effect chain in mOrphanEffectChains, the chain is updated
-                // and removed from mOrphanEffectChains if it does not contain any effect.
-                // Return true if the effect was found in mOrphanEffectChains, false otherwise.
-public:
-// TODO(b/291319167) suggest better grouping
-                bool updateOrphanEffectChains(const sp<IAfEffectModule>& effect);
-private:
+
                 std::vector< sp<IAfEffectModule> > purgeStaleEffects_l();
 
                 void broadcastParametersToRecordThreads_l(const String8& keyValuePairs);
@@ -749,14 +732,11 @@
         int         mCnt;
     };
 
-public:
-    // TODO(b/291319167) access by getter,
     mutable     Mutex                               mLock;
                 // protects mClients and mNotificationClients.
                 // must be locked after mLock and ThreadBase::mLock if both must be locked
                 // avoids acquiring AudioFlinger::mLock from inside thread loop.
 
-private:
     mutable Mutex mClientLock;
 
                 // protected by mClientLock
@@ -828,9 +808,6 @@
                 // protected by mLock
                 Vector<AudioSessionRef*> mAudioSessionRefs;
 
-                float       masterVolume_l() const;
-                float       getMasterBalance_l() const;
-                bool        masterMute_l() const;
                 AudioHwDevice* loadHwModule_l(const char *name);
 
                 // sync events awaiting for a session to be created.
@@ -847,7 +824,6 @@
                 // Audio data transfer is directly handled by the client creating the MMAP stream
     DefaultKeyedVector<audio_io_handle_t, sp<IAfMmapThread>> mMmapThreads;
 
-private:
     sp<Client>  registerPid(pid_t pid);    // always returns non-0
 
     // for use from destructor
@@ -862,15 +838,10 @@
                                       size_t rejectedKVPSize, const String8& rejectedKVPs,
                                       uid_t callingUid);
 
-public:
-    sp<IAudioManager> getOrCreateAudioManager();
-
     // These methods read variables atomically without mLock,
     // though the variables are updated with mLock.
-    bool    isLowRamDevice() const { return mIsLowRamDevice; }
     size_t getClientSharedHeapSize() const;
 
-private:
     std::atomic<bool> mIsLowRamDevice;
     bool    mIsDeviceTypeKnown;
     int64_t mTotalMemory;
@@ -881,10 +852,7 @@
 
     /* const */ sp<IAfPatchPanel> mPatchPanel;
 
-public:
-    // TODO(b/291319167) access by getter.
     sp<EffectsFactoryHalInterface> mEffectsFactoryHal;
-private:
 
     const sp<PatchCommandThread> mPatchCommandThread;
     /* const */ sp<DeviceEffectManager> mDeviceEffectManager;  // set onFirstRef
@@ -903,8 +871,10 @@
 
     static inline constexpr const char *mMetricsId = AMEDIAMETRICS_KEY_AUDIO_FLINGER;
 
+public:
     // Keep in sync with java definition in media/java/android/media/AudioRecord.java
     static constexpr int32_t kMaxSharedAudioHistoryMs = 5000;
+private:
 
     std::map<media::audio::common::AudioMMapPolicyType,
              std::vector<media::audio::common::AudioMMapPolicyInfo>> mPolicyInfos;
diff --git a/services/audioflinger/Effects.cpp b/services/audioflinger/Effects.cpp
index 55b4f59..e318e2f 100644
--- a/services/audioflinger/Effects.cpp
+++ b/services/audioflinger/Effects.cpp
@@ -2112,30 +2112,22 @@
 
 /* static */
 sp<IAfEffectChain> IAfEffectChain::create(
-        const wp<IAfThreadBase>& wThread,
+        const sp<IAfThreadBase>& thread,
         audio_session_t sessionId)
 {
-    return sp<EffectChain>::make(wThread, sessionId);
+    return sp<EffectChain>::make(thread, sessionId);
 }
 
-EffectChain::EffectChain(const wp<IAfThreadBase>& thread,
+EffectChain::EffectChain(const sp<IAfThreadBase>& thread,
                                        audio_session_t sessionId)
     : mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
       mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
       mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX),
       mEffectCallback(new EffectCallback(wp<EffectChain>(this), thread))
 {
-    const sp<IAfThreadBase> p = thread.promote();
-    if (p == nullptr) {
-        return;
-    }
-    mStrategy = p->getStrategyForStream(AUDIO_STREAM_MUSIC);
-    mMaxTailBuffers = ((kProcessTailDurationMs * p->sampleRate()) / 1000) /
-                                    p->frameCount();
-}
-
-EffectChain::~EffectChain()
-{
+    mStrategy = thread->getStrategyForStream(AUDIO_STREAM_MUSIC);
+    mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
+                                    thread->frameCount();
 }
 
 // getEffectFromDesc_l() must be called with IAfThreadBase::mutex() held
@@ -3002,12 +2994,12 @@
 bool EffectChain::EffectCallback::updateOrphanEffectChains(
         const sp<IAfEffectBase>& effect) {
     // in EffectChain context, an EffectBase is always from an EffectModule so static cast is safe
-    return mAudioFlinger.updateOrphanEffectChains(effect->asEffectModule());
+    return mAfThreadCallback->updateOrphanEffectChains(effect->asEffectModule());
 }
 
 status_t EffectChain::EffectCallback::allocateHalBuffer(
         size_t size, sp<EffectBufferHalInterface>* buffer) {
-    return mAudioFlinger.mEffectsFactoryHal->allocateBuffer(size, buffer);
+    return mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(size, buffer);
 }
 
 status_t EffectChain::EffectCallback::addEffectToHal(
diff --git a/services/audioflinger/Effects.h b/services/audioflinger/Effects.h
index 1a894e3..50d3264 100644
--- a/services/audioflinger/Effects.h
+++ b/services/audioflinger/Effects.h
@@ -382,8 +382,7 @@
 // it also provide it's own input buffer used by the track as accumulation buffer.
 class EffectChain : public IAfEffectChain {
 public:
-    EffectChain(const wp<IAfThreadBase>& wThread, audio_session_t sessionId);
-    ~EffectChain() override;
+    EffectChain(const sp<IAfThreadBase>& thread, audio_session_t sessionId);
 
     void process_l() final;
 
@@ -516,16 +515,11 @@
         // Note: ctors taking a weak pointer to their owner must not promote it
         // during construction (but may keep a reference for later promotion).
         EffectCallback(const wp<EffectChain>& owner,
-                const wp<IAfThreadBase>& thread)
+                const sp<IAfThreadBase>& thread)  // we take a sp<> but store a wp<>.
             : mChain(owner)
-            , mThread(thread)
-            , mAudioFlinger(*AudioFlinger::gAudioFlinger) {
-            const sp<IAfThreadBase> base = thread.promote();
-            if (base != nullptr) {
-                mThreadType = base->type();
-            } else {
-                mThreadType = IAfThreadBase::MIXER;  // assure a consistent value.
-            }
+            , mThread(thread) {
+            mThreadType = thread->type();
+            mAfThreadCallback = thread->afThreadCallback();
         }
 
         status_t createEffectHal(const effect_uuid_t *pEffectUuid,
@@ -566,7 +560,7 @@
         wp<IAfEffectChain> chain() const final { return mChain; }
 
         bool isAudioPolicyReady() const final {
-            return mAudioFlinger.isAudioPolicyReady();
+            return mAfThreadCallback->isAudioPolicyReady();
         }
 
         wp<IAfThreadBase> thread() const { return mThread.load(); }
@@ -574,12 +568,13 @@
         void setThread(const sp<IAfThreadBase>& thread) {
             mThread = thread;
             mThreadType = thread->type();
+            mAfThreadCallback = thread->afThreadCallback();
         }
 
     private:
         const wp<IAfEffectChain> mChain;
         mediautils::atomic_wp<IAfThreadBase> mThread;
-        AudioFlinger &mAudioFlinger;  // implementation detail: outer instance always exists.
+        sp<IAfThreadCallback> mAfThreadCallback;
         IAfThreadBase::type_t mThreadType;
     };
 
diff --git a/services/audioflinger/IAfEffect.h b/services/audioflinger/IAfEffect.h
index 1236bc7..a59eff4 100644
--- a/services/audioflinger/IAfEffect.h
+++ b/services/audioflinger/IAfEffect.h
@@ -192,7 +192,7 @@
     // Most of these methods are accessed from AudioFlinger::Thread
 public:
     static sp<IAfEffectChain> create(
-            const wp<IAfThreadBase>& wThread,
+            const sp<IAfThreadBase>& thread,
             audio_session_t sessionId);
 
     // special key used for an entry in mSuspendedEffects keyed vector
diff --git a/services/audioflinger/IAfThread.h b/services/audioflinger/IAfThread.h
index ce4d62d..deb019f 100644
--- a/services/audioflinger/IAfThread.h
+++ b/services/audioflinger/IAfThread.h
@@ -26,6 +26,50 @@
 class IAfMmapPlaybackThread;
 class IAfPlaybackThread;
 class IAfRecordThread;
+class MelReporter;
+
+// Note this is exposed through IAfThreadBase::afThreadCallback()
+// and hence may be used by the Effect / Track framework.
+class IAfThreadCallback : public virtual RefBase {
+public:
+    virtual Mutex& mutex() const = 0;
+    virtual bool isNonOffloadableGlobalEffectEnabled_l() const = 0;  // Tracks
+    virtual audio_unique_id_t nextUniqueId(audio_unique_id_use_t use) = 0;
+    virtual bool btNrecIsOff() const = 0;
+    virtual float masterVolume_l() const = 0;
+    virtual bool masterMute_l() const = 0;
+    virtual float getMasterBalance_l() const = 0;
+    virtual bool streamMute_l(audio_stream_type_t stream) const = 0;
+    virtual audio_mode_t getMode() const = 0;
+    virtual bool isLowRamDevice() const = 0;
+    virtual bool isAudioPolicyReady() const = 0;  // Effects
+    virtual std::optional<media::AudioVibratorInfo> getDefaultVibratorInfo_l() const = 0;
+    virtual const sp<IAfPatchPanel>& getPatchPanel() const = 0;
+    virtual const sp<MelReporter>& getMelReporter() const = 0;
+    virtual const sp<EffectsFactoryHalInterface>& getEffectsFactoryHal() const = 0;
+    virtual sp<IAudioManager> getOrCreateAudioManager() = 0;  // Tracks
+
+    virtual bool updateOrphanEffectChains(const sp<IAfEffectModule>& effect) = 0;
+    virtual status_t moveEffectChain_l(audio_session_t sessionId,
+            IAfPlaybackThread* srcThread, IAfPlaybackThread* dstThread) = 0;
+
+    virtual void requestLogMerge() = 0;
+    virtual sp<NBLog::Writer> newWriter_l(size_t size, const char *name) = 0;
+    virtual void unregisterWriter(const sp<NBLog::Writer>& writer) = 0;
+
+    virtual sp<audioflinger::SyncEvent> createSyncEvent(AudioSystem::sync_event_t type,
+            audio_session_t triggerSession,
+            audio_session_t listenerSession,
+            const audioflinger::SyncEventCallback& callBack,
+            const wp<IAfTrackBase>& cookie) = 0;
+
+    virtual void ioConfigChanged(audio_io_config_event_t event,
+            const sp<AudioIoDescriptor>& ioDesc,
+            pid_t pid = 0) = 0;
+    virtual void onNonOffloadableGlobalEffectEnable() = 0;
+    virtual void onSupportedLatencyModesChanged(
+            audio_io_handle_t output, const std::vector<audio_latency_mode_t>& modes) = 0;
+};
 
 class IAfThreadBase : public virtual RefBase {
 public:
@@ -250,30 +294,31 @@
     virtual sp<IAfDuplicatingThread> asIAfDuplicatingThread() { return nullptr; }
     virtual sp<IAfPlaybackThread> asIAfPlaybackThread() { return nullptr; }
     virtual sp<IAfRecordThread> asIAfRecordThread() { return nullptr; }
-    virtual AudioFlinger* audioFlinger() const = 0;
+    virtual IAfThreadCallback* afThreadCallback() const = 0;
 };
 
 class IAfPlaybackThread : public virtual IAfThreadBase, public virtual VolumeInterface {
 public:
     static sp<IAfPlaybackThread> createBitPerfectThread(
-            const sp<AudioFlinger>& audioflinger, AudioStreamOut* output, audio_io_handle_t id,
-            bool systemReady);
+            const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
+            audio_io_handle_t id, bool systemReady);
 
     static sp<IAfPlaybackThread> createDirectOutputThread(
-            const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, audio_io_handle_t id,
-            bool systemReady, const audio_offload_info_t& offloadInfo);
+            const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
+            audio_io_handle_t id, bool systemReady, const audio_offload_info_t& offloadInfo);
 
     static sp<IAfPlaybackThread> createMixerThread(
-            const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, audio_io_handle_t id,
-            bool systemReady, type_t type = MIXER, audio_config_base_t* mixerConfig = nullptr);
+            const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
+            audio_io_handle_t id, bool systemReady, type_t type = MIXER,
+            audio_config_base_t* mixerConfig = nullptr);
 
     static sp<IAfPlaybackThread> createOffloadThread(
-            const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, audio_io_handle_t id,
-            bool systemReady, const audio_offload_info_t& offloadInfo);
+            const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
+            audio_io_handle_t id, bool systemReady, const audio_offload_info_t& offloadInfo);
 
     static sp<IAfPlaybackThread> createSpatializerThread(
-            const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, audio_io_handle_t id,
-            bool systemReady, audio_config_base_t* mixerConfig);
+            const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
+            audio_io_handle_t id, bool systemReady, audio_config_base_t* mixerConfig);
 
     static constexpr int8_t kMaxTrackStopRetriesOffload = 2;
 
@@ -388,7 +433,7 @@
 class IAfDuplicatingThread : public virtual IAfPlaybackThread {
 public:
     static sp<IAfDuplicatingThread> create(
-            const sp<AudioFlinger>& audioFlinger, IAfPlaybackThread* mainThread,
+            const sp<IAfThreadCallback>& afThreadCallback, IAfPlaybackThread* mainThread,
             audio_io_handle_t id, bool systemReady);
 
     virtual void addOutputTrack(IAfPlaybackThread* thread) = 0;
@@ -399,8 +444,8 @@
 class IAfRecordThread : public virtual IAfThreadBase {
 public:
     static sp<IAfRecordThread> create(
-            const sp<AudioFlinger>& audioFlinger, AudioStreamIn* input, audio_io_handle_t id,
-            bool systemReady);
+            const sp<IAfThreadCallback>& afThreadCallback, AudioStreamIn* input,
+            audio_io_handle_t id, bool systemReady);
 
     virtual sp<IAfRecordTrack> createRecordTrack_l(
             const sp<Client>& client,
@@ -499,8 +544,8 @@
 class IAfMmapPlaybackThread : public virtual IAfMmapThread, public virtual VolumeInterface {
 public:
     static sp<IAfMmapPlaybackThread> create(
-            const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id, AudioHwDevice* hwDev,
-            AudioStreamOut* output, bool systemReady);
+            const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
+            AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady);
 
     virtual AudioStreamOut* clearOutput() = 0;
 };
@@ -508,8 +553,8 @@
 class IAfMmapCaptureThread : public virtual IAfMmapThread {
 public:
     static sp<IAfMmapCaptureThread> create(
-            const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id, AudioHwDevice* hwDev,
-            AudioStreamIn* input, bool systemReady);
+            const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
+            AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady);
 
     virtual AudioStreamIn* clearInput() = 0;
 };
diff --git a/services/audioflinger/Threads.cpp b/services/audioflinger/Threads.cpp
index ce4396d..0965aa2 100644
--- a/services/audioflinger/Threads.cpp
+++ b/services/audioflinger/Threads.cpp
@@ -544,11 +544,11 @@
     }
 }
 
-ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
+ThreadBase::ThreadBase(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
         type_t type, bool systemReady, bool isOut)
     :   Thread(false /*canCallJava*/),
         mType(type),
-        mAudioFlinger(audioFlinger),
+        mAfThreadCallback(afThreadCallback),
         mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
                isOut),
         mIsOut(isOut),
@@ -1588,7 +1588,7 @@
         ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
 
         if (effect == 0) {
-            effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
+            effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
             // create a new effect module if none present in the chain
             lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
             if (lStatus != NO_ERROR) {
@@ -1599,14 +1599,14 @@
             // FIXME: use vector of device and address when effect interface is ready.
             effect->setDevices(outDeviceTypeAddrs());
             effect->setInputDevice(inDeviceTypeAddr());
-            effect->setMode(mAudioFlinger->getMode());
+            effect->setMode(mAfThreadCallback->getMode());
             effect->setAudioSource(mAudioSource);
         }
         if (effect->isHapticGenerator()) {
             // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
             // for the HapticGenerator.
             const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
-                    std::move(mAudioFlinger->getDefaultVibratorInfo_l());
+                    std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
             if (defaultVibratorInfo) {
                 // Only set the vibrator info when it is a valid one.
                 effect->setVibratorInfo(*defaultVibratorInfo);
@@ -1664,7 +1664,7 @@
         sendCheckOutputStageEffectsEvent_l();
     }
     if (remove) {
-        mAudioFlinger->updateOrphanEffectChains(effect);
+        mAfThreadCallback->updateOrphanEffectChains(effect);
         if (handle->enabled()) {
             effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
         }
@@ -1682,7 +1682,7 @@
             t->invalidateTracks(AUDIO_STREAM_MUSIC);
         }
         if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
-            mAudioFlinger->onNonOffloadableGlobalEffectEnable();
+            mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
         }
     }
 }
@@ -1755,7 +1755,7 @@
 
     effect->setDevices(outDeviceTypeAddrs());
     effect->setInputDevice(inDeviceTypeAddr());
-    effect->setMode(mAudioFlinger->getMode());
+    effect->setMode(mAfThreadCallback->getMode());
     effect->setAudioSource(mAudioSource);
 
     return NO_ERROR;
@@ -2029,7 +2029,7 @@
 
 product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
 {
-    if (!mAudioFlinger->isAudioPolicyReady()) {
+    if (!mAfThreadCallback->isAudioPolicyReady()) {
         return PRODUCT_STRATEGY_NONE;
     }
     return AudioSystem::getStrategyForStream(stream);
@@ -2054,13 +2054,13 @@
 //      Playback
 // ----------------------------------------------------------------------------
 
-PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
+PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
                                              AudioStreamOut* output,
                                              audio_io_handle_t id,
                                              type_t type,
                                              bool systemReady,
                                              audio_config_base_t *mixerConfig)
-    :   ThreadBase(audioFlinger, id, type, systemReady, true /* isOut */),
+    :   ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
         mNormalFrameCount(0), mSinkBuffer(NULL),
         mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
         mMixerBuffer(NULL),
@@ -2097,7 +2097,7 @@
         mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
 {
     snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
-    mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
+    mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
 
     // Assumes constructor is called by AudioFlinger with it's mLock held, but
     // it would be safer to explicitly pass initial masterVolume/masterMute as
@@ -2106,8 +2106,8 @@
     // If the HAL we are using has support for master volume or master mute,
     // then do not attenuate or mute during mixing (just leave the volume at 1.0
     // and the mute set to false).
-    mMasterVolume = audioFlinger->masterVolume_l();
-    mMasterMute = audioFlinger->masterMute_l();
+    mMasterVolume = afThreadCallback->masterVolume_l();
+    mMasterMute = afThreadCallback->masterMute_l();
     if (mOutput->audioHwDev) {
         if (mOutput->audioHwDev->canSetMasterVolume()) {
             mMasterVolume = 1.0;
@@ -2145,7 +2145,7 @@
     for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
         const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
         mStreamTypes[stream].volume = 0.0f;
-        mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
+        mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
     }
     // Audio patch and call assistant volume are always max
     mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
@@ -2156,7 +2156,7 @@
 
 PlaybackThread::~PlaybackThread()
 {
-    mAudioFlinger->unregisterWriter(mNBLogWriter);
+    mAfThreadCallback->unregisterWriter(mNBLogWriter);
     free(mSinkBuffer);
     free(mMixerBuffer);
     free(mEffectBuffer);
@@ -2842,8 +2842,8 @@
             {
                 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
                 // used to play this track.
-                Mutex::Autolock _l(mAudioFlinger->mLock);
-                vibratorInfo = std::move(mAudioFlinger->getDefaultVibratorInfo_l());
+                Mutex::Autolock _l(mAfThreadCallback->mutex());
+                vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
             }
             mLock.lock();
             track->setHapticIntensity(intensity);
@@ -2968,7 +2968,7 @@
         desc = sp<AudioIoDescriptor>::make(mId);
         break;
     }
-    mAudioFlinger->ioConfigChanged(event, desc, pid);
+    mAfThreadCallback->ioConfigChanged(event, desc, pid);
 }
 
 void PlaybackThread::onWriteReady()
@@ -3212,7 +3212,7 @@
     // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
     Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
     for (size_t i = 0; i < effectChains.size(); i ++) {
-        mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
+        mAfThreadCallback->moveEffectChain_l(effectChains[i]->sessionId(),
             this/* srcThread */, this/* dstThread */);
     }
 
@@ -3642,12 +3642,12 @@
             }
             size_t numSamples = mNormalFrameCount
                     * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
-            status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
+            status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
                     numSamples * sizeof(float),
                     &halInBuffer);
             if (result != OK) return result;
 
-            result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
+            result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
                     isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
                     isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
                     &halOutBuffer);
@@ -3662,10 +3662,10 @@
             // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
             // mPostSpatializerBuffer as output buffer
             // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
-            status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
+            status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
                     mEffectBuffer, mEffectBufferSize, &halInBuffer);
             if (result != OK) return result;
-            result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
+            result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
                     mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
             if (result != OK) return result;
 
@@ -3674,7 +3674,7 @@
             }
         }
     } else {
-        status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
+        status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
                 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
                 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
                 &halInBuffer);
@@ -3690,7 +3690,8 @@
                 size_t numSamples = mNormalFrameCount
                         * (audio_channel_count_from_out_mask(mMixerChannelMask)
                                                              + mHapticChannelCount);
-                const status_t allocateStatus = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
+                const status_t allocateStatus =
+                        mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
                         numSamples * sizeof(float),
                         &halInBuffer);
                 if (allocateStatus != OK) return allocateStatus;
@@ -3882,7 +3883,7 @@
     {
         // Log merge requests are performed during AudioFlinger binder transactions, but
         // that does not cover audio playback. It's requested here for that reason.
-        mAudioFlinger->requestLogMerge();
+        mAfThreadCallback->requestLogMerge();
 
         cpuStats.sample(myName);
 
@@ -3897,12 +3898,12 @@
         if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
             // Here, we try for the AF lock, but do not block on it as the latency
             // is more informational.
-            if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
+            if (mAfThreadCallback->mutex().tryLock() == NO_ERROR) {
                 std::vector<SoftwarePatch> swPatches;
                 double latencyMs = 0.; // not required; initialized for clang-tidy
                 status_t status = INVALID_OPERATION;
                 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
-                if (mAudioFlinger->mPatchPanel->getDownstreamSoftwarePatches(
+                if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
                                 id(), &swPatches) == OK
                         && swPatches.size() > 0) {
                         status = swPatches[0].getLatencyMs_l(&latencyMs);
@@ -3924,7 +3925,7 @@
                     }
                     mDownstreamLatencyStatMs.add(latencyMs);
                 }
-                mAudioFlinger->mLock.unlock();
+                mAfThreadCallback->mutex().unlock();
             }
         } else {
             if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
@@ -4285,7 +4286,7 @@
         unlockEffectChains(effectChains);
 
         if (!metadataUpdate.playbackMetadataUpdate.empty()) {
-            mAudioFlinger->mMelReporter->updateMetadataForCsd(id(),
+            mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
                     metadataUpdate.playbackMetadataUpdate);
         }
 
@@ -4877,14 +4878,14 @@
 
 /* static */
 sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
-        const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
+        const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
         audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
-    return sp<MixerThread>::make(audioFlinger, output, id, systemReady, type, mixerConfig);
+    return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
 }
 
-MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
+MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
         audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
-    :   PlaybackThread(audioFlinger, output, id, type, systemReady, mixerConfig),
+    :   PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
         // mAudioMixer below
         // mFastMixer below
         mBluetoothLatencyModesEnabled(false),
@@ -4894,7 +4895,7 @@
         // mPipeSink below
         // mNormalSink below
 {
-    setMasterBalance(audioFlinger->getMasterBalance_l());
+    setMasterBalance(afThreadCallback->getMasterBalance_l());
     ALOGV("MixerThread() id=%d type=%d", id, type);
     ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
             "mFrameCount=%zu, mNormalFrameCount=%zu",
@@ -5021,7 +5022,7 @@
         state->mColdFutexAddr = &mFastMixerFutex;
         state->mColdGen++;
         state->mDumpState = &mFastMixerDumpState;
-        mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
+        mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
         state->mNBLogWriter = mFastMixerNBLogWriter.get();
         sq->end();
         sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
@@ -5100,7 +5101,7 @@
         }
 #endif
     }
-    mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
+    mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
     delete mAudioMixer;
 }
 
@@ -5157,7 +5158,7 @@
             }
             state->mCommand = FastMixerState::MIX_WRITE;
 #ifdef FAST_THREAD_STATISTICS
-            mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
+            mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
                 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
 #endif
             sq->end();
@@ -5585,7 +5586,7 @@
                 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
                 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
 
-                track->processMuteEvent_l(mAudioFlinger->getOrCreateAudioManager(),
+                track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
                     /*muteState=*/{masterVolume == 0.f,
                                    mStreamTypes[track->streamType()].volume == 0.f,
                                    mStreamTypes[track->streamType()].mute,
@@ -5768,7 +5769,7 @@
                     vrf = GAIN_FLOAT_UNITY;
                 }
 
-                track->processMuteEvent_l(mAudioFlinger->getOrCreateAudioManager(),
+                track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
                     /*muteState=*/{masterVolume == 0.f,
                                    mStreamTypes[track->streamType()].volume == 0.f,
                                    mStreamTypes[track->streamType()].mute,
@@ -6336,7 +6337,7 @@
 }
 
 void MixerThread::onHalLatencyModesChanged_l() {
-    mAudioFlinger->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
+    mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
 }
 
 void MixerThread::setHalLatencyMode_l() {
@@ -6433,20 +6434,20 @@
 
 /* static */
 sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
-        const sp<AudioFlinger>& audioFlinger,
+        const sp<IAfThreadCallback>& afThreadCallback,
         AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
         const audio_offload_info_t& offloadInfo) {
     return sp<DirectOutputThread>::make(
-            audioFlinger, output, id, systemReady, offloadInfo);
+            afThreadCallback, output, id, systemReady, offloadInfo);
 }
 
-DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
+DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
         AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
         const audio_offload_info_t& offloadInfo)
-    :   PlaybackThread(audioFlinger, output, id, type, systemReady)
+    :   PlaybackThread(afThreadCallback, output, id, type, systemReady)
     , mOffloadInfo(offloadInfo)
 {
-    setMasterBalance(audioFlinger->getMasterBalance_l());
+    setMasterBalance(afThreadCallback->getMasterBalance_l());
 }
 
 DirectOutputThread::~DirectOutputThread()
@@ -6509,14 +6510,14 @@
         }
         left *= v;
         right *= v;
-        if (mAudioFlinger->getMode() != AUDIO_MODE_IN_COMMUNICATION
+        if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
                 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
             left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
             right *= mMasterBalanceRight;
         }
     }
 
-    track->processMuteEvent_l(mAudioFlinger->getOrCreateAudioManager(),
+    track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
         /*muteState=*/{mMasterMute,
                        mStreamTypes[track->streamType()].volume == 0.f,
                        mStreamTypes[track->streamType()].mute,
@@ -7100,16 +7101,16 @@
 
 /* static */
 sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
-        const sp<AudioFlinger>& audioFlinger,
+        const sp<IAfThreadCallback>& afThreadCallback,
         AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
         const audio_offload_info_t& offloadInfo) {
-    return sp<OffloadThread>::make(audioFlinger, output, id, systemReady, offloadInfo);
+    return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
 }
 
-OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
+OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
         AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
         const audio_offload_info_t& offloadInfo)
-    :   DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady, offloadInfo),
+    :   DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
         mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
 {
     //FIXME: mStandby should be set to true by ThreadBase constructo
@@ -7432,14 +7433,14 @@
 
 /* static */
 sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
-        const sp<AudioFlinger>& audioFlinger,
+        const sp<IAfThreadCallback>& afThreadCallback,
         IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
-    return sp<DuplicatingThread>::make(audioFlinger, mainThread, id, systemReady);
+    return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
 }
 
-DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
+DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
        IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
-    :   MixerThread(audioFlinger, mainThread->getOutput(), id,
+    :   MixerThread(afThreadCallback, mainThread->getOutput(), id,
                     systemReady, DUPLICATING),
         mWaitTimeMs(UINT_MAX)
 {
@@ -7676,20 +7677,20 @@
 
 /* static */
 sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
-        const sp<AudioFlinger>& audioFlinger,
+        const sp<IAfThreadCallback>& afThreadCallback,
         AudioStreamOut* output,
         audio_io_handle_t id,
         bool systemReady,
         audio_config_base_t* mixerConfig) {
-    return sp<SpatializerThread>::make(audioFlinger, output, id, systemReady, mixerConfig);
+    return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
 }
 
-SpatializerThread::SpatializerThread(const sp<AudioFlinger>& audioFlinger,
+SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
                                                              AudioStreamOut* output,
                                                              audio_io_handle_t id,
                                                              bool systemReady,
                                                              audio_config_base_t *mixerConfig)
-    : MixerThread(audioFlinger, output, id, systemReady, SPATIALIZER, mixerConfig)
+    : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
 {
 }
 
@@ -7780,7 +7781,7 @@
         finalDownMixer.clear();
     } else if (!hasDownMixer) {
         std::vector<effect_descriptor_t> descriptors;
-        status_t status = mAudioFlinger->mEffectsFactoryHal->getDescriptors(
+        status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
                                                         EFFECT_UIID_DOWNMIX, &descriptors);
         if (status != NO_ERROR) {
             return;
@@ -7811,19 +7812,19 @@
 //      Record
 // ----------------------------------------------------------------------------
 
-sp<IAfRecordThread> IAfRecordThread::create(const sp<AudioFlinger>& audioFlinger,
+sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
         AudioStreamIn* input,
         audio_io_handle_t id,
         bool systemReady) {
-    return sp<RecordThread>::make(audioFlinger, input, id, systemReady);
+    return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
 }
 
-RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
+RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
                                          AudioStreamIn *input,
                                          audio_io_handle_t id,
                                          bool systemReady
                                          ) :
-    ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
+    ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
     mInput(input),
     mSource(mInput),
     mActiveTracks(&this->mLocalLog),
@@ -7844,7 +7845,7 @@
     , mBtNrecSuspended(false)
 {
     snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
-    mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
+    mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
 
     if (mInput->audioHwDev != nullptr) {
         mIsMsdDevice = strcmp(
@@ -7952,7 +7953,8 @@
 #ifdef TEE_SINK
         // FIXME
 #endif
-        mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
+        mFastCaptureNBLogWriter =
+                afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
         state->mNBLogWriter = mFastCaptureNBLogWriter.get();
         sq->end();
         sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
@@ -7994,8 +7996,8 @@
         mFastCapture->join();
         mFastCapture.clear();
     }
-    mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
-    mAudioFlinger->unregisterWriter(mNBLogWriter);
+    mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
+    mAfThreadCallback->unregisterWriter(mNBLogWriter);
     free(mRsmpInBuffer);
 }
 
@@ -8223,7 +8225,7 @@
                 }
                 state->mCommand = FastCaptureState::READ_WRITE;
 #if 0   // FIXME
-                mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
+                mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
                         FastThreadDumpState::kSamplingNforLowRamDevice :
                         FastThreadDumpState::kSamplingN);
 #endif
@@ -8842,7 +8844,7 @@
         recordTrack->clearSyncStartEvent();
     } else if (event != AudioSystem::SYNC_EVENT_SAME) {
         recordTrack->synchronizedRecordState().startRecording(
-                mAudioFlinger->createSyncEvent(
+                mAfThreadCallback->createSyncEvent(
                         event, triggerSession,
                         recordTrack->sessionId(), syncStartEventCallback, recordTrack));
     }
@@ -9334,7 +9336,7 @@
     // disable AEC and NS if the device is a BT SCO headset supporting those
     // pre processings
     bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
-                        mAudioFlinger->btNrecIsOff();
+                        mAfThreadCallback->btNrecIsOff();
     if (mBtNrecSuspended.exchange(suspend) != suspend) {
         for (size_t i = 0; i < mEffectChains.size(); i++) {
             setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
@@ -9462,7 +9464,7 @@
         desc = sp<AudioIoDescriptor>::make(mId);
         break;
     }
-    mAudioFlinger->ioConfigChanged(event, desc, pid);
+    mAfThreadCallback->ioConfigChanged(event, desc, pid);
 }
 
 void RecordThread::readInputParameters_l()
@@ -9907,9 +9909,9 @@
 
 
 MmapThread::MmapThread(
-        const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
+        const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
         AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
-    : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
+    : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
       mSessionId(AUDIO_SESSION_NONE),
       mPortId(AUDIO_PORT_HANDLE_NONE),
       mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
@@ -10379,7 +10381,7 @@
         desc = sp<AudioIoDescriptor>::make(mId);
         break;
     }
-    mAudioFlinger->ioConfigChanged(event, desc, pid);
+    mAfThreadCallback->ioConfigChanged(event, desc, pid);
 }
 
 status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
@@ -10665,15 +10667,15 @@
 
 /* static */
 sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
-        const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
+        const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
         AudioHwDevice* hwDev,  AudioStreamOut* output, bool systemReady) {
-    return sp<MmapPlaybackThread>::make(audioFlinger, id, hwDev, output, systemReady);
+    return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
 }
 
 MmapPlaybackThread::MmapPlaybackThread(
-        const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
+        const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
         AudioHwDevice *hwDev,  AudioStreamOut *output, bool systemReady)
-    : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
+    : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
       mStreamType(AUDIO_STREAM_MUSIC),
       mStreamVolume(1.0),
       mStreamMute(false),
@@ -10681,8 +10683,8 @@
 {
     snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
     mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
-    mMasterVolume = audioFlinger->masterVolume_l();
-    mMasterMute = audioFlinger->masterMute_l();
+    mMasterVolume = afThreadCallback->masterVolume_l();
+    mMasterMute = afThreadCallback->masterMute_l();
     if (mAudioHwDev) {
         if (mAudioHwDev->canSetMasterVolume()) {
             mMasterVolume = 1.0;
@@ -10837,7 +10839,7 @@
         }
         for (const sp<IAfMmapTrack>& track : mActiveTracks) {
             track->setMetadataHasChanged();
-            track->processMuteEvent_l(mAudioFlinger->getOrCreateAudioManager(),
+            track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
                 /*muteState=*/{mMasterMute,
                                mStreamVolume == 0.f,
                                mStreamMute,
@@ -10959,15 +10961,15 @@
 
 /* static */
 sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
-        const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
+        const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
         AudioHwDevice* hwDev,  AudioStreamIn* input, bool systemReady) {
-    return sp<MmapCaptureThread>::make(audioFlinger, id, hwDev, input, systemReady);
+    return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
 }
 
 MmapCaptureThread::MmapCaptureThread(
-        const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
+        const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
         AudioHwDevice *hwDev,  AudioStreamIn *input, bool systemReady)
-    : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
+    : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
       mInput(input)
 {
     snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
@@ -11077,14 +11079,14 @@
 
 /* static */
 sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
-        const sp<AudioFlinger>& audioflinger,
+        const sp<IAfThreadCallback>& afThreadCallback,
         AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
-    return sp<BitPerfectThread>::make(audioflinger, output, id, systemReady);
+    return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
 }
 
-BitPerfectThread::BitPerfectThread(const sp<AudioFlinger> &audioflinger,
+BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
         AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
-        : MixerThread(audioflinger, output, id, systemReady, BIT_PERFECT) {}
+        : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
 
 PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
         Vector<sp<IAfTrack>>* tracksToRemove) {
diff --git a/services/audioflinger/Threads.h b/services/audioflinger/Threads.h
index 77776a0..87f4648 100644
--- a/services/audioflinger/Threads.h
+++ b/services/audioflinger/Threads.h
@@ -25,9 +25,9 @@
 public:
     static const char *threadTypeToString(type_t type);
 
-    AudioFlinger* audioFlinger() const final { return mAudioFlinger.get(); }
+    IAfThreadCallback* afThreadCallback() const final { return mAfThreadCallback.get(); }
 
-    ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
+    ThreadBase(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
                type_t type, bool systemReady, bool isOut);
     ~ThreadBase() override;
 
@@ -582,7 +582,7 @@
                 // Used by parameters, config events, addTrack_l, exit
                 Condition               mWaitWorkCV;
 
-                const sp<AudioFlinger>  mAudioFlinger;
+                const sp<IAfThreadCallback>  mAfThreadCallback;
                 ThreadMetrics           mThreadMetrics;
                 const bool              mIsOut;
 
@@ -806,7 +806,7 @@
     // for initial conditions or large delays.
     static const nsecs_t kMaxNextBufferDelayNs = 100000000;
 
-    PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
+    PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
                    audio_io_handle_t id, type_t type, bool systemReady,
                    audio_config_base_t *mixerConfig = nullptr);
     ~PlaybackThread() override;
@@ -1436,7 +1436,7 @@
 class MixerThread : public PlaybackThread,
                     public StreamOutHalInterfaceLatencyModeCallback  {
 public:
-    MixerThread(const sp<AudioFlinger>& audioFlinger,
+    MixerThread(const sp<IAfThreadCallback>& afThreadCallback,
                 AudioStreamOut* output,
                 audio_io_handle_t id,
                 bool systemReady,
@@ -1566,10 +1566,10 @@
         return sp<IAfDirectOutputThread>::fromExisting(this);
     }
 
-    DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
+    DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
                        audio_io_handle_t id, bool systemReady,
                        const audio_offload_info_t& offloadInfo)
-        : DirectOutputThread(audioFlinger, output, id, DIRECT, systemReady, offloadInfo) { }
+        : DirectOutputThread(afThreadCallback, output, id, DIRECT, systemReady, offloadInfo) { }
 
     virtual                 ~DirectOutputThread();
 
@@ -1606,7 +1606,7 @@
     audioflinger::MonotonicFrameCounter mMonotonicFrameCounter;  // for VolumeShaper
     bool mVolumeShaperActive = false;
 
-    DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
+    DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
                        audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
                        const audio_offload_info_t& offloadInfo);
     void processVolume_l(IAfTrack *track, bool lastTrack);
@@ -1647,7 +1647,7 @@
 class OffloadThread : public DirectOutputThread {
 public:
 
-    OffloadThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
+    OffloadThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
                   audio_io_handle_t id, bool systemReady,
                   const audio_offload_info_t& offloadInfo);
     virtual                 ~OffloadThread() {};
@@ -1705,7 +1705,8 @@
 
 class DuplicatingThread : public MixerThread, public IAfDuplicatingThread {
 public:
-    DuplicatingThread(const sp<AudioFlinger>& audioFlinger, IAfPlaybackThread* mainThread,
+    DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
+            IAfPlaybackThread* mainThread,
                       audio_io_handle_t id, bool systemReady);
     ~DuplicatingThread() override;
 
@@ -1767,7 +1768,7 @@
 
 class SpatializerThread : public MixerThread {
 public:
-    SpatializerThread(const sp<AudioFlinger>& audioFlinger,
+    SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
                            AudioStreamOut* output,
                            audio_io_handle_t id,
                            bool systemReady,
@@ -1800,7 +1801,7 @@
         return sp<IAfRecordThread>::fromExisting(this);
     }
 
-            RecordThread(const sp<AudioFlinger>& audioFlinger,
+            RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
                     AudioStreamIn *input,
                     audio_io_handle_t id,
                     bool systemReady
@@ -2027,7 +2028,7 @@
 class MmapThread : public ThreadBase, public virtual IAfMmapThread
 {
  public:
-    MmapThread(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
+    MmapThread(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
                AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady,
                bool isOut);
 
@@ -2152,7 +2153,7 @@
 class MmapPlaybackThread : public MmapThread, public IAfMmapPlaybackThread,
         public virtual VolumeInterface {
 public:
-    MmapPlaybackThread(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
+    MmapPlaybackThread(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
                        AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady);
 
     sp<IAfMmapPlaybackThread> asIAfMmapPlaybackThread() final {
@@ -2216,7 +2217,7 @@
 class MmapCaptureThread : public MmapThread, public IAfMmapCaptureThread
 {
 public:
-    MmapCaptureThread(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
+    MmapCaptureThread(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
                       AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady);
 
     sp<IAfMmapCaptureThread> asIAfMmapCaptureThread() final {
@@ -2246,7 +2247,7 @@
 
 class BitPerfectThread : public MixerThread {
 public:
-    BitPerfectThread(const sp<AudioFlinger>& audioflinger, AudioStreamOut *output,
+    BitPerfectThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut *output,
                      audio_io_handle_t id, bool systemReady);
 
 protected:
diff --git a/services/audioflinger/Tracks.cpp b/services/audioflinger/Tracks.cpp
index 3cfb87d..ea56797 100644
--- a/services/audioflinger/Tracks.cpp
+++ b/services/audioflinger/Tracks.cpp
@@ -1168,10 +1168,10 @@
     const sp<IAfThreadBase> thread = mThread.promote();
     if (thread != 0) {
         if (isOffloaded()) {
-            Mutex::Autolock _laf(thread->audioFlinger()->mLock);
+            Mutex::Autolock _laf(thread->afThreadCallback()->mutex());
             Mutex::Autolock _lth(thread->mutex());
             sp<IAfEffectChain> ec = thread->getEffectChain_l(mSessionId);
-            if (thread->audioFlinger()->isNonOffloadableGlobalEffectEnabled_l() ||
+            if (thread->afThreadCallback()->isNonOffloadableGlobalEffectEnabled_l() ||
                     (ec != 0 && ec->isNonOffloadableEnabled())) {
                 invalidate();
                 return PERMISSION_DENIED;
@@ -1276,7 +1276,8 @@
         forEachTeePatchTrack([](auto patchTrack) { patchTrack->start(); });
 
         // send format to AudioManager for playback activity monitoring
-        const sp<IAudioManager> audioManager = thread->audioFlinger()->getOrCreateAudioManager();
+        const sp<IAudioManager> audioManager =
+                thread->afThreadCallback()->getOrCreateAudioManager();
         if (audioManager && mPortId != AUDIO_PORT_HANDLE_NONE) {
             std::unique_ptr<os::PersistableBundle> bundle =
                     std::make_unique<os::PersistableBundle>();