AudioFlinger: Add more Thread interfaces

Add interfaces

IAfDirectOutputThread
IAfDuplicatingThread
IAfRecordThread

Test: atest audiorecord_tests audiotrack_tests audiorouting_tests trackplayerbase_tests audiosystem_tests
Test: atest AudioTrackTest AudioRecordTest
Test: YouTube Camera
Bug: 288339104
Bug: 289233517
Merged-In: Ibd46b7de4c4264294b645d0df2a69825513a1426
Change-Id: Ibd46b7de4c4264294b645d0df2a69825513a1426
diff --git a/services/audioflinger/Tracks.cpp b/services/audioflinger/Tracks.cpp
index 093c14a..b11479f 100644
--- a/services/audioflinger/Tracks.cpp
+++ b/services/audioflinger/Tracks.cpp
@@ -81,7 +81,7 @@
 
 // TrackBase constructor must be called with AudioFlinger::mLock held
 TrackBase::TrackBase(
-            AudioFlinger::ThreadBase *thread,
+        IAfThreadBase *thread,
             const sp<Client>& client,
             const audio_attributes_t& attr,
             uint32_t sampleRate,
@@ -315,7 +315,7 @@
 }
 
 PatchTrackBase::PatchTrackBase(const sp<ClientProxy>& proxy,
-        const AudioFlinger::ThreadBase& thread, const Timeout& timeout)
+        const IAfThreadBase& thread, const Timeout& timeout)
     : mProxy(proxy)
 {
     if (timeout) {
@@ -559,7 +559,7 @@
 
 // static
 sp<OpPlayAudioMonitor> OpPlayAudioMonitor::createIfNeeded(
-            AudioFlinger::ThreadBase* thread,
+            IAfThreadBase* thread,
             const AttributionSourceState& attributionSource, const audio_attributes_t& attr, int id,
             audio_stream_type_t streamType)
 {
@@ -589,11 +589,10 @@
     return sp<OpPlayAudioMonitor>::make(thread, attributionSource, attr.usage, id, uid);
 }
 
-OpPlayAudioMonitor::OpPlayAudioMonitor(
-        AudioFlinger::ThreadBase* thread,
-        const AttributionSourceState& attributionSource,
-        audio_usage_t usage, int id, uid_t uid)
-    : mThread(wp<AudioFlinger::ThreadBase>::fromExisting(thread)),
+OpPlayAudioMonitor::OpPlayAudioMonitor(IAfThreadBase* thread,
+                                       const AttributionSourceState& attributionSource,
+                                       audio_usage_t usage, int id, uid_t uid)
+    : mThread(wp<IAfThreadBase>::fromExisting(thread)),
       mHasOpPlayAudio(true),
       mAttributionSource(attributionSource),
       mUsage((int32_t)usage),
@@ -643,7 +642,7 @@
             auto thread = mThread.promote();
             if (thread != nullptr && thread->type() == AudioFlinger::ThreadBase::OFFLOAD) {
                 // Wake up Thread if offloaded, otherwise it may be several seconds for update.
-                Mutex::Autolock _l(thread->mLock);
+                Mutex::Autolock _l(thread->mutex());
                 thread->broadcast_l();
             }
         }
@@ -680,8 +679,8 @@
 #define LOG_TAG "AF::Track"
 
 /* static */
-sp<IAfTrack> IAfTrack::create( // TODO(b/288339104) void*
-        void * /* AudioFlinger::PlaybackThread */ thread,
+sp<IAfTrack> IAfTrack::create(
+        IAfPlaybackThread* thread,
         const sp<Client>& client,
         audio_stream_type_t streamType,
         const audio_attributes_t& attr,
@@ -704,7 +703,7 @@
         float speed,
         bool isSpatialized,
         bool isBitPerfect) {
-    return sp<Track>::make(reinterpret_cast<AudioFlinger::PlaybackThread*>(thread),
+    return sp<Track>::make(thread,
             client,
             streamType,
             attr,
@@ -729,7 +728,7 @@
 
 // Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
 Track::Track(
-            AudioFlinger::PlaybackThread *thread,
+        IAfPlaybackThread* thread,
             const sp<Client>& client,
             audio_stream_type_t streamType,
             const audio_attributes_t& attr,
@@ -820,15 +819,15 @@
         // race with setSyncEvent(). However, if we call it, we cannot properly start
         // static fast tracks (SoundPool) immediately after stopping.
         //mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
-        ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
-        int i = __builtin_ctz(thread->mFastTrackAvailMask);
+        ALOG_ASSERT(thread->fastTrackAvailMask_l() != 0);
+        const int i = __builtin_ctz(thread->fastTrackAvailMask_l());
         ALOG_ASSERT(0 < i && i < (int)FastMixerState::sMaxFastTracks);
         // FIXME This is too eager.  We allocate a fast track index before the
         //       fast track becomes active.  Since fast tracks are a scarce resource,
         //       this means we are potentially denying other more important fast tracks from
         //       being created.  It would be better to allocate the index dynamically.
         mFastIndex = i;
-        thread->mFastTrackAvailMask &= ~(1 << i);
+        thread->fastTrackAvailMask_l() &= ~(1 << i);
     }
 
     mServerLatencySupported = checkServerLatencySupported(format, flags);
@@ -888,10 +887,10 @@
     sp<Track> keep(this);
     { // scope for mLock
         bool wasActive = false;
-        sp<AudioFlinger::ThreadBase> thread = mThread.promote();
+        const sp<IAfThreadBase> thread = mThread.promote();
         if (thread != 0) {
-            Mutex::Autolock _l(thread->mLock);
-            auto* const playbackThread = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
+            Mutex::Autolock _l(thread->mutex());
+            auto* const playbackThread = thread->asIAfPlaybackThread().get();
             wasActive = playbackThread->destroyTrack_l(this);
         }
         if (isExternalTrack() && !wasActive) {
@@ -1167,19 +1166,19 @@
     ALOGV("%s(%d): calling pid %d session %d",
             __func__, mId, IPCThreadState::self()->getCallingPid(), mSessionId);
 
-    sp<AudioFlinger::ThreadBase> thread = mThread.promote();
+    const sp<IAfThreadBase> thread = mThread.promote();
     if (thread != 0) {
         if (isOffloaded()) {
-            Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
-            Mutex::Autolock _lth(thread->mLock);
+            Mutex::Autolock _laf(thread->audioFlinger()->mLock);
+            Mutex::Autolock _lth(thread->mutex());
             sp<IAfEffectChain> ec = thread->getEffectChain_l(mSessionId);
-            if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
+            if (thread->audioFlinger()->isNonOffloadableGlobalEffectEnabled_l() ||
                     (ec != 0 && ec->isNonOffloadableEnabled())) {
                 invalidate();
                 return PERMISSION_DENIED;
             }
         }
-        Mutex::Autolock _lth(thread->mLock);
+        Mutex::Autolock _lth(thread->mutex());
         track_state state = mState;
         // here the track could be either new, or restarted
         // in both cases "unstop" the track
@@ -1211,7 +1210,7 @@
                     __func__, mId, (int)mThreadIoHandle);
         }
 
-        auto* const playbackThread = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
+        auto* const playbackThread = thread->asIAfPlaybackThread().get();
 
         // states to reset position info for pcm tracks
         if (audio_is_linear_pcm(mFormat)
@@ -1278,7 +1277,7 @@
         forEachTeePatchTrack([](auto patchTrack) { patchTrack->start(); });
 
         // send format to AudioManager for playback activity monitoring
-        sp<IAudioManager> audioManager = thread->mAudioFlinger->getOrCreateAudioManager();
+        const sp<IAudioManager> audioManager = thread->audioFlinger()->getOrCreateAudioManager();
         if (audioManager && mPortId != AUDIO_PORT_HANDLE_NONE) {
             std::unique_ptr<os::PersistableBundle> bundle =
                     std::make_unique<os::PersistableBundle>();
@@ -1300,14 +1299,14 @@
 void Track::stop()
 {
     ALOGV("%s(%d): calling pid %d", __func__, mId, IPCThreadState::self()->getCallingPid());
-    sp<AudioFlinger::ThreadBase> thread = mThread.promote();
+    const sp<IAfThreadBase> thread = mThread.promote();
     if (thread != 0) {
-        Mutex::Autolock _l(thread->mLock);
+        Mutex::Autolock _l(thread->mutex());
         track_state state = mState;
         if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
             // If the track is not active (PAUSED and buffers full), flush buffers
-            auto* const playbackThread = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
-            if (playbackThread->mActiveTracks.indexOf(this) < 0) {
+            auto* const playbackThread = thread->asIAfPlaybackThread().get();
+            if (!playbackThread->isTrackActive(this)) {
                 reset();
                 mState = STOPPED;
             } else if (!isFastTrack() && !isOffloaded() && !isDirect()) {
@@ -1319,7 +1318,7 @@
                 // move to STOPPING_2 when drain completes and then STOPPED
                 mState = STOPPING_1;
                 if (isOffloaded()) {
-                    mRetryCount = AudioFlinger::PlaybackThread::kMaxTrackStopRetriesOffload;
+                    mRetryCount = IAfPlaybackThread::kMaxTrackStopRetriesOffload;
                 }
             }
             playbackThread->broadcast_l();
@@ -1333,10 +1332,10 @@
 void Track::pause()
 {
     ALOGV("%s(%d): calling pid %d", __func__, mId, IPCThreadState::self()->getCallingPid());
-    sp<AudioFlinger::ThreadBase> thread = mThread.promote();
+    const sp<IAfThreadBase> thread = mThread.promote();
     if (thread != 0) {
-        Mutex::Autolock _l(thread->mLock);
-        auto* const playbackThread = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
+        Mutex::Autolock _l(thread->mutex());
+        auto* const playbackThread = thread->asIAfPlaybackThread().get();
         switch (mState) {
         case STOPPING_1:
         case STOPPING_2:
@@ -1370,15 +1369,15 @@
 void Track::flush()
 {
     ALOGV("%s(%d)", __func__, mId);
-    sp<AudioFlinger::ThreadBase> thread = mThread.promote();
+    const sp<IAfThreadBase> thread = mThread.promote();
     if (thread != 0) {
-        Mutex::Autolock _l(thread->mLock);
-        auto* const playbackThread = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
+        Mutex::Autolock _l(thread->mutex());
+        auto* const playbackThread = thread->asIAfPlaybackThread().get();
 
         // Flush the ring buffer now if the track is not active in the PlaybackThread.
         // Otherwise the flush would not be done until the track is resumed.
         // Requires FastTrack removal be BLOCK_UNTIL_ACKED
-        if (playbackThread->mActiveTracks.indexOf(this) < 0) {
+        if (!playbackThread->isTrackActive(this)) {
             (void)mServerProxy->flushBufferIfNeeded();
         }
 
@@ -1417,7 +1416,7 @@
             if (isDirect()) {
                 mFlushHwPending = true;
             }
-            if (playbackThread->mActiveTracks.indexOf(this) < 0) {
+            if (!playbackThread->isTrackActive(this)) {
                 reset();
             }
         }
@@ -1467,12 +1466,12 @@
 
 status_t Track::setParameters(const String8& keyValuePairs)
 {
-    sp<AudioFlinger::ThreadBase> thread = mThread.promote();
+    const sp<IAfThreadBase> thread = mThread.promote();
     if (thread == 0) {
         ALOGE("%s(%d): thread is dead", __func__, mId);
         return FAILED_TRANSACTION;
-    } else if ((thread->type() == AudioFlinger::ThreadBase::DIRECT) ||
-                    (thread->type() == AudioFlinger::ThreadBase::OFFLOAD)) {
+    } else if (thread->type() == IAfThreadBase::DIRECT
+            || thread->type() == IAfThreadBase::OFFLOAD) {
         return thread->setParameters(keyValuePairs);
     } else {
         return PERMISSION_DENIED;
@@ -1481,13 +1480,13 @@
 
 status_t Track::selectPresentation(int presentationId,
         int programId) {
-    sp<AudioFlinger::ThreadBase> thread = mThread.promote();
+    const sp<IAfThreadBase> thread = mThread.promote();
     if (thread == 0) {
         ALOGE("thread is dead");
         return FAILED_TRANSACTION;
-    } else if ((thread->type() == AudioFlinger::ThreadBase::DIRECT)
-            || (thread->type() == AudioFlinger::ThreadBase::OFFLOAD)) {
-        auto directOutputThread = static_cast<AudioFlinger::DirectOutputThread*>(thread.get());
+    } else if (thread->type() == IAfThreadBase::DIRECT
+            || thread->type() == IAfThreadBase::OFFLOAD) {
+        auto directOutputThread = thread->asIAfDirectOutputThread().get();
         return directOutputThread->selectPresentation(presentationId, programId);
     }
     return INVALID_OPERATION;
@@ -1501,9 +1500,9 @@
 
     if (isOffloadedOrDirect()) {
         // Signal thread to fetch new volume.
-        sp<AudioFlinger::ThreadBase> thread = mThread.promote();
+        const sp<IAfThreadBase> thread = mThread.promote();
         if (thread != 0) {
-            Mutex::Autolock _l(thread->mLock);
+            Mutex::Autolock _l(thread->mutex());
             thread->broadcast_l();
         }
     }
@@ -1662,26 +1661,26 @@
     if (!isOffloaded() && !isDirect()) {
         return INVALID_OPERATION; // normal tracks handled through SSQ
     }
-    sp<AudioFlinger::ThreadBase> thread = mThread.promote();
+    const sp<IAfThreadBase> thread = mThread.promote();
     if (thread == 0) {
         return INVALID_OPERATION;
     }
 
-    Mutex::Autolock _l(thread->mLock);
-    auto* const playbackThread = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
+    Mutex::Autolock _l(thread->mutex());
+    auto* const playbackThread = thread->asIAfPlaybackThread().get();
     return playbackThread->getTimestamp_l(timestamp);
 }
 
 status_t Track::attachAuxEffect(int EffectId)
 {
-    sp<AudioFlinger::ThreadBase> thread = mThread.promote();
+    const sp<IAfThreadBase> thread = mThread.promote();
     if (thread == nullptr) {
         return DEAD_OBJECT;
     }
 
-    auto dstThread = sp<AudioFlinger::PlaybackThread>::cast(thread);
+    auto dstThread = thread->asIAfPlaybackThread();
     // srcThread is initialized by call to moveAuxEffectToIo()
-    sp<AudioFlinger::PlaybackThread> srcThread;
+    sp<IAfPlaybackThread> srcThread;
     sp<AudioFlinger> af = mClient->audioFlinger();
     status_t status = af->moveAuxEffectToIo(EffectId, dstThread, &srcThread);
 
@@ -1867,10 +1866,10 @@
 
 void Track::signal()
 {
-    sp<AudioFlinger::ThreadBase> thread = mThread.promote();
+    const sp<IAfThreadBase> thread = mThread.promote();
     if (thread != 0) {
-        auto* const t = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
-        Mutex::Autolock _l(t->mLock);
+        auto* const t = thread->asIAfPlaybackThread().get();
+        Mutex::Autolock _l(t->mutex());
         t->broadcast_l();
     }
 }
@@ -1879,11 +1878,11 @@
 {
     status_t status = INVALID_OPERATION;
     if (isOffloadedOrDirect()) {
-        sp<AudioFlinger::ThreadBase> thread = mThread.promote();
+        const sp<IAfThreadBase> thread = mThread.promote();
         if (thread != nullptr) {
-            auto* const t = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
-            Mutex::Autolock _l(t->mLock);
-            status = t->mOutput->stream->getDualMonoMode(mode);
+            auto* const t = thread->asIAfPlaybackThread().get();
+            Mutex::Autolock _l(t->mutex());
+            status = t->getOutput_l()->stream->getDualMonoMode(mode);
             ALOGD_IF((status == NO_ERROR) && (mDualMonoMode != *mode),
                     "%s: mode %d inconsistent", __func__, mDualMonoMode);
         }
@@ -1895,11 +1894,11 @@
 {
     status_t status = INVALID_OPERATION;
     if (isOffloadedOrDirect()) {
-        sp<AudioFlinger::ThreadBase> thread = mThread.promote();
+        const sp<IAfThreadBase> thread = mThread.promote();
         if (thread != nullptr) {
-            auto* const t = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
-            Mutex::Autolock lock(t->mLock);
-            status = t->mOutput->stream->setDualMonoMode(mode);
+            auto* const t = thread->asIAfPlaybackThread().get();
+            Mutex::Autolock lock(t->mutex());
+            status = t->getOutput_l()->stream->setDualMonoMode(mode);
             if (status == NO_ERROR) {
                 mDualMonoMode = mode;
             }
@@ -1912,11 +1911,11 @@
 {
     status_t status = INVALID_OPERATION;
     if (isOffloadedOrDirect()) {
-        sp<AudioFlinger::ThreadBase> thread = mThread.promote();
+        sp<IAfThreadBase> thread = mThread.promote();
         if (thread != nullptr) {
-            auto* const t = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
-            Mutex::Autolock lock(t->mLock);
-            status = t->mOutput->stream->getAudioDescriptionMixLevel(leveldB);
+            auto* const t = thread->asIAfPlaybackThread().get();
+            Mutex::Autolock lock(t->mutex());
+            status = t->getOutput_l()->stream->getAudioDescriptionMixLevel(leveldB);
             ALOGD_IF((status == NO_ERROR) && (mAudioDescriptionMixLevel != *leveldB),
                     "%s: level %.3f inconsistent", __func__, mAudioDescriptionMixLevel);
         }
@@ -1928,11 +1927,11 @@
 {
     status_t status = INVALID_OPERATION;
     if (isOffloadedOrDirect()) {
-        sp<AudioFlinger::ThreadBase> thread = mThread.promote();
+        const sp<IAfThreadBase> thread = mThread.promote();
         if (thread != nullptr) {
-            auto* const t = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
-            Mutex::Autolock lock(t->mLock);
-            status = t->mOutput->stream->setAudioDescriptionMixLevel(leveldB);
+            auto* const t = thread->asIAfPlaybackThread().get();
+            Mutex::Autolock lock(t->mutex());
+            status = t->getOutput_l()->stream->setAudioDescriptionMixLevel(leveldB);
             if (status == NO_ERROR) {
                 mAudioDescriptionMixLevel = leveldB;
             }
@@ -1946,11 +1945,11 @@
 {
     status_t status = INVALID_OPERATION;
     if (isOffloadedOrDirect()) {
-        sp<AudioFlinger::ThreadBase> thread = mThread.promote();
+        const sp<IAfThreadBase> thread = mThread.promote();
         if (thread != nullptr) {
-            auto* const t = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
-            Mutex::Autolock lock(t->mLock);
-            status = t->mOutput->stream->getPlaybackRateParameters(playbackRate);
+            auto* const t = thread->asIAfPlaybackThread().get();
+            Mutex::Autolock lock(t->mutex());
+            status = t->getOutput_l()->stream->getPlaybackRateParameters(playbackRate);
             ALOGD_IF((status == NO_ERROR) &&
                     !isAudioPlaybackRateEqual(mPlaybackRateParameters, *playbackRate),
                     "%s: playbackRate inconsistent", __func__);
@@ -1964,11 +1963,11 @@
 {
     status_t status = INVALID_OPERATION;
     if (isOffloadedOrDirect()) {
-        sp<AudioFlinger::ThreadBase> thread = mThread.promote();
+        const sp<IAfThreadBase> thread = mThread.promote();
         if (thread != nullptr) {
-            auto* const t = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
-            Mutex::Autolock lock(t->mLock);
-            status = t->mOutput->stream->setPlaybackRateParameters(playbackRate);
+            auto* const t = thread->asIAfPlaybackThread().get();
+            Mutex::Autolock lock(t->mutex());
+            status = t->getOutput_l()->stream->setPlaybackRateParameters(playbackRate);
             if (status == NO_ERROR) {
                 mPlaybackRateParameters = playbackRate;
             }
@@ -2087,13 +2086,13 @@
 }
 
 bool Track::AudioVibrationController::setMute(bool muted) {
-    sp<AudioFlinger::ThreadBase> thread = mTrack->mThread.promote();
+    const sp<IAfThreadBase> thread = mTrack->mThread.promote();
     if (thread != 0) {
         // Lock for updating mHapticPlaybackEnabled.
-        Mutex::Autolock _l(thread->mLock);
-        auto* const playbackThread = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
+        Mutex::Autolock _l(thread->mutex());
+        auto* const playbackThread = thread->asIAfPlaybackThread().get();
         if ((mTrack->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
-                && playbackThread->mHapticChannelCount > 0) {
+                && playbackThread->hapticChannelCount() > 0) {
             ALOGD("%s, haptic playback was %s for track %d",
                     __func__, muted ? "muted" : "unmuted", mTrack->id());
             mTrack->setHapticPlaybackEnabled(!muted);
@@ -2120,17 +2119,17 @@
 #define LOG_TAG "AF::OutputTrack"
 
 /* static */
-sp<IAfOutputTrack> IAfOutputTrack::create(  // TODO(b/288339104) void*
-        void* /* AudioFlinger::PlaybackThread */ playbackThread,
-        void* /* AudioFlinger::DuplicatingThread */ sourceThread,
+sp<IAfOutputTrack> IAfOutputTrack::create(
+        IAfPlaybackThread* playbackThread,
+        IAfDuplicatingThread* sourceThread,
         uint32_t sampleRate,
         audio_format_t format,
         audio_channel_mask_t channelMask,
         size_t frameCount,
         const AttributionSourceState& attributionSource) {
     return sp<OutputTrack>::make(
-            reinterpret_cast<AudioFlinger::PlaybackThread*>(playbackThread),
-            reinterpret_cast<AudioFlinger::DuplicatingThread*>(sourceThread),
+            playbackThread,
+            sourceThread,
             sampleRate,
             format,
             channelMask,
@@ -2139,8 +2138,8 @@
 }
 
 OutputTrack::OutputTrack(
-            AudioFlinger::PlaybackThread *playbackThread,
-            AudioFlinger::DuplicatingThread *sourceThread,
+            IAfPlaybackThread* playbackThread,
+            IAfDuplicatingThread* sourceThread,
             uint32_t sampleRate,
             audio_format_t format,
             audio_channel_mask_t channelMask,
@@ -2157,7 +2156,7 @@
 
     if (mCblk != NULL) {
         mOutBuffer.frameCount = 0;
-        playbackThread->mTracks.add(this);
+        playbackThread->addOutputTrack_l(this);
         ALOGV("%s(): mCblk %p, mBuffer %p, "
                 "frameCount %zu, mChannelMask 0x%08x",
                 __func__, mCblk, mBuffer,
@@ -2205,7 +2204,7 @@
 ssize_t OutputTrack::write(void* data, uint32_t frames)
 {
     if (!mActive && frames != 0) {
-        sp<AudioFlinger::ThreadBase> thread = mThread.promote();
+        const sp<IAfThreadBase> thread = mThread.promote();
         if (thread != nullptr && thread->inStandby()) {
             // preload one silent buffer to trigger mixer on start()
             ClientProxy::Buffer buf { .mFrameCount = mClientProxy->getStartThresholdInFrames() };
@@ -2224,7 +2223,7 @@
             // If another OutputTrack has already started it can underrun but this is OK
             // as only silence has been played so far and the retry count is very high on
             // OutputTrack.
-            auto* const pt = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
+            auto* const pt = thread->asIAfPlaybackThread().get();
             if (!pt->waitForHalStart()) {
                 ALOGW("%s(%d): timeout waiting for thread to exit standby", __func__, mId);
                 stop();
@@ -2313,7 +2312,7 @@
 
     // If we could not write all frames, allocate a buffer and queue it for next time.
     if (inBuffer.frameCount) {
-        sp<AudioFlinger::ThreadBase> thread = mThread.promote();
+        const sp<IAfThreadBase> thread = mThread.promote();
         if (thread != nullptr && !thread->inStandby()) {
             queueBuffer(inBuffer);
         }
@@ -2406,7 +2405,7 @@
 
 /* static */
 sp<IAfPatchTrack> IAfPatchTrack::create(
-        void* /* PlaybackThread */ playbackThread, // TODO(b/288339104)
+        IAfPlaybackThread* playbackThread,
         audio_stream_type_t streamType,
         uint32_t sampleRate,
         audio_channel_mask_t channelMask,
@@ -2422,7 +2421,7 @@
                                          *  even if it might glitch. */)
 {
     return sp<PatchTrack>::make(
-            reinterpret_cast<AudioFlinger::PlaybackThread*>(playbackThread),
+            playbackThread,
             streamType,
             sampleRate,
             channelMask,
@@ -2435,7 +2434,7 @@
             frameCountToBeReady);
 }
 
-PatchTrack::PatchTrack(AudioFlinger::PlaybackThread *playbackThread,
+PatchTrack::PatchTrack(IAfPlaybackThread* playbackThread,
                                                      audio_stream_type_t streamType,
                                                      uint32_t sampleRate,
                                                      audio_channel_mask_t channelMask,
@@ -2553,9 +2552,9 @@
     if (mFillingStatus == FS_ACTIVE
             && audio_is_linear_pcm(mFormat)
             && !isOffloadedOrDirect()) {
-        if (sp<AudioFlinger::ThreadBase> thread = mThread.promote();
+        if (const sp<IAfThreadBase> thread = mThread.promote();
             thread != 0) {
-            auto* const playbackThread = static_cast<AudioFlinger::PlaybackThread*>(thread.get());
+            auto* const playbackThread = thread->asIAfPlaybackThread().get();
             const size_t frameCount = playbackThread->frameCount() * sampleRate()
                     / playbackThread->sampleRate();
             if (framesReady() < frameCount) {
@@ -2671,7 +2670,7 @@
 
 
 /* static */ // TODO(b/288339104)
-sp<IAfRecordTrack> IAfRecordTrack::create(void* /*AudioFlinger::RecordThread */ thread,
+sp<IAfRecordTrack> IAfRecordTrack::create(IAfRecordThread* thread,
         const sp<Client>& client,
         const audio_attributes_t& attr,
         uint32_t sampleRate,
@@ -2689,7 +2688,7 @@
         int32_t startFrames)
 {
     return sp<RecordTrack>::make(
-        reinterpret_cast<AudioFlinger::RecordThread*>(thread),
+        thread,
         client,
         attr,
         sampleRate,
@@ -2709,7 +2708,7 @@
 
 // RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
 RecordTrack::RecordTrack(
-            AudioFlinger::RecordThread* thread,
+            IAfRecordThread* thread,
             const sp<Client>& client,
             const audio_attributes_t& attr,
             uint32_t sampleRate,
@@ -2748,7 +2747,7 @@
 
     if (!isDirect()) {
         mRecordBufferConverter = new RecordBufferConverter(
-                thread->mChannelMask, thread->mFormat, thread->mSampleRate,
+                thread->channelMask(), thread->format(), thread->sampleRate(),
                 channelMask, format, sampleRate);
         // Check if the RecordBufferConverter construction was successful.
         // If not, don't continue with construction.
@@ -2768,8 +2767,8 @@
     mResamplerBufferProvider = new ResamplerBufferProvider(this);
 
     if (flags & AUDIO_INPUT_FLAG_FAST) {
-        ALOG_ASSERT(thread->mFastTrackAvail);
-        thread->mFastTrackAvail = false;
+        ALOG_ASSERT(thread->fastTrackAvailable());
+        thread->setFastTrackAvailable(false);
     } else {
         // TODO: only Normal Record has timestamps (Fast Record does not).
         mServerLatencySupported = checkServerLatencySupported(mFormat, flags);
@@ -2818,9 +2817,9 @@
 status_t RecordTrack::start(AudioSystem::sync_event_t event,
                                                         audio_session_t triggerSession)
 {
-    sp<AudioFlinger::ThreadBase> thread = mThread.promote();
+    const sp<IAfThreadBase> thread = mThread.promote();
     if (thread != 0) {
-        auto* const recordThread = static_cast<AudioFlinger::RecordThread*>(thread.get());
+        auto* const recordThread = thread->asIAfRecordThread().get();
         return recordThread->start(this, event, triggerSession);
     } else {
         ALOGW("%s track %d: thread was destroyed", __func__, portId());
@@ -2830,9 +2829,9 @@
 
 void RecordTrack::stop()
 {
-    sp<AudioFlinger::ThreadBase> thread = mThread.promote();
+    const sp<IAfThreadBase> thread = mThread.promote();
     if (thread != 0) {
-        auto* const recordThread = static_cast<AudioFlinger::RecordThread*>(thread.get());
+        auto* const recordThread = thread->asIAfRecordThread().get();
         if (recordThread->stop(this) && isExternalTrack()) {
             AudioSystem::stopInput(mPortId);
         }
@@ -2845,10 +2844,10 @@
     sp<RecordTrack> keep(this);
     {
         track_state priorState = mState;
-        sp<AudioFlinger::ThreadBase> thread = mThread.promote();
+        const sp<IAfThreadBase> thread = mThread.promote();
         if (thread != 0) {
-            Mutex::Autolock _l(thread->mLock);
-            auto* const recordThread = static_cast<AudioFlinger::RecordThread*>(thread.get());
+            Mutex::Autolock _l(thread->mutex());
+            auto* const recordThread = thread->asIAfRecordThread().get();
             priorState = mState;
             if (!mSharedAudioPackageName.empty()) {
                 recordThread->resetAudioHistory_l();
@@ -2942,11 +2941,11 @@
         const sp<audioflinger::SyncEvent>& event)
 {
     size_t framesToDrop = 0;
-    sp<AudioFlinger::ThreadBase> threadBase = mThread.promote();
+    const sp<IAfThreadBase> threadBase = mThread.promote();
     if (threadBase != 0) {
         // TODO: use actual buffer filling status instead of 2 buffers when info is available
         // from audio HAL
-        framesToDrop = threadBase->mFrameCount * 2;
+        framesToDrop = threadBase->frameCount() * 2;
     }
 
     mSynchronizedRecordState.onPlaybackFinished(event, framesToDrop);
@@ -3000,9 +2999,9 @@
 status_t RecordTrack::getActiveMicrophones(
         std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
 {
-    sp<AudioFlinger::ThreadBase> thread = mThread.promote();
+    const sp<IAfThreadBase> thread = mThread.promote();
     if (thread != 0) {
-        auto* const recordThread = static_cast<AudioFlinger::RecordThread*>(thread.get());
+        auto* const recordThread = thread->asIAfRecordThread().get();
         return recordThread->getActiveMicrophones(activeMicrophones);
     } else {
         return BAD_VALUE;
@@ -3011,9 +3010,9 @@
 
 status_t RecordTrack::setPreferredMicrophoneDirection(
         audio_microphone_direction_t direction) {
-    sp<AudioFlinger::ThreadBase> thread = mThread.promote();
+    const sp<IAfThreadBase> thread = mThread.promote();
     if (thread != 0) {
-        auto* const recordThread = static_cast<AudioFlinger::RecordThread*>(thread.get());
+        auto* const recordThread = thread->asIAfRecordThread().get();
         return recordThread->setPreferredMicrophoneDirection(direction);
     } else {
         return BAD_VALUE;
@@ -3021,9 +3020,9 @@
 }
 
 status_t RecordTrack::setPreferredMicrophoneFieldDimension(float zoom) {
-    sp<AudioFlinger::ThreadBase> thread = mThread.promote();
+    const sp<IAfThreadBase> thread = mThread.promote();
     if (thread != 0) {
-        auto* const recordThread = static_cast<AudioFlinger::RecordThread*>(thread.get());
+        auto* const recordThread = thread->asIAfRecordThread().get();
         return recordThread->setPreferredMicrophoneFieldDimension(zoom);
     } else {
         return BAD_VALUE;
@@ -3047,9 +3046,9 @@
         return PERMISSION_DENIED;
     }
 
-    sp<AudioFlinger::ThreadBase> thread = mThread.promote();
+    const sp<IAfThreadBase> thread = mThread.promote();
     if (thread != 0) {
-        auto* const recordThread = static_cast<AudioFlinger::RecordThread*>(thread.get());
+        auto* const recordThread = thread->asIAfRecordThread().get();
         status_t status = recordThread->shareAudioHistory(
                 sharedAudioPackageName, mSessionId, sharedAudioStartMs);
         if (status == NO_ERROR) {
@@ -3087,7 +3086,7 @@
 
 /* static */
 sp<IAfPatchRecord> IAfPatchRecord::create(
-        void* /* RecordThread */ recordThread, // TODO(b/288339104)
+        IAfRecordThread* recordThread,
         uint32_t sampleRate,
         audio_channel_mask_t channelMask,
         audio_format_t format,
@@ -3099,7 +3098,7 @@
         audio_source_t source)
 {
     return sp<PatchRecord>::make(
-            reinterpret_cast<AudioFlinger::RecordThread*>(recordThread),
+            recordThread,
             sampleRate,
             channelMask,
             format,
@@ -3111,7 +3110,7 @@
             source);
 }
 
-PatchRecord::PatchRecord(AudioFlinger::RecordThread *recordThread,
+PatchRecord::PatchRecord(IAfRecordThread* recordThread,
                                                      uint32_t sampleRate,
                                                      audio_channel_mask_t channelMask,
                                                      audio_format_t format,
@@ -3230,7 +3229,7 @@
 
 /* static */
 sp<IAfPatchRecord> IAfPatchRecord::createPassThru(
-        void* /* RecordThread */ recordThread, // TODO(b/288339104)
+        IAfRecordThread* recordThread,
         uint32_t sampleRate,
         audio_channel_mask_t channelMask,
         audio_format_t format,
@@ -3239,7 +3238,7 @@
         audio_source_t source)
 {
     return sp<PassthruPatchRecord>::make(
-            reinterpret_cast<AudioFlinger::RecordThread*>(recordThread),
+            recordThread,
             sampleRate,
             channelMask,
             format,
@@ -3249,7 +3248,7 @@
 }
 
 PassthruPatchRecord::PassthruPatchRecord(
-        AudioFlinger::RecordThread* recordThread,
+        IAfRecordThread* recordThread,
         uint32_t sampleRate,
         audio_channel_mask_t channelMask,
         audio_format_t format,
@@ -3266,13 +3265,13 @@
 }
 
 sp<StreamInHalInterface> PassthruPatchRecord::obtainStream(
-        sp<AudioFlinger::ThreadBase>* thread)
+        sp<IAfThreadBase>* thread)
 {
     *thread = mThread.promote();
     if (!*thread) return nullptr;
-    auto* const recordThread = static_cast<AudioFlinger::RecordThread*>((*thread).get());
-    Mutex::Autolock _l(recordThread->mLock);
-    return recordThread->mInput ? recordThread->mInput->stream : nullptr;
+    auto* const recordThread = (*thread)->asIAfRecordThread().get();
+    Mutex::Autolock _l(recordThread->mutex());
+    return recordThread->getInput() ? recordThread->getInput()->stream : nullptr;
 }
 
 // PatchProxyBufferProvider methods are called on DirectOutputThread
@@ -3294,7 +3293,7 @@
     const size_t framesToRead = std::min(buffer->mFrameCount, mFrameCount);
     buffer->mFrameCount = 0;
     buffer->mRaw = nullptr;
-    sp<AudioFlinger::ThreadBase> thread;
+    sp<IAfThreadBase> thread;
     sp<StreamInHalInterface> stream = obtainStream(&thread);
     if (!stream) return NO_INIT;  // If there is no stream, RecordThread is not reading.
 
@@ -3381,7 +3380,7 @@
 status_t PassthruPatchRecord::getCapturePosition(
         int64_t* frames, int64_t* time)
 {
-    sp<AudioFlinger::ThreadBase> thread;
+    sp<IAfThreadBase> thread;
     sp<StreamInHalInterface> stream = obtainStream(&thread);
     return stream ? stream->getCapturePosition(frames, time) : NO_INIT;
 }
@@ -3418,7 +3417,7 @@
 #define LOG_TAG "AF::MmapTrack"
 
 /* static */
-sp<IAfMmapTrack> IAfMmapTrack::create(void* /* AudioFlinger::ThreadBase */ thread,
+sp<IAfMmapTrack> IAfMmapTrack::create(IAfThreadBase* thread,
           const audio_attributes_t& attr,
           uint32_t sampleRate,
           audio_format_t format,
@@ -3430,7 +3429,7 @@
           audio_port_handle_t portId)
 {
     return sp<MmapTrack>::make(
-            reinterpret_cast<AudioFlinger::ThreadBase*>(thread),
+            thread,
             attr,
             sampleRate,
             format,
@@ -3442,7 +3441,7 @@
             portId);
 }
 
-MmapTrack::MmapTrack(AudioFlinger::ThreadBase* thread,
+MmapTrack::MmapTrack(IAfThreadBase* thread,
         const audio_attributes_t& attr,
         uint32_t sampleRate,
         audio_format_t format,