blob: 724a46d00692447c85d778bc26de7d643fe687ec [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
Andy Hungee58e4a2023-07-07 13:47:37 -070018#pragma once
Eric Laurent81784c32012-11-19 14:55:58 -080019
Andy Hung25a80ac2023-07-19 12:47:35 -070020// ADD_BATTERY_DATA AUDIO_WATCHDOG FAST_THREAD_STATISTICS STATE_QUEUE_DUMP TEE_SINK
21#include "Configuration.h"
22#include "IAfThread.h"
23#include "IAfTrack.h"
24
25#include <android-base/macros.h> // DISALLOW_COPY_AND_ASSIGN
26#include <android/os/IPowerManager.h>
27#include <afutils/AudioWatchdog.h>
28#include <afutils/NBAIO_Tee.h>
29#include <audio_utils/Balance.h>
30#include <audio_utils/SimpleLog.h>
31#include <datapath/ThreadMetrics.h>
32#include <fastpath/FastCapture.h>
33#include <fastpath/FastMixer.h>
34#include <mediautils/Synchronization.h>
35#include <mediautils/ThreadSnapshot.h>
36#include <timing/MonotonicFrameCounter.h>
37#include <utils/Log.h>
38
Andy Hungee58e4a2023-07-07 13:47:37 -070039namespace android {
Andy Hung440901d2023-06-29 21:19:25 -070040
41class AsyncCallbackThread;
42
43class ThreadBase : public virtual IAfThreadBase, public Thread {
Eric Laurent81784c32012-11-19 14:55:58 -080044public:
Glenn Kasten97b7b752014-09-28 13:04:24 -070045 static const char *threadTypeToString(type_t type);
46
Andy Hung8d672e02023-09-15 18:19:28 -070047 // ThreadBase_ThreadLoop is a virtual mutex (always nullptr) that
48 // guards methods and variables that ONLY run and are accessed
49 // on the single threaded threadLoop().
50 //
51 // As access is by a single thread, the variables are thread safe.
52 static audio_utils::mutex* ThreadBase_ThreadLoop;
53
Andy Hung583043b2023-07-17 17:05:00 -070054 IAfThreadCallback* afThreadCallback() const final { return mAfThreadCallback.get(); }
Andy Hung87c693c2023-07-06 20:56:16 -070055
Andy Hung583043b2023-07-17 17:05:00 -070056 ThreadBase(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -070057 type_t type, bool systemReady, bool isOut);
Andy Hung440901d2023-06-29 21:19:25 -070058 ~ThreadBase() override;
Eric Laurent81784c32012-11-19 14:55:58 -080059
Andy Hung440901d2023-06-29 21:19:25 -070060 status_t readyToRun() final;
Andy Hungab65b182023-09-06 19:41:47 -070061 void clearPowerManager() final EXCLUDES_ThreadBase_Mutex;
Eric Laurent81784c32012-11-19 14:55:58 -080062
63 // base for record and playback
64 enum {
65 CFG_EVENT_IO,
Eric Laurent10351942014-05-08 18:49:52 -070066 CFG_EVENT_PRIO,
67 CFG_EVENT_SET_PARAMETER,
Eric Laurent1c333e22014-05-20 10:48:17 -070068 CFG_EVENT_CREATE_AUDIO_PATCH,
69 CFG_EVENT_RELEASE_AUDIO_PATCH,
jiabinc52b1ff2019-10-31 17:20:42 -070070 CFG_EVENT_UPDATE_OUT_DEVICE,
Eric Laurentb3f315a2021-07-13 15:09:05 +020071 CFG_EVENT_RESIZE_BUFFER,
Eric Laurent68a40a82022-05-03 18:15:04 +020072 CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS,
73 CFG_EVENT_HAL_LATENCY_MODES_CHANGED,
Eric Laurent81784c32012-11-19 14:55:58 -080074 };
75
Eric Laurent10351942014-05-08 18:49:52 -070076 class ConfigEventData: public RefBase {
Eric Laurent81784c32012-11-19 14:55:58 -080077 public:
Eric Laurent81784c32012-11-19 14:55:58 -080078 virtual void dump(char *buffer, size_t size) = 0;
Eric Laurent10351942014-05-08 18:49:52 -070079 protected:
Andy Hungab65b182023-09-06 19:41:47 -070080 ConfigEventData() = default;
Eric Laurent81784c32012-11-19 14:55:58 -080081 };
82
Eric Laurent10351942014-05-08 18:49:52 -070083 // Config event sequence by client if status needed (e.g binder thread calling setParameters()):
84 // 1. create SetParameterConfigEvent. This sets mWaitStatus in config event
Andy Hungc5007f82023-08-29 14:26:09 -070085 // 2. Lock mutex()
Eric Laurent10351942014-05-08 18:49:52 -070086 // 3. Call sendConfigEvent_l(): Append to mConfigEvents and mWaitWorkCV.signal
87 // 4. sendConfigEvent_l() reads status from event->mStatus;
88 // 5. sendConfigEvent_l() returns status
89 // 6. Unlock
90 //
91 // Parameter sequence by server: threadLoop calling processConfigEvents_l():
Andy Hungc5007f82023-08-29 14:26:09 -070092 // 1. Lock mutex()
Eric Laurent10351942014-05-08 18:49:52 -070093 // 2. If there is an entry in mConfigEvents proceed ...
94 // 3. Read first entry in mConfigEvents
95 // 4. Remove first entry from mConfigEvents
96 // 5. Process
97 // 6. Set event->mStatus
Andy Hungc5007f82023-08-29 14:26:09 -070098 // 7. event->mCondition.notify_one()
Eric Laurent10351942014-05-08 18:49:52 -070099 // 8. Unlock
Eric Laurent81784c32012-11-19 14:55:58 -0800100
Eric Laurent10351942014-05-08 18:49:52 -0700101 class ConfigEvent: public RefBase {
102 public:
Eric Laurentb3f315a2021-07-13 15:09:05 +0200103 void dump(char *buffer, size_t size) {
104 snprintf(buffer, size, "Event type: %d\n", mType);
105 if (mData != nullptr) {
106 snprintf(buffer, size, "Data:\n");
107 mData->dump(buffer, size);
108 }
109 }
Eric Laurent10351942014-05-08 18:49:52 -0700110
Andy Hungab65b182023-09-06 19:41:47 -0700111 audio_utils::mutex& mutex() const RETURN_CAPABILITY(audio_utils::ConfigEvent_Mutex) {
112 return mMutex;
113 }
Eric Laurent10351942014-05-08 18:49:52 -0700114 const int mType; // event type e.g. CFG_EVENT_IO
Andy Hungc5007f82023-08-29 14:26:09 -0700115 mutable audio_utils::mutex mMutex; // mutex associated with mCondition
116 audio_utils::condition_variable mCondition; // condition for status return
Andy Hungab65b182023-09-06 19:41:47 -0700117
118 // NO_THREAD_SAFETY_ANALYSIS Can we add GUARDED_BY?
Eric Laurent10351942014-05-08 18:49:52 -0700119 status_t mStatus; // status communicated to sender
Andy Hungab65b182023-09-06 19:41:47 -0700120
121 bool mWaitStatus GUARDED_BY(mutex()); // true if sender is waiting for status
122 // true if must wait for system ready to enter event queue
123 bool mRequiresSystemReady GUARDED_BY(mutex());
124
125 // NO_THREAD_SAFETY_ANALYSIS Can we add GUARDED_BY?
126 sp<ConfigEventData> mData; // event specific parameter data
Eric Laurent10351942014-05-08 18:49:52 -0700127
128 protected:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700129 explicit ConfigEvent(int type, bool requiresSystemReady = false) :
Eric Laurent72e3f392015-05-20 14:43:50 -0700130 mType(type), mStatus(NO_ERROR), mWaitStatus(false),
131 mRequiresSystemReady(requiresSystemReady), mData(NULL) {}
Eric Laurent10351942014-05-08 18:49:52 -0700132 };
133
134 class IoConfigEventData : public ConfigEventData {
135 public:
Mikhail Naganov88536df2021-07-26 17:30:29 -0700136 IoConfigEventData(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700137 audio_port_handle_t portId) :
138 mEvent(event), mPid(pid), mPortId(portId) {}
Eric Laurent81784c32012-11-19 14:55:58 -0800139
140 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200141 snprintf(buffer, size, "- IO event: event %d\n", mEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800142 }
143
Mikhail Naganov88536df2021-07-26 17:30:29 -0700144 const audio_io_config_event_t mEvent;
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700145 const pid_t mPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -0700146 const audio_port_handle_t mPortId;
Eric Laurent81784c32012-11-19 14:55:58 -0800147 };
148
Eric Laurent10351942014-05-08 18:49:52 -0700149 class IoConfigEvent : public ConfigEvent {
Eric Laurent81784c32012-11-19 14:55:58 -0800150 public:
Mikhail Naganov88536df2021-07-26 17:30:29 -0700151 IoConfigEvent(audio_io_config_event_t event, pid_t pid, audio_port_handle_t portId) :
Eric Laurent10351942014-05-08 18:49:52 -0700152 ConfigEvent(CFG_EVENT_IO) {
Eric Laurent09f1ed22019-04-24 17:45:17 -0700153 mData = new IoConfigEventData(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700154 }
Eric Laurent10351942014-05-08 18:49:52 -0700155 };
Eric Laurent81784c32012-11-19 14:55:58 -0800156
Eric Laurent10351942014-05-08 18:49:52 -0700157 class PrioConfigEventData : public ConfigEventData {
158 public:
Mikhail Naganov83f04272017-02-07 10:45:09 -0800159 PrioConfigEventData(pid_t pid, pid_t tid, int32_t prio, bool forApp) :
160 mPid(pid), mTid(tid), mPrio(prio), mForApp(forApp) {}
Eric Laurent81784c32012-11-19 14:55:58 -0800161
162 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200163 snprintf(buffer, size, "- Prio event: pid %d, tid %d, prio %d, for app? %d\n",
Mikhail Naganov83f04272017-02-07 10:45:09 -0800164 mPid, mTid, mPrio, mForApp);
Eric Laurent81784c32012-11-19 14:55:58 -0800165 }
166
Eric Laurent81784c32012-11-19 14:55:58 -0800167 const pid_t mPid;
168 const pid_t mTid;
169 const int32_t mPrio;
Mikhail Naganov83f04272017-02-07 10:45:09 -0800170 const bool mForApp;
Eric Laurent81784c32012-11-19 14:55:58 -0800171 };
172
Eric Laurent10351942014-05-08 18:49:52 -0700173 class PrioConfigEvent : public ConfigEvent {
174 public:
Mikhail Naganov83f04272017-02-07 10:45:09 -0800175 PrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp) :
Eric Laurent72e3f392015-05-20 14:43:50 -0700176 ConfigEvent(CFG_EVENT_PRIO, true) {
Mikhail Naganov83f04272017-02-07 10:45:09 -0800177 mData = new PrioConfigEventData(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700178 }
Eric Laurent10351942014-05-08 18:49:52 -0700179 };
180
181 class SetParameterConfigEventData : public ConfigEventData {
182 public:
Andy Hung920f6572022-10-06 12:09:49 -0700183 explicit SetParameterConfigEventData(const String8& keyValuePairs) :
Eric Laurent10351942014-05-08 18:49:52 -0700184 mKeyValuePairs(keyValuePairs) {}
185
186 virtual void dump(char *buffer, size_t size) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000187 snprintf(buffer, size, "- KeyValue: %s\n", mKeyValuePairs.c_str());
Eric Laurent10351942014-05-08 18:49:52 -0700188 }
189
190 const String8 mKeyValuePairs;
191 };
192
193 class SetParameterConfigEvent : public ConfigEvent {
194 public:
Andy Hung920f6572022-10-06 12:09:49 -0700195 explicit SetParameterConfigEvent(const String8& keyValuePairs) :
Eric Laurent10351942014-05-08 18:49:52 -0700196 ConfigEvent(CFG_EVENT_SET_PARAMETER) {
197 mData = new SetParameterConfigEventData(keyValuePairs);
198 mWaitStatus = true;
199 }
Eric Laurent10351942014-05-08 18:49:52 -0700200 };
201
Eric Laurent1c333e22014-05-20 10:48:17 -0700202 class CreateAudioPatchConfigEventData : public ConfigEventData {
203 public:
204 CreateAudioPatchConfigEventData(const struct audio_patch patch,
205 audio_patch_handle_t handle) :
206 mPatch(patch), mHandle(handle) {}
207
208 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200209 snprintf(buffer, size, "- Patch handle: %u\n", mHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -0700210 }
211
212 const struct audio_patch mPatch;
Andy Hungab65b182023-09-06 19:41:47 -0700213 audio_patch_handle_t mHandle; // cannot be const
Eric Laurent1c333e22014-05-20 10:48:17 -0700214 };
215
216 class CreateAudioPatchConfigEvent : public ConfigEvent {
217 public:
218 CreateAudioPatchConfigEvent(const struct audio_patch patch,
219 audio_patch_handle_t handle) :
220 ConfigEvent(CFG_EVENT_CREATE_AUDIO_PATCH) {
221 mData = new CreateAudioPatchConfigEventData(patch, handle);
222 mWaitStatus = true;
223 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700224 };
225
226 class ReleaseAudioPatchConfigEventData : public ConfigEventData {
227 public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700228 explicit ReleaseAudioPatchConfigEventData(const audio_patch_handle_t handle) :
Eric Laurent1c333e22014-05-20 10:48:17 -0700229 mHandle(handle) {}
230
231 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200232 snprintf(buffer, size, "- Patch handle: %u\n", mHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -0700233 }
234
Andy Hungab65b182023-09-06 19:41:47 -0700235 const audio_patch_handle_t mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -0700236 };
237
238 class ReleaseAudioPatchConfigEvent : public ConfigEvent {
239 public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700240 explicit ReleaseAudioPatchConfigEvent(const audio_patch_handle_t handle) :
Eric Laurent1c333e22014-05-20 10:48:17 -0700241 ConfigEvent(CFG_EVENT_RELEASE_AUDIO_PATCH) {
242 mData = new ReleaseAudioPatchConfigEventData(handle);
243 mWaitStatus = true;
244 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700245 };
Eric Laurent81784c32012-11-19 14:55:58 -0800246
jiabinc52b1ff2019-10-31 17:20:42 -0700247 class UpdateOutDevicesConfigEventData : public ConfigEventData {
248 public:
249 explicit UpdateOutDevicesConfigEventData(const DeviceDescriptorBaseVector& outDevices) :
250 mOutDevices(outDevices) {}
251
252 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200253 snprintf(buffer, size, "- Devices: %s", android::toString(mOutDevices).c_str());
jiabinc52b1ff2019-10-31 17:20:42 -0700254 }
255
Andy Hungab65b182023-09-06 19:41:47 -0700256 const DeviceDescriptorBaseVector mOutDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700257 };
258
259 class UpdateOutDevicesConfigEvent : public ConfigEvent {
260 public:
261 explicit UpdateOutDevicesConfigEvent(const DeviceDescriptorBaseVector& outDevices) :
262 ConfigEvent(CFG_EVENT_UPDATE_OUT_DEVICE) {
263 mData = new UpdateOutDevicesConfigEventData(outDevices);
264 }
jiabinc52b1ff2019-10-31 17:20:42 -0700265 };
266
Eric Laurentec376dc2021-04-08 20:41:22 +0200267 class ResizeBufferConfigEventData : public ConfigEventData {
268 public:
269 explicit ResizeBufferConfigEventData(int32_t maxSharedAudioHistoryMs) :
270 mMaxSharedAudioHistoryMs(maxSharedAudioHistoryMs) {}
271
272 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200273 snprintf(buffer, size, "- mMaxSharedAudioHistoryMs: %d", mMaxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +0200274 }
275
Andy Hungab65b182023-09-06 19:41:47 -0700276 const int32_t mMaxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +0200277 };
278
279 class ResizeBufferConfigEvent : public ConfigEvent {
280 public:
281 explicit ResizeBufferConfigEvent(int32_t maxSharedAudioHistoryMs) :
282 ConfigEvent(CFG_EVENT_RESIZE_BUFFER) {
283 mData = new ResizeBufferConfigEventData(maxSharedAudioHistoryMs);
284 }
Eric Laurentec376dc2021-04-08 20:41:22 +0200285 };
286
Eric Laurentb3f315a2021-07-13 15:09:05 +0200287 class CheckOutputStageEffectsEvent : public ConfigEvent {
288 public:
289 CheckOutputStageEffectsEvent() :
290 ConfigEvent(CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS) {
291 }
Eric Laurentb3f315a2021-07-13 15:09:05 +0200292 };
293
Eric Laurent68a40a82022-05-03 18:15:04 +0200294 class HalLatencyModesChangedEvent : public ConfigEvent {
295 public:
296 HalLatencyModesChangedEvent() :
297 ConfigEvent(CFG_EVENT_HAL_LATENCY_MODES_CHANGED) {
298 }
Eric Laurent68a40a82022-05-03 18:15:04 +0200299 };
300
Eric Laurentb3f315a2021-07-13 15:09:05 +0200301
Eric Laurent81784c32012-11-19 14:55:58 -0800302 class PMDeathRecipient : public IBinder::DeathRecipient {
303 public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700304 explicit PMDeathRecipient(const wp<ThreadBase>& thread) : mThread(thread) {}
Eric Laurent81784c32012-11-19 14:55:58 -0800305
306 // IBinder::DeathRecipient
Andy Hungab65b182023-09-06 19:41:47 -0700307 void binderDied(const wp<IBinder>& who) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800308
309 private:
Mikhail Naganovbf493082017-04-17 17:37:12 -0700310 DISALLOW_COPY_AND_ASSIGN(PMDeathRecipient);
Eric Laurent81784c32012-11-19 14:55:58 -0800311
Andy Hungab65b182023-09-06 19:41:47 -0700312 const wp<ThreadBase> mThread;
Eric Laurent81784c32012-11-19 14:55:58 -0800313 };
314
Andy Hung440901d2023-06-29 21:19:25 -0700315 type_t type() const final { return mType; }
316 bool isDuplicating() const final { return (mType == DUPLICATING); }
317 audio_io_handle_t id() const final { return mId;}
Eric Laurent81784c32012-11-19 14:55:58 -0800318
Andy Hung440901d2023-06-29 21:19:25 -0700319 uint32_t sampleRate() const final { return mSampleRate; }
320 audio_channel_mask_t channelMask() const final { return mChannelMask; }
321 audio_channel_mask_t mixerChannelMask() const override { return mChannelMask; }
322 audio_format_t format() const final { return mHALFormat; }
323 uint32_t channelCount() const final { return mChannelCount; }
324 audio_channel_mask_t hapticChannelMask() const override { return AUDIO_CHANNEL_NONE; }
Andy Hung87c693c2023-07-06 20:56:16 -0700325 uint32_t hapticChannelCount() const override { return 0; }
Andy Hungab65b182023-09-06 19:41:47 -0700326 uint32_t latency_l() const override { return 0; } // NO_THREAD_SAFETY_ANALYSIS
327 void setVolumeForOutput_l(float /* left */, float /* right */) const override
328 REQUIRES(mutex()) {}
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700329
330 // Return's the HAL's frame count i.e. fast mixer buffer size.
Andy Hung440901d2023-06-29 21:19:25 -0700331 size_t frameCountHAL() const final { return mFrameCount; }
332 size_t frameSize() const final { return mFrameSize; }
Eric Laurent81784c32012-11-19 14:55:58 -0800333
334 // Should be "virtual status_t requestExitAndWait()" and override same
335 // method in Thread, but Thread::requestExitAndWait() is not yet virtual.
Andy Hungab65b182023-09-06 19:41:47 -0700336 void exit() final EXCLUDES_ThreadBase_Mutex;
337 status_t setParameters(const String8& keyValuePairs) final EXCLUDES_ThreadBase_Mutex;
Andy Hung440901d2023-06-29 21:19:25 -0700338
Andy Hungc5007f82023-08-29 14:26:09 -0700339 // sendConfigEvent_l() must be called with ThreadBase::mutex() held
Eric Laurent10351942014-05-08 18:49:52 -0700340 // Can temporarily release the lock if waiting for a reply from
341 // processConfigEvents_l().
Andy Hungab65b182023-09-06 19:41:47 -0700342 status_t sendConfigEvent_l(sp<ConfigEvent>& event) REQUIRES(mutex());
Andy Hung440901d2023-06-29 21:19:25 -0700343 void sendIoConfigEvent(audio_io_config_event_t event, pid_t pid = 0,
Andy Hungab65b182023-09-06 19:41:47 -0700344 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final EXCLUDES_ThreadBase_Mutex;
Andy Hung440901d2023-06-29 21:19:25 -0700345 void sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid = 0,
Andy Hungab65b182023-09-06 19:41:47 -0700346 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final REQUIRES(mutex());
347 void sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp) final
348 EXCLUDES_ThreadBase_Mutex;
349 void sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio, bool forApp) final
350 REQUIRES(mutex());
351 status_t sendSetParameterConfigEvent_l(const String8& keyValuePair) final REQUIRES(mutex());
Andy Hung440901d2023-06-29 21:19:25 -0700352 status_t sendCreateAudioPatchConfigEvent(const struct audio_patch* patch,
Andy Hungab65b182023-09-06 19:41:47 -0700353 audio_patch_handle_t* handle) final EXCLUDES_ThreadBase_Mutex;
354 status_t sendReleaseAudioPatchConfigEvent(audio_patch_handle_t handle) final
355 EXCLUDES_ThreadBase_Mutex;
Andy Hung440901d2023-06-29 21:19:25 -0700356 status_t sendUpdateOutDeviceConfigEvent(
Andy Hungab65b182023-09-06 19:41:47 -0700357 const DeviceDescriptorBaseVector& outDevices) final EXCLUDES_ThreadBase_Mutex;
358 void sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs) final REQUIRES(mutex());
359 void sendCheckOutputStageEffectsEvent() final EXCLUDES_ThreadBase_Mutex;
360 void sendCheckOutputStageEffectsEvent_l() final REQUIRES(mutex());
361 void sendHalLatencyModesChangedEvent_l() final REQUIRES(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +0200362
Andy Hungab65b182023-09-06 19:41:47 -0700363 void processConfigEvents_l() final REQUIRES(mutex());
Andy Hung440901d2023-06-29 21:19:25 -0700364 void setCheckOutputStageEffects() override {}
365 void updateOutDevices(const DeviceDescriptorBaseVector& outDevices) override;
366 void toAudioPortConfig(struct audio_port_config* config) override;
Andy Hungab65b182023-09-06 19:41:47 -0700367 void resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs) override REQUIRES(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700368
Andy Hung440901d2023-06-29 21:19:25 -0700369 // see note at declaration of mStandby, mOutDevice and mInDevice
370 bool inStandby() const override { return mStandby; }
Andy Hungab65b182023-09-06 19:41:47 -0700371 const DeviceTypeSet outDeviceTypes_l() const final REQUIRES(mutex()) {
Andy Hung440901d2023-06-29 21:19:25 -0700372 return getAudioDeviceTypes(mOutDeviceTypeAddrs);
373 }
Andy Hungab65b182023-09-06 19:41:47 -0700374 audio_devices_t inDeviceType_l() const final REQUIRES(mutex()) {
375 return mInDeviceTypeAddr.mType;
376 }
377 DeviceTypeSet getDeviceTypes_l() const final REQUIRES(mutex()) {
378 return isOutput() ? outDeviceTypes_l() : DeviceTypeSet({inDeviceType_l()});
Andy Hung440901d2023-06-29 21:19:25 -0700379 }
Eric Laurent81784c32012-11-19 14:55:58 -0800380
Andy Hung440901d2023-06-29 21:19:25 -0700381 const AudioDeviceTypeAddrVector& outDeviceTypeAddrs() const final {
382 return mOutDeviceTypeAddrs;
383 }
384 const AudioDeviceTypeAddr& inDeviceTypeAddr() const final {
385 return mInDeviceTypeAddr;
386 }
Andy Hung293558a2017-03-21 12:19:20 -0700387
Andy Hung440901d2023-06-29 21:19:25 -0700388 bool isOutput() const final { return mIsOut; }
jiabin8f278ee2019-11-11 12:16:27 -0800389
Andy Hung440901d2023-06-29 21:19:25 -0700390 bool isOffloadOrMmap() const final {
391 switch (mType) {
392 case OFFLOAD:
393 case MMAP_PLAYBACK:
394 case MMAP_CAPTURE:
395 return true;
396 default:
397 return false;
398 }
399 }
Eric Laurent81784c32012-11-19 14:55:58 -0800400
Andy Hung440901d2023-06-29 21:19:25 -0700401 sp<IAfEffectHandle> createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -0700402 const sp<Client>& client,
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700403 const sp<media::IEffectClient>& effectClient,
Eric Laurent81784c32012-11-19 14:55:58 -0800404 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -0800405 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800406 effect_descriptor_t *desc,
407 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -0800408 status_t *status /*non-NULL*/,
Eric Laurent2fe0acd2020-03-13 14:30:46 -0700409 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +0200410 bool probe,
Andy Hung972bec12023-08-31 16:13:39 -0700411 bool notifyFramesProcessed) final
412 REQUIRES(audio_utils::AudioFlinger_Mutex);
Eric Laurent81784c32012-11-19 14:55:58 -0800413
414 // return values for hasAudioSession (bit field)
415 enum effect_state {
416 EFFECT_SESSION = 0x1, // the audio session corresponds to at least one
417 // effect
Eric Laurent4c415062016-06-17 16:14:16 -0700418 TRACK_SESSION = 0x2, // the audio session corresponds to at least one
Eric Laurent81784c32012-11-19 14:55:58 -0800419 // track
Eric Laurentb62d0362021-10-26 17:40:18 +0200420 FAST_SESSION = 0x4, // the audio session corresponds to at least one
Eric Laurent4c415062016-06-17 16:14:16 -0700421 // fast track
jiabinc658e452022-10-21 20:52:21 +0000422 SPATIALIZED_SESSION = 0x8, // the audio session corresponds to at least one
423 // spatialized track
424 BIT_PERFECT_SESSION = 0x10 // the audio session corresponds to at least one
425 // bit-perfect track
Eric Laurent81784c32012-11-19 14:55:58 -0800426 };
427
Andy Hung440901d2023-06-29 21:19:25 -0700428 // get effect chain corresponding to session Id.
429 sp<IAfEffectChain> getEffectChain(audio_session_t sessionId) const final;
430 // same as getEffectChain() but must be called with ThreadBase mutex locked
Andy Hung8d672e02023-09-15 18:19:28 -0700431 sp<IAfEffectChain> getEffectChain_l(audio_session_t sessionId) const final REQUIRES(mutex());
432 std::vector<int> getEffectIds_l(audio_session_t sessionId) const final REQUIRES(mutex());
Andy Hung440901d2023-06-29 21:19:25 -0700433
Eric Laurent81784c32012-11-19 14:55:58 -0800434 // lock all effect chains Mutexes. Must be called before releasing the
435 // ThreadBase mutex before processing the mixer and effects. This guarantees the
436 // integrity of the chains during the process.
437 // Also sets the parameter 'effectChains' to current value of mEffectChains.
Andy Hungab65b182023-09-06 19:41:47 -0700438 void lockEffectChains_l(Vector<sp<IAfEffectChain>>& effectChains) final REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800439 // unlock effect chains after process
Andy Hung440901d2023-06-29 21:19:25 -0700440 void unlockEffectChains(const Vector<sp<IAfEffectChain>>& effectChains) final;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800441 // get a copy of mEffectChains vector
Andy Hungab65b182023-09-06 19:41:47 -0700442 Vector<sp<IAfEffectChain>> getEffectChains_l() const final REQUIRES(mutex()) {
443 return mEffectChains;
444 }
Eric Laurent81784c32012-11-19 14:55:58 -0800445 // set audio mode to all effect chains
Andy Hung440901d2023-06-29 21:19:25 -0700446 void setMode(audio_mode_t mode) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800447 // get effect module with corresponding ID on specified audio session
Andy Hung440901d2023-06-29 21:19:25 -0700448 sp<IAfEffectModule> getEffect(audio_session_t sessionId, int effectId) const final;
Andy Hungab65b182023-09-06 19:41:47 -0700449 sp<IAfEffectModule> getEffect_l(audio_session_t sessionId, int effectId) const final
450 REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800451 // add and effect module. Also creates the effect chain is none exists for
Eric Laurent6c796322019-04-09 14:13:17 -0700452 // the effects audio session. Only called in a context of moving an effect
453 // from one thread to another
Andy Hung972bec12023-08-31 16:13:39 -0700454 status_t addEffect_ll(const sp<IAfEffectModule>& effect) final
455 REQUIRES(audio_utils::AudioFlinger_Mutex, mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800456 // remove and effect module. Also removes the effect chain is this was the last
457 // effect
Andy Hungab65b182023-09-06 19:41:47 -0700458 void removeEffect_l(const sp<IAfEffectModule>& effect, bool release = false) final
459 REQUIRES(mutex());
Eric Laurent0d5a2ed2016-12-01 15:28:29 -0800460 // disconnect an effect handle from module and destroy module if last handle
Andy Hung440901d2023-06-29 21:19:25 -0700461 void disconnectEffectHandle(IAfEffectHandle* handle, bool unpinIfLast) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800462 // detach all tracks connected to an auxiliary effect
Andy Hungab65b182023-09-06 19:41:47 -0700463 void detachAuxEffect_l(int /* effectId */) override REQUIRES(mutex()) {}
Andy Hung99b1ba62023-07-14 11:00:08 -0700464 // TODO(b/291317898) - remove hasAudioSession_l below.
Andy Hungab65b182023-09-06 19:41:47 -0700465 uint32_t hasAudioSession_l(audio_session_t sessionId) const override REQUIRES(mutex()) = 0;
466 uint32_t hasAudioSession(audio_session_t sessionId) const final EXCLUDES_ThreadBase_Mutex {
Andy Hung8d672e02023-09-15 18:19:28 -0700467 audio_utils::lock_guard _l(mutex());
Andy Hungab65b182023-09-06 19:41:47 -0700468 return hasAudioSession_l(sessionId);
469 }
Eric Laurent4c415062016-06-17 16:14:16 -0700470
Andy Hungc3d62f92019-03-14 13:38:51 -0700471 template <typename T>
Andy Hung8d672e02023-09-15 18:19:28 -0700472 uint32_t hasAudioSession_l(audio_session_t sessionId, const T& tracks) const
473 REQUIRES(mutex()) {
Andy Hungc3d62f92019-03-14 13:38:51 -0700474 uint32_t result = 0;
475 if (getEffectChain_l(sessionId) != 0) {
476 result = EFFECT_SESSION;
477 }
478 for (size_t i = 0; i < tracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -0700479 const sp<IAfTrackBase>& track = tracks[i];
Andy Hungc3d62f92019-03-14 13:38:51 -0700480 if (sessionId == track->sessionId()
481 && !track->isInvalid() // not yet removed from tracks.
482 && !track->isTerminated()) {
483 result |= TRACK_SESSION;
484 if (track->isFastTrack()) {
485 result |= FAST_SESSION; // caution, only represents first track.
486 }
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200487 if (track->isSpatialized()) {
Eric Laurentb62d0362021-10-26 17:40:18 +0200488 result |= SPATIALIZED_SESSION; // caution, only first track.
489 }
jiabinc658e452022-10-21 20:52:21 +0000490 if (track->isBitPerfect()) {
491 result |= BIT_PERFECT_SESSION;
492 }
Andy Hungc3d62f92019-03-14 13:38:51 -0700493 break;
494 }
495 }
496 return result;
497 }
498
Eric Laurent81784c32012-11-19 14:55:58 -0800499 // the value returned by default implementation is not important as the
500 // strategy is only meaningful for PlaybackThread which implements this method
Andy Hung440901d2023-06-29 21:19:25 -0700501 product_strategy_t getStrategyForSession_l(
Andy Hungab65b182023-09-06 19:41:47 -0700502 audio_session_t /* sessionId */) const override REQUIRES(mutex()){
503 return static_cast<product_strategy_t>(0);
504 }
Eric Laurent81784c32012-11-19 14:55:58 -0800505
Eric Laurent81784c32012-11-19 14:55:58 -0800506 // check if some effects must be suspended/restored when an effect is enabled
507 // or disabled
Andy Hung440901d2023-06-29 21:19:25 -0700508 void checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -0800509 audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -0700510 bool threadLocked) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800511
Eric Laurent81784c32012-11-19 14:55:58 -0800512
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700513 // Return a reference to a per-thread heap which can be used to allocate IMemory
514 // objects that will be read-only to client processes, read/write to mediaserver,
515 // and shared by all client processes of the thread.
516 // The heap is per-thread rather than common across all threads, because
517 // clients can't be trusted not to modify the offset of the IMemory they receive.
518 // If a thread does not have such a heap, this method returns 0.
Andy Hung440901d2023-06-29 21:19:25 -0700519 sp<MemoryDealer> readOnlyHeap() const override { return nullptr; }
Eric Laurent81784c32012-11-19 14:55:58 -0800520
Andy Hung440901d2023-06-29 21:19:25 -0700521 sp<IMemory> pipeMemory() const override { return nullptr; }
Glenn Kasten6181ffd2014-05-13 10:41:52 -0700522
Andy Hungab65b182023-09-06 19:41:47 -0700523 void systemReady() final EXCLUDES_ThreadBase_Mutex;
Eric Laurent72e3f392015-05-20 14:43:50 -0700524
Andy Hungab65b182023-09-06 19:41:47 -0700525 void broadcast_l() final REQUIRES(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -0700526
Andy Hungab65b182023-09-06 19:41:47 -0700527 bool isTimestampCorrectionEnabled_l() const override REQUIRES(mutex()) { return false; }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800528
Andy Hung440901d2023-06-29 21:19:25 -0700529 bool isMsdDevice() const final { return mIsMsdDevice; }
Andy Hungc8fddf32018-08-08 18:32:37 -0700530
Andy Hung440901d2023-06-29 21:19:25 -0700531 void dump(int fd, const Vector<String16>& args) override;
Andy Hungdc099c22018-09-18 13:46:39 -0700532
Andy Hungd0979812019-02-21 15:51:44 -0800533 // deliver stats to mediametrics.
Andy Hung8d672e02023-09-15 18:19:28 -0700534 void sendStatistics(bool force) final
535 REQUIRES(ThreadBase_ThreadLoop) EXCLUDES_ThreadBase_Mutex;
Andy Hungd0979812019-02-21 15:51:44 -0800536
Andy Hung972bec12023-08-31 16:13:39 -0700537 audio_utils::mutex& mutex() const final RETURN_CAPABILITY(audio_utils::ThreadBase_Mutex) {
Andy Hungc5007f82023-08-29 14:26:09 -0700538 return mMutex;
Andy Hung440901d2023-06-29 21:19:25 -0700539 }
Andy Hungc5007f82023-08-29 14:26:09 -0700540 mutable audio_utils::mutex mMutex;
Eric Laurent81784c32012-11-19 14:55:58 -0800541
Andy Hungab65b182023-09-06 19:41:47 -0700542 void onEffectEnable(const sp<IAfEffectModule>& effect) final EXCLUDES_ThreadBase_Mutex;
543 void onEffectDisable() final EXCLUDES_ThreadBase_Mutex;
Eric Laurent6b446ce2019-12-13 10:56:31 -0800544
Andy Hungc5007f82023-08-29 14:26:09 -0700545 // invalidateTracksForAudioSession_l must be called with holding mutex().
Andy Hungab65b182023-09-06 19:41:47 -0700546 void invalidateTracksForAudioSession_l(audio_session_t /* sessionId */) const override
547 REQUIRES(mutex()) {}
jiabineb3bda02020-06-30 14:07:03 -0700548 // Invalidate all the tracks with the given audio session.
Andy Hungab65b182023-09-06 19:41:47 -0700549 void invalidateTracksForAudioSession(audio_session_t sessionId) const final
550 EXCLUDES_ThreadBase_Mutex {
Andy Hung8d672e02023-09-15 18:19:28 -0700551 audio_utils::lock_guard _l(mutex());
jiabineb3bda02020-06-30 14:07:03 -0700552 invalidateTracksForAudioSession_l(sessionId);
553 }
554
555 template <typename T>
Andy Hungab65b182023-09-06 19:41:47 -0700556 void invalidateTracksForAudioSession_l(audio_session_t sessionId,
557 const T& tracks) const REQUIRES(mutex()) {
jiabineb3bda02020-06-30 14:07:03 -0700558 for (size_t i = 0; i < tracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -0700559 const sp<IAfTrackBase>& track = tracks[i];
jiabineb3bda02020-06-30 14:07:03 -0700560 if (sessionId == track->sessionId()) {
561 track->invalidate();
562 }
563 }
564 }
565
Andy Hung972bec12023-08-31 16:13:39 -0700566 void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) override
567 REQUIRES(audio_utils::AudioFlinger_Mutex);
568 void stopMelComputation_l() override
569 REQUIRES(audio_utils::AudioFlinger_Mutex);
Vlad Popa6fbbfbf2023-02-22 15:05:43 +0100570
Eric Laurent81784c32012-11-19 14:55:58 -0800571protected:
572
573 // entry describing an effect being suspended in mSuspendedSessions keyed vector
574 class SuspendedSessionDesc : public RefBase {
575 public:
576 SuspendedSessionDesc() : mRefCount(0) {}
577
578 int mRefCount; // number of active suspend requests
579 effect_uuid_t mType; // effect type UUID
580 };
581
Andy Hungab65b182023-09-06 19:41:47 -0700582 void acquireWakeLock() EXCLUDES_ThreadBase_Mutex;
583 virtual void acquireWakeLock_l() REQUIRES(mutex());
584 void releaseWakeLock() EXCLUDES_ThreadBase_Mutex;
585 void releaseWakeLock_l() REQUIRES(mutex());
586 void updateWakeLockUids_l(const SortedVector<uid_t> &uids) REQUIRES(mutex());
587 void getPowerManager_l() REQUIRES(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -0700588 // suspend or restore effects of the specified type (or all if type is NULL)
589 // on a given session. The number of suspend requests is counted and restore
590 // occurs when all suspend requests are cancelled.
Andy Hungab65b182023-09-06 19:41:47 -0700591 void setEffectSuspended_l(const effect_uuid_t *type,
Eric Laurent81784c32012-11-19 14:55:58 -0800592 bool suspend,
Andy Hungab65b182023-09-06 19:41:47 -0700593 audio_session_t sessionId) final REQUIRES(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -0700594 // updated mSuspendedSessions when an effect is suspended or restored
Andy Hungab65b182023-09-06 19:41:47 -0700595 void updateSuspendedSessions_l(const effect_uuid_t *type,
Eric Laurent81784c32012-11-19 14:55:58 -0800596 bool suspend,
Andy Hungab65b182023-09-06 19:41:47 -0700597 audio_session_t sessionId) REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800598 // check if some effects must be suspended when an effect chain is added
Andy Hungab65b182023-09-06 19:41:47 -0700599 void checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain) REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800600
Kevin Rocard069c2712018-03-29 19:09:14 -0700601 // sends the metadata of the active tracks to the HAL
Vlad Popa7e81cea2023-01-19 16:34:16 +0100602 struct MetadataUpdate {
603 std::vector<playback_track_metadata_v7_t> playbackMetadataUpdate;
604 std::vector<record_track_metadata_v7_t> recordMetadataUpdate;
605 };
Andy Hung8d672e02023-09-15 18:19:28 -0700606 // NO_THREAD_SAFETY_ANALYSIS, updateMetadata_l() should include ThreadBase_ThreadLoop
607 // but MmapThread::start() -> exitStandby_l() -> updateMetadata_l() prevents this.
Andy Hungab65b182023-09-06 19:41:47 -0700608 virtual MetadataUpdate updateMetadata_l() REQUIRES(mutex()) = 0;
Kevin Rocard069c2712018-03-29 19:09:14 -0700609
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100610 String16 getWakeLockTag();
611
Andy Hungab65b182023-09-06 19:41:47 -0700612 virtual void preExit() EXCLUDES_ThreadBase_Mutex {}
613 virtual void setMasterMono_l(bool mono __unused) REQUIRES(mutex()) {}
Andy Hung2ddee192015-12-18 17:34:44 -0800614 virtual bool requireMonoBlend() { return false; }
Eric Laurent81784c32012-11-19 14:55:58 -0800615
Andy Hung1c86ebe2018-05-29 20:29:08 -0700616 // called within the threadLoop to obtain timestamp from the HAL.
Andy Hungab65b182023-09-06 19:41:47 -0700617 virtual status_t threadloop_getHalTimestamp_l(
Andy Hung8d672e02023-09-15 18:19:28 -0700618 ExtendedTimestamp *timestamp __unused) const
619 REQUIRES(mutex(), ThreadBase_ThreadLoop) {
Andy Hung1c86ebe2018-05-29 20:29:08 -0700620 return INVALID_OPERATION;
621 }
Andy Hung116bc262023-06-20 18:56:17 -0700622public:
Andy Hung99b1ba62023-07-14 11:00:08 -0700623// TODO(b/291317898) organize with publics
Eric Laurentd66d7a12021-07-13 13:35:32 +0200624 product_strategy_t getStrategyForStream(audio_stream_type_t stream) const;
Andy Hung116bc262023-06-20 18:56:17 -0700625protected:
Eric Laurentd66d7a12021-07-13 13:35:32 +0200626
Andy Hungab65b182023-09-06 19:41:47 -0700627 virtual void onHalLatencyModesChanged_l() REQUIRES(mutex()) {}
Eric Laurentb0463942022-12-20 16:31:10 +0100628
Andy Hungab65b182023-09-06 19:41:47 -0700629 virtual void dumpInternals_l(int fd __unused, const Vector<String16>& args __unused)
630 REQUIRES(mutex()) {}
631 virtual void dumpTracks_l(int fd __unused, const Vector<String16>& args __unused)
632 REQUIRES(mutex()) {}
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700633
Eric Laurent81784c32012-11-19 14:55:58 -0800634 const type_t mType;
635
636 // Used by parameters, config events, addTrack_l, exit
Andy Hungc5007f82023-08-29 14:26:09 -0700637 audio_utils::condition_variable mWaitWorkCV;
Eric Laurent81784c32012-11-19 14:55:58 -0800638
Andy Hung583043b2023-07-17 17:05:00 -0700639 const sp<IAfThreadCallback> mAfThreadCallback;
Andy Hungcf10d742020-04-28 15:38:24 -0700640 ThreadMetrics mThreadMetrics;
641 const bool mIsOut;
Glenn Kasten9b58f632013-07-16 11:37:48 -0700642
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800643 // updated by PlaybackThread::readOutputParameters_l() or
644 // RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800645 uint32_t mSampleRate;
646 size_t mFrameCount; // output HAL, direct output, record
Eric Laurent81784c32012-11-19 14:55:58 -0800647 audio_channel_mask_t mChannelMask;
Glenn Kastenf6ed4232013-07-16 11:16:27 -0700648 uint32_t mChannelCount;
Eric Laurent81784c32012-11-19 14:55:58 -0800649 size_t mFrameSize;
Glenn Kasten97b7b752014-09-28 13:04:24 -0700650 // not HAL frame size, this is for output sink (to pipe to fast mixer)
Andy Hung463be252014-07-10 16:56:07 -0700651 audio_format_t mFormat; // Source format for Recording and
652 // Sink format for Playback.
653 // Sink format may be different than
654 // HAL format if Fastmixer is used.
655 audio_format_t mHALFormat;
Glenn Kasten70949c42013-08-06 07:40:12 -0700656 size_t mBufferSize; // HAL buffer size for read() or write()
Andy Hungab65b182023-09-06 19:41:47 -0700657
658 // output device types and addresses
659 AudioDeviceTypeAddrVector mOutDeviceTypeAddrs GUARDED_BY(mutex());
660 AudioDeviceTypeAddr mInDeviceTypeAddr GUARDED_BY(mutex()); // input device type and address
Andy Hung8d672e02023-09-15 18:19:28 -0700661 Vector<sp<ConfigEvent>> mConfigEvents GUARDED_BY(mutex());
662
663 // events awaiting system ready
664 Vector<sp<ConfigEvent>> mPendingConfigEvents GUARDED_BY(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800665
666 // These fields are written and read by thread itself without lock or barrier,
jiabinc52b1ff2019-10-31 17:20:42 -0700667 // and read by other threads without lock or barrier via standby(), outDeviceTypes()
668 // and inDeviceType().
Eric Laurent81784c32012-11-19 14:55:58 -0800669 // Because of the absence of a lock or barrier, any other thread that reads
670 // these fields must use the information in isolation, or be prepared to deal
671 // with possibility that it might be inconsistent with other information.
Glenn Kasten4944acb2013-08-19 08:39:20 -0700672 bool mStandby; // Whether thread is currently in standby.
jiabinc52b1ff2019-10-31 17:20:42 -0700673
Andy Hung8d672e02023-09-15 18:19:28 -0700674 // NO_THREAD_SAFETY_ANALYSIS - mPatch and mAudioSource should be guarded by mutex().
Eric Laurent296fb132015-05-01 11:38:42 -0700675 struct audio_patch mPatch;
Glenn Kastenf59497b2015-01-26 16:35:47 -0800676 audio_source_t mAudioSource;
Eric Laurent81784c32012-11-19 14:55:58 -0800677
678 const audio_io_handle_t mId;
Andy Hung8d672e02023-09-15 18:19:28 -0700679 Vector<sp<IAfEffectChain>> mEffectChains GUARDED_BY(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800680
Glenn Kastend7dca052015-03-05 16:05:54 -0800681 static const int kThreadNameLength = 16; // prctl(PR_SET_NAME) limit
682 char mThreadName[kThreadNameLength]; // guaranteed NUL-terminated
Andy Hung8d672e02023-09-15 18:19:28 -0700683 sp<os::IPowerManager> mPowerManager GUARDED_BY(mutex());
684 sp<IBinder> mWakeLockToken GUARDED_BY(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800685 const sp<PMDeathRecipient> mDeathRecipient;
Glenn Kastend848eb42016-03-08 13:42:11 -0800686 // list of suspended effects per session and per type. The first (outer) vector is
687 // keyed by session ID, the second (inner) by type UUID timeLow field
Eric Laurentd8365c52017-07-16 15:27:05 -0700688 // Updated by updateSuspendedSessions_l() only.
Glenn Kastend848eb42016-03-08 13:42:11 -0800689 KeyedVector< audio_session_t, KeyedVector< int, sp<SuspendedSessionDesc> > >
Eric Laurent81784c32012-11-19 14:55:58 -0800690 mSuspendedSessions;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -0700691 // TODO: add comment and adjust size as needed
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800692 static const size_t kLogSize = 4 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -0800693 sp<NBLog::Writer> mNBLogWriter;
Eric Laurent72e3f392015-05-20 14:43:50 -0700694 bool mSystemReady;
Andy Hung8d672e02023-09-15 18:19:28 -0700695
696 // NO_THREAD_SAFETY_ANALYSIS - mTimestamp and mTimestampVerifier should be
697 // accessed under mutex for the RecordThread.
698 ExtendedTimestamp mTimestamp;
699 TimestampVerifier<int64_t /* frame count */, int64_t /* time ns */> mTimestampVerifier;
Dean Wheatley12473e92021-03-18 23:00:55 +1100700 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush
701 // TODO: add confirmation checks:
702 // 1) DIRECT threads and linear PCM format really resets to 0?
703 // 2) Is frame count really valid if not linear pcm?
704 // 3) Are all 64 bits of position returned, not just lowest 32 bits?
jiabinc52b1ff2019-10-31 17:20:42 -0700705 // Timestamp corrected device should be a single device.
Andy Hung8d672e02023-09-15 18:19:28 -0700706
707 audio_devices_t mTimestampCorrectedDevice = AUDIO_DEVICE_NONE; // CONST set in ctor
Andy Hung446f4df2019-02-21 12:26:41 -0800708
709 // ThreadLoop statistics per iteration.
Andy Hung8d672e02023-09-15 18:19:28 -0700710 std::atomic<int64_t> mLastIoBeginNs = -1; // set in threadLoop, read by dump()
711 int64_t mLastIoEndNs GUARDED_BY(ThreadBase_ThreadLoop) = -1;
Andy Hung446f4df2019-02-21 12:26:41 -0800712
Andy Hung44d648b2022-04-08 17:33:40 -0700713 // ThreadSnapshot is thread-safe (internally locked)
714 mediautils::ThreadSnapshot mThreadSnapshot;
715
Andy Hung8d672e02023-09-15 18:19:28 -0700716 audio_utils::Statistics<double> mIoJitterMs GUARDED_BY(mutex()) {0.995 /* alpha */};
717 audio_utils::Statistics<double> mProcessTimeMs GUARDED_BY(mutex()) {0.995 /* alpha */};
718
719 // NO_THREAD_SAFETY_ANALYSIS GUARDED_BY(mutex())
Andy Hunge6c37112019-02-26 17:38:10 -0800720 audio_utils::Statistics<double> mLatencyMs{0.995 /* alpha */};
Robert Wu06db0a32021-08-10 19:05:34 +0000721 audio_utils::Statistics<double> mMonopipePipeDepthStats{0.999 /* alpha */};
Andy Hung446f4df2019-02-21 12:26:41 -0800722
Andy Hungd0979812019-02-21 15:51:44 -0800723 // Save the last count when we delivered statistics to mediametrics.
724 int64_t mLastRecordedTimestampVerifierN = 0;
725 int64_t mLastRecordedTimeNs = 0; // BOOTTIME to include suspend.
726
Andy Hungc8fddf32018-08-08 18:32:37 -0700727 bool mIsMsdDevice = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800728 // A condition that must be evaluated by the thread loop has changed and
729 // we must not wait for async write callback in the thread loop before evaluating it
730 bool mSignalPending;
Andy Hungdae27702016-10-31 14:01:16 -0700731
Andy Hung8946a282018-04-19 20:04:56 -0700732#ifdef TEE_SINK
733 NBAIO_Tee mTee;
734#endif
Andy Hungdae27702016-10-31 14:01:16 -0700735 // ActiveTracks is a sorted vector of track type T representing the
736 // active tracks of threadLoop() to be considered by the locked prepare portion.
737 // ActiveTracks should be accessed with the ThreadBase lock held.
738 //
739 // During processing and I/O, the threadLoop does not hold the lock;
740 // hence it does not directly use ActiveTracks. Care should be taken
741 // to hold local strong references or defer removal of tracks
742 // if the threadLoop may still be accessing those tracks due to mix, etc.
743 //
744 // This class updates power information appropriately.
745 //
746
747 template <typename T>
748 class ActiveTracks {
749 public:
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700750 explicit ActiveTracks(SimpleLog *localLog = nullptr)
Andy Hungdae27702016-10-31 14:01:16 -0700751 : mActiveTracksGeneration(0)
752 , mLastActiveTracksGeneration(0)
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700753 , mLocalLog(localLog)
Andy Hungdae27702016-10-31 14:01:16 -0700754 { }
755
756 ~ActiveTracks() {
757 ALOGW_IF(!mActiveTracks.isEmpty(),
758 "ActiveTracks should be empty in destructor");
759 }
760 // returns the last track added (even though it may have been
761 // subsequently removed from ActiveTracks).
762 //
763 // Used for DirectOutputThread to ensure a flush is called when transitioning
764 // to a new track (even though it may be on the same session).
765 // Used for OffloadThread to ensure that volume and mixer state is
766 // taken from the latest track added.
767 //
768 // The latest track is saved with a weak pointer to prevent keeping an
769 // otherwise useless track alive. Thus the function will return nullptr
770 // if the latest track has subsequently been removed and destroyed.
771 sp<T> getLatest() {
772 return mLatestActiveTrack.promote();
773 }
774
775 // SortedVector methods
776 ssize_t add(const sp<T> &track);
777 ssize_t remove(const sp<T> &track);
778 size_t size() const {
779 return mActiveTracks.size();
780 }
Eric Tan39ec8d62018-07-24 09:49:29 -0700781 bool isEmpty() const {
782 return mActiveTracks.isEmpty();
783 }
Andy Hung87c693c2023-07-06 20:56:16 -0700784 ssize_t indexOf(const sp<T>& item) const {
Andy Hungdae27702016-10-31 14:01:16 -0700785 return mActiveTracks.indexOf(item);
786 }
787 sp<T> operator[](size_t index) const {
788 return mActiveTracks[index];
789 }
790 typename SortedVector<sp<T>>::iterator begin() {
791 return mActiveTracks.begin();
792 }
793 typename SortedVector<sp<T>>::iterator end() {
794 return mActiveTracks.end();
795 }
796
797 // Due to Binder recursion optimization, clear() and updatePowerState()
798 // cannot be called from a Binder thread because they may call back into
799 // the original calling process (system server) for BatteryNotifier
800 // (which requires a Java environment that may not be present).
801 // Hence, call clear() and updatePowerState() only from the
802 // ThreadBase thread.
803 void clear();
804 // periodically called in the threadLoop() to update power state uids.
Andy Hungab65b182023-09-06 19:41:47 -0700805 void updatePowerState_l(const sp<ThreadBase>& thread, bool force = false)
806 REQUIRES(audio_utils::ThreadBase_Mutex);
Andy Hungdae27702016-10-31 14:01:16 -0700807
Kevin Rocardc86a7f72018-04-03 09:00:09 -0700808 /** @return true if one or move active tracks was added or removed since the
Jasmine Chaeaa10e42021-05-11 10:11:14 +0800809 * last time this function was called or the vector was created.
810 * true if volume of one of active tracks was changed.
811 */
Kevin Rocard069c2712018-03-29 19:09:14 -0700812 bool readAndClearHasChanged();
813
Eric Laurentdda206a2022-07-08 17:28:35 +0200814 /** Force updating track metadata to audio HAL stream next time
815 * readAndClearHasChanged() is called.
816 */
817 void setHasChanged() { mHasChanged = true; }
818
Andy Hungdae27702016-10-31 14:01:16 -0700819 private:
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700820 void logTrack(const char *funcName, const sp<T> &track) const;
821
Andy Hungd01b0f12016-11-07 16:10:30 -0800822 SortedVector<uid_t> getWakeLockUids() {
823 SortedVector<uid_t> wakeLockUids;
Andy Hungdae27702016-10-31 14:01:16 -0700824 for (const sp<T> &track : mActiveTracks) {
825 wakeLockUids.add(track->uid());
826 }
827 return wakeLockUids; // moved by underlying SharedBuffer
828 }
829
Andy Hungdae27702016-10-31 14:01:16 -0700830 SortedVector<sp<T>> mActiveTracks;
831 int mActiveTracksGeneration;
832 int mLastActiveTracksGeneration;
833 wp<T> mLatestActiveTrack; // latest track added to ActiveTracks
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700834 SimpleLog * const mLocalLog;
Kevin Rocardc86a7f72018-04-03 09:00:09 -0700835 // If the vector has changed since last call to readAndClearHasChanged
Kevin Rocard069c2712018-03-29 19:09:14 -0700836 bool mHasChanged = false;
Andy Hungdae27702016-10-31 14:01:16 -0700837 };
Andy Hung293558a2017-03-21 12:19:20 -0700838
Andy Hungab65b182023-09-06 19:41:47 -0700839 SimpleLog mLocalLog; // locked internally
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700840
841private:
Andy Hungab65b182023-09-06 19:41:47 -0700842 void dumpBase_l(int fd, const Vector<String16>& args) REQUIRES(mutex());
843 void dumpEffectChains_l(int fd, const Vector<String16>& args) REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800844};
845
846// --- PlaybackThread ---
Andy Hung440901d2023-06-29 21:19:25 -0700847class PlaybackThread : public ThreadBase, public virtual IAfPlaybackThread,
848 public StreamOutHalInterfaceCallback,
Andy Hung87c693c2023-07-06 20:56:16 -0700849 public virtual VolumeInterface, public StreamOutHalInterfaceEventCallback {
Eric Laurent81784c32012-11-19 14:55:58 -0800850public:
Andy Hung87c693c2023-07-06 20:56:16 -0700851 sp<IAfPlaybackThread> asIAfPlaybackThread() final {
852 return sp<IAfPlaybackThread>::fromExisting(this);
853 }
Eric Laurent81784c32012-11-19 14:55:58 -0800854
Eric Laurente93cc032016-05-05 10:15:10 -0700855 // retry count before removing active track in case of underrun on offloaded thread:
856 // we need to make sure that AudioTrack client has enough time to send large buffers
857 //FIXME may be more appropriate if expressed in time units. Need to revise how underrun is
858 // handled for offloaded tracks
859 static const int8_t kMaxTrackRetriesOffload = 20;
860 static const int8_t kMaxTrackStartupRetriesOffload = 100;
Andy Hung8ed196a2018-01-05 13:21:11 -0800861 static constexpr uint32_t kMaxTracksPerUid = 40;
Andy Hung1bc088a2018-02-09 15:57:31 -0800862 static constexpr size_t kMaxTracks = 256;
Eric Laurente93cc032016-05-05 10:15:10 -0700863
rago1bb90822017-05-02 18:31:48 -0700864 // Maximum delay (in nanoseconds) for upcoming buffers in suspend mode, otherwise
865 // if delay is greater, the estimated time for timeLoopNextNs is reset.
866 // This allows for catch-up to be done for small delays, while resetting the estimate
867 // for initial conditions or large delays.
868 static const nsecs_t kMaxNextBufferDelayNs = 100000000;
869
Andy Hung583043b2023-07-17 17:05:00 -0700870 PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +0200871 audio_io_handle_t id, type_t type, bool systemReady,
872 audio_config_base_t *mixerConfig = nullptr);
Andy Hung440901d2023-06-29 21:19:25 -0700873 ~PlaybackThread() override;
Eric Laurent81784c32012-11-19 14:55:58 -0800874
Eric Laurent81784c32012-11-19 14:55:58 -0800875 // Thread virtuals
Andy Hung8d672e02023-09-15 18:19:28 -0700876 bool threadLoop() final REQUIRES(ThreadBase_ThreadLoop) EXCLUDES_ThreadBase_Mutex;
Eric Laurent81784c32012-11-19 14:55:58 -0800877
878 // RefBase
Andy Hung440901d2023-06-29 21:19:25 -0700879 void onFirstRef() override;
Eric Laurent81784c32012-11-19 14:55:58 -0800880
Andy Hung440901d2023-06-29 21:19:25 -0700881 status_t checkEffectCompatibility_l(
Andy Hungab65b182023-09-06 19:41:47 -0700882 const effect_descriptor_t* desc, audio_session_t sessionId) final REQUIRES(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -0700883
Andy Hungab65b182023-09-06 19:41:47 -0700884 void addOutputTrack_l(const sp<IAfTrack>& track) final REQUIRES(mutex()) {
Andy Hung87c693c2023-07-06 20:56:16 -0700885 mTracks.add(track);
886 }
887
Eric Laurent81784c32012-11-19 14:55:58 -0800888protected:
889 // Code snippets that were lifted up out of threadLoop()
Andy Hung8d672e02023-09-15 18:19:28 -0700890 virtual void threadLoop_mix() REQUIRES(ThreadBase_ThreadLoop) = 0;
891 virtual void threadLoop_sleepTime() REQUIRES(ThreadBase_ThreadLoop) = 0;
892 virtual ssize_t threadLoop_write() REQUIRES(ThreadBase_ThreadLoop);
893 virtual void threadLoop_drain() REQUIRES(ThreadBase_ThreadLoop);
894 virtual void threadLoop_standby() REQUIRES(ThreadBase_ThreadLoop);
895 virtual void threadLoop_exit() REQUIRES(ThreadBase_ThreadLoop);
896 virtual void threadLoop_removeTracks(const Vector<sp<IAfTrack>>& tracksToRemove)
897 REQUIRES(ThreadBase_ThreadLoop);
Eric Laurent81784c32012-11-19 14:55:58 -0800898
899 // prepareTracks_l reads and writes mActiveTracks, and returns
900 // the pending set of tracks to remove via Vector 'tracksToRemove'. The caller
901 // is responsible for clearing or destroying this Vector later on, when it
902 // is safe to do so. That will drop the final ref count and destroy the tracks.
Andy Hung8d672e02023-09-15 18:19:28 -0700903 virtual mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove)
904 REQUIRES(mutex(), ThreadBase_ThreadLoop) = 0;
905
906 void removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove) REQUIRES(mutex());
907 status_t handleVoipVolume_l(float *volume) REQUIRES(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -0800908
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700909 // StreamOutHalInterfaceCallback implementation
910 virtual void onWriteReady();
911 virtual void onDrainReady();
912 virtual void onError();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800913
Andy Hungee58e4a2023-07-07 13:47:37 -0700914public: // AsyncCallbackThread
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700915 void resetWriteBlocked(uint32_t sequence);
916 void resetDraining(uint32_t sequence);
Andy Hungee58e4a2023-07-07 13:47:37 -0700917protected:
Eric Laurentbfb1b832013-01-07 09:53:42 -0800918
919 virtual bool waitingAsyncCallback();
Andy Hungab65b182023-09-06 19:41:47 -0700920 virtual bool waitingAsyncCallback_l() REQUIRES(mutex());
Andy Hung8d672e02023-09-15 18:19:28 -0700921 virtual bool shouldStandby_l() REQUIRES(mutex(), ThreadBase_ThreadLoop);
Andy Hungab65b182023-09-06 19:41:47 -0700922 virtual void onAddNewTrack_l() REQUIRES(mutex());
Andy Hungee58e4a2023-07-07 13:47:37 -0700923public: // AsyncCallbackThread
Haynes Mathew George4527b9e2016-07-07 19:54:17 -0700924 void onAsyncError(); // error reported by AsyncCallbackThread
Andy Hungee58e4a2023-07-07 13:47:37 -0700925protected:
jiabinf6eb4c32020-02-25 14:06:25 -0800926 // StreamHalInterfaceCodecFormatCallback implementation
927 void onCodecFormatChanged(
Andy Hung440901d2023-06-29 21:19:25 -0700928 const std::basic_string<uint8_t>& metadataBs) final;
jiabinf6eb4c32020-02-25 14:06:25 -0800929
Eric Laurent81784c32012-11-19 14:55:58 -0800930 // ThreadBase virtuals
Andy Hungab65b182023-09-06 19:41:47 -0700931 void preExit() final EXCLUDES_ThreadBase_Mutex;
Eric Laurent81784c32012-11-19 14:55:58 -0800932
Eric Laurent64667972016-03-30 18:19:46 -0700933 virtual bool keepWakeLock() const { return true; }
Andy Hungab65b182023-09-06 19:41:47 -0700934 virtual void acquireWakeLock_l() REQUIRES(mutex()) {
Andy Hungdae27702016-10-31 14:01:16 -0700935 ThreadBase::acquireWakeLock_l();
Andy Hungab65b182023-09-06 19:41:47 -0700936 mActiveTracks.updatePowerState_l(this, true /* force */);
Andy Hungdae27702016-10-31 14:01:16 -0700937 }
Eric Laurent64667972016-03-30 18:19:46 -0700938
Andy Hung8d672e02023-09-15 18:19:28 -0700939 virtual void checkOutputStageEffects()
940 REQUIRES(ThreadBase_ThreadLoop) EXCLUDES_ThreadBase_Mutex {}
Eric Laurent68a40a82022-05-03 18:15:04 +0200941 virtual void setHalLatencyMode_l() {}
942
Eric Laurentb3f315a2021-07-13 15:09:05 +0200943
Andy Hungab65b182023-09-06 19:41:47 -0700944 void dumpInternals_l(int fd, const Vector<String16>& args) override REQUIRES(mutex());
945 void dumpTracks_l(int fd, const Vector<String16>& args) final REQUIRES(mutex());
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700946
Eric Laurent81784c32012-11-19 14:55:58 -0800947public:
948
Andy Hung440901d2023-06-29 21:19:25 -0700949 status_t initCheck() const final { return mOutput == nullptr ? NO_INIT : NO_ERROR; }
Eric Laurent81784c32012-11-19 14:55:58 -0800950
951 // return estimated latency in milliseconds, as reported by HAL
Andy Hung440901d2023-06-29 21:19:25 -0700952 uint32_t latency() const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800953 // same, but lock must already be held
Andy Hungab65b182023-09-06 19:41:47 -0700954 uint32_t latency_l() const final /* REQUIRES(mutex()) */; // NO_THREAD_SAFETY_ANALYSIS
Eric Laurent81784c32012-11-19 14:55:58 -0800955
Eric Laurent6acd1d42017-01-04 14:23:29 -0800956 // VolumeInterface
Andy Hung440901d2023-06-29 21:19:25 -0700957 void setMasterVolume(float value) final;
Andy Hungab65b182023-09-06 19:41:47 -0700958 void setMasterBalance(float balance) override EXCLUDES_ThreadBase_Mutex;
Andy Hung440901d2023-06-29 21:19:25 -0700959 void setMasterMute(bool muted) final;
Andy Hungab65b182023-09-06 19:41:47 -0700960 void setStreamVolume(audio_stream_type_t stream, float value) final EXCLUDES_ThreadBase_Mutex;
961 void setStreamMute(audio_stream_type_t stream, bool muted) final EXCLUDES_ThreadBase_Mutex;
962 float streamVolume(audio_stream_type_t stream) const final EXCLUDES_ThreadBase_Mutex;
Andy Hung440901d2023-06-29 21:19:25 -0700963 void setVolumeForOutput_l(float left, float right) const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800964
Andy Hung440901d2023-06-29 21:19:25 -0700965 sp<IAfTrack> createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -0700966 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -0800967 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700968 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -0800969 uint32_t *sampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -0800970 audio_format_t format,
971 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -0800972 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -0800973 size_t *pNotificationFrameCount,
974 uint32_t notificationsPerBuffer,
975 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -0800976 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -0800977 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -0700978 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700979 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +0000980 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -0800981 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800982 status_t *status /*non-NULL*/,
jiabinf6eb4c32020-02-25 14:06:25 -0800983 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200984 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +0000985 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +0000986 bool isBitPerfect,
Andy Hung972bec12023-08-31 16:13:39 -0700987 audio_output_flags_t* afTrackFlags) final
988 REQUIRES(audio_utils::AudioFlinger_Mutex);
Eric Laurent81784c32012-11-19 14:55:58 -0800989
Andy Hung87c693c2023-07-06 20:56:16 -0700990 bool isTrackActive(const sp<IAfTrack>& track) const final {
991 return mActiveTracks.indexOf(track) >= 0;
992 }
993
Andy Hungab65b182023-09-06 19:41:47 -0700994 AudioStreamOut* getOutput_l() const final REQUIRES(mutex()) { return mOutput; }
Andy Hung8d672e02023-09-15 18:19:28 -0700995 AudioStreamOut* getOutput() const final EXCLUDES_ThreadBase_Mutex;
996 AudioStreamOut* clearOutput() final EXCLUDES_ThreadBase_Mutex;
997
998 // NO_THREAD_SAFETY_ANALYSIS -- probably needs a lock.
Andy Hung440901d2023-06-29 21:19:25 -0700999 sp<StreamHalInterface> stream() const final;
Eric Laurent81784c32012-11-19 14:55:58 -08001000
Andy Hung8d672e02023-09-15 18:19:28 -07001001 // suspend(), restore(), and isSuspended() are implemented atomically.
1002 void suspend() final { ++mSuspended; }
1003 void restore() final {
1004 // if restore() is done without suspend(), get back into
1005 // range so that the next suspend() will operate correctly
1006 while (true) {
1007 int32_t suspended = mSuspended;
1008 if (suspended <= 0) {
1009 ALOGW("%s: invalid mSuspended %d <= 0", __func__, suspended);
1010 return;
1011 }
1012 const int32_t desired = suspended - 1;
1013 if (mSuspended.compare_exchange_weak(suspended, desired)) return;
1014 }
1015 }
1016 bool isSuspended() const final { return mSuspended > 0; }
Eric Laurent81784c32012-11-19 14:55:58 -08001017
Andy Hungab65b182023-09-06 19:41:47 -07001018 String8 getParameters(const String8& keys) EXCLUDES_ThreadBase_Mutex;
1019
1020 // Hold either the AudioFlinger::mutex or the ThreadBase::mutex
1021 void ioConfigChanged_l(audio_io_config_event_t event, pid_t pid = 0,
Andy Hung440901d2023-06-29 21:19:25 -07001022 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final;
Andy Hungab65b182023-09-06 19:41:47 -07001023 status_t getRenderPosition(uint32_t* halFrames, uint32_t* dspFrames) const final
1024 EXCLUDES_ThreadBase_Mutex;
Andy Hung010a1a12014-03-13 13:57:33 -07001025 // Consider also removing and passing an explicit mMainBuffer initialization
Andy Hung8d31fd22023-06-26 19:20:57 -07001026 // parameter to AF::IAfTrack::Track().
Andy Hung440901d2023-06-29 21:19:25 -07001027 float* sinkBuffer() const final {
Andy Hung319587b2023-05-23 14:01:03 -07001028 return reinterpret_cast<float *>(mSinkBuffer); };
Eric Laurent81784c32012-11-19 14:55:58 -08001029
Andy Hungab65b182023-09-06 19:41:47 -07001030 void detachAuxEffect_l(int effectId) final REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001031
Andy Hungab65b182023-09-06 19:41:47 -07001032 status_t attachAuxEffect(const sp<IAfTrack>& track, int EffectId) final
1033 EXCLUDES_ThreadBase_Mutex;
1034 status_t attachAuxEffect_l(const sp<IAfTrack>& track, int EffectId) final REQUIRES(mutex());
Andy Hung440901d2023-06-29 21:19:25 -07001035
Andy Hungab65b182023-09-06 19:41:47 -07001036 status_t addEffectChain_l(const sp<IAfEffectChain>& chain) final REQUIRES(mutex());
1037 size_t removeEffectChain_l(const sp<IAfEffectChain>& chain) final REQUIRES(mutex());
1038 uint32_t hasAudioSession_l(audio_session_t sessionId) const final REQUIRES(mutex()) {
Andy Hungc3d62f92019-03-14 13:38:51 -07001039 return ThreadBase::hasAudioSession_l(sessionId, mTracks);
1040 }
Andy Hungab65b182023-09-06 19:41:47 -07001041 product_strategy_t getStrategyForSession_l(audio_session_t sessionId) const final
1042 REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001043
1044
Andy Hungab65b182023-09-06 19:41:47 -07001045 status_t setSyncEvent(const sp<audioflinger::SyncEvent>& event) final
1046 EXCLUDES_ThreadBase_Mutex;
1047 // could be static.
Andy Hung440901d2023-06-29 21:19:25 -07001048 bool isValidSyncEvent(const sp<audioflinger::SyncEvent>& event) const final;
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001049
Andy Hungab65b182023-09-06 19:41:47 -07001050 // Does this require the AudioFlinger mutex as well?
1051 bool invalidateTracks_l(audio_stream_type_t streamType) final
1052 REQUIRES(mutex());
1053 bool invalidateTracks_l(std::set<audio_port_handle_t>& portIds) final
1054 REQUIRES(mutex());
Andy Hung440901d2023-06-29 21:19:25 -07001055 void invalidateTracks(audio_stream_type_t streamType) override;
jiabinc44b3462022-12-08 12:52:31 -08001056 // Invalidate tracks by a set of port ids. The port id will be removed from
1057 // the given set if the corresponding track is found and invalidated.
Andy Hungab65b182023-09-06 19:41:47 -07001058 void invalidateTracks(std::set<audio_port_handle_t>& portIds) override
1059 EXCLUDES_ThreadBase_Mutex;
Eric Laurent81784c32012-11-19 14:55:58 -08001060
Andy Hung87c693c2023-07-06 20:56:16 -07001061 size_t frameCount() const final { return mNormalFrameCount; }
Glenn Kasten9b58f632013-07-16 11:37:48 -07001062
Andy Hung440901d2023-06-29 21:19:25 -07001063 audio_channel_mask_t mixerChannelMask() const final {
Eric Laurentf1f22e72021-07-13 14:04:14 +02001064 return mMixerChannelMask;
1065 }
1066
Andy Hung8d672e02023-09-15 18:19:28 -07001067 status_t getTimestamp_l(AudioTimestamp& timestamp) final
1068 REQUIRES(mutex(), ThreadBase_ThreadLoop);
Eric Laurent83b88082014-06-20 18:31:16 -07001069
Andy Hungab65b182023-09-06 19:41:47 -07001070 void addPatchTrack(const sp<IAfPatchTrack>& track) final EXCLUDES_ThreadBase_Mutex;
1071 void deletePatchTrack(const sp<IAfPatchTrack>& track) final EXCLUDES_ThreadBase_Mutex;
Eric Laurent83b88082014-06-20 18:31:16 -07001072
Andy Hungab65b182023-09-06 19:41:47 -07001073 // NO_THREAD_SAFETY_ANALYSIS - fix this to use atomics.
Andy Hung440901d2023-06-29 21:19:25 -07001074 void toAudioPortConfig(struct audio_port_config* config) final;
Eric Laurentaccc1472013-09-20 09:36:34 -07001075
Andy Hung10cbff12017-02-21 17:30:14 -08001076 // Return the asynchronous signal wait time.
Andy Hungab65b182023-09-06 19:41:47 -07001077 int64_t computeWaitTimeNs_l() const override REQUIRES(mutex()) { return INT64_MAX; }
Andy Hung1bc088a2018-02-09 15:57:31 -08001078 // returns true if the track is allowed to be added to the thread.
Andy Hung440901d2023-06-29 21:19:25 -07001079 bool isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08001080 audio_channel_mask_t channelMask __unused,
1081 audio_format_t format __unused,
1082 audio_session_t sessionId __unused,
Andy Hungab65b182023-09-06 19:41:47 -07001083 uid_t uid) const override REQUIRES(mutex()) {
Andy Hung1bc088a2018-02-09 15:57:31 -08001084 return trackCountForUid_l(uid) < PlaybackThread::kMaxTracksPerUid
1085 && mTracks.size() < PlaybackThread::kMaxTracks;
1086 }
1087
Andy Hungab65b182023-09-06 19:41:47 -07001088 bool isTimestampCorrectionEnabled_l() const final REQUIRES(mutex()) {
1089 return audio_is_output_devices(mTimestampCorrectedDevice)
1090 && outDeviceTypes_l().count(mTimestampCorrectedDevice) != 0;
Andy Hungc8fddf32018-08-08 18:32:37 -07001091 }
jiabinc52b1ff2019-10-31 17:20:42 -07001092
Andy Hungab65b182023-09-06 19:41:47 -07001093 // NO_THREAD_SAFETY_ANALYSIS - fix this to be atomic.
Andy Hung440901d2023-06-29 21:19:25 -07001094 bool isStreamInitialized() const final {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001095 return !(mOutput == nullptr || mOutput->stream == nullptr);
1096 }
1097
Andy Hung440901d2023-06-29 21:19:25 -07001098 audio_channel_mask_t hapticChannelMask() const final {
jiabineb3bda02020-06-30 14:07:03 -07001099 return mHapticChannelMask;
1100 }
Andy Hung87c693c2023-07-06 20:56:16 -07001101
1102 uint32_t hapticChannelCount() const final {
1103 return mHapticChannelCount;
1104 }
1105
Andy Hung440901d2023-06-29 21:19:25 -07001106 bool supportsHapticPlayback() const final {
jiabineb3bda02020-06-30 14:07:03 -07001107 return (mHapticChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE;
1108 }
1109
Andy Hungab65b182023-09-06 19:41:47 -07001110 void setDownStreamPatch(const struct audio_patch* patch) final EXCLUDES_ThreadBase_Mutex {
Andy Hung8d672e02023-09-15 18:19:28 -07001111 audio_utils::lock_guard _l(mutex());
Eric Laurent74c38dc2020-12-23 18:19:44 +01001112 mDownStreamPatch = *patch;
1113 }
1114
Andy Hungab65b182023-09-06 19:41:47 -07001115 IAfTrack* getTrackById_l(audio_port_handle_t trackId) final REQUIRES(mutex());
jiabinf042b9b2021-05-07 23:46:28 +00001116
Andy Hung440901d2023-06-29 21:19:25 -07001117 bool hasMixer() const final {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001118 return mType == MIXER || mType == DUPLICATING || mType == SPATIALIZER;
Eric Laurentb3f315a2021-07-13 15:09:05 +02001119 }
Eric Laurent68a40a82022-05-03 18:15:04 +02001120
Andy Hung440901d2023-06-29 21:19:25 -07001121 status_t setRequestedLatencyMode(
1122 audio_latency_mode_t /* mode */) override { return INVALID_OPERATION; }
Eric Laurent68a40a82022-05-03 18:15:04 +02001123
Andy Hung440901d2023-06-29 21:19:25 -07001124 status_t getSupportedLatencyModes(
1125 std::vector<audio_latency_mode_t>* /* modes */) override {
Eric Laurent68a40a82022-05-03 18:15:04 +02001126 return INVALID_OPERATION;
1127 }
1128
Andy Hung440901d2023-06-29 21:19:25 -07001129 status_t setBluetoothVariableLatencyEnabled(bool /* enabled */) override{
Eric Laurentb0463942022-12-20 16:31:10 +01001130 return INVALID_OPERATION;
1131 }
Eric Laurent52057642022-12-16 11:45:07 +01001132
Andy Hung972bec12023-08-31 16:13:39 -07001133 void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) override
1134 REQUIRES(audio_utils::AudioFlinger_Mutex);
1135 void stopMelComputation_l() override
1136 REQUIRES(audio_utils::AudioFlinger_Mutex);
Vlad Popab042ee62022-10-20 18:05:00 +02001137
Andy Hung8d672e02023-09-15 18:19:28 -07001138 void setStandby() final EXCLUDES_ThreadBase_Mutex {
1139 audio_utils::lock_guard _l(mutex());
Eric Laurent19952e12023-04-20 10:08:29 +02001140 setStandby_l();
1141 }
1142
Andy Hungab65b182023-09-06 19:41:47 -07001143 void setStandby_l() final REQUIRES(mutex()) {
Eric Laurent19952e12023-04-20 10:08:29 +02001144 mStandby = true;
1145 mHalStarted = false;
1146 mKernelPositionOnStandby =
1147 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
1148 }
1149
Andy Hungab65b182023-09-06 19:41:47 -07001150 bool waitForHalStart() final EXCLUDES_ThreadBase_Mutex {
Andy Hungc5007f82023-08-29 14:26:09 -07001151 audio_utils::unique_lock _l(mutex());
Eric Laurent19952e12023-04-20 10:08:29 +02001152 static const nsecs_t kWaitHalTimeoutNs = seconds(2);
1153 nsecs_t endWaitTimetNs = systemTime() + kWaitHalTimeoutNs;
1154 while (!mHalStarted) {
1155 nsecs_t timeNs = systemTime();
1156 if (timeNs >= endWaitTimetNs) {
1157 break;
1158 }
1159 nsecs_t waitTimeLeftNs = endWaitTimetNs - timeNs;
Andy Hungc5007f82023-08-29 14:26:09 -07001160 mWaitHalStartCV.wait_for(_l, std::chrono::nanoseconds(waitTimeLeftNs));
Eric Laurent19952e12023-04-20 10:08:29 +02001161 }
1162 return mHalStarted;
1163 }
Eric Laurent81784c32012-11-19 14:55:58 -08001164protected:
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001165 // updated by readOutputParameters_l()
Glenn Kasten9b58f632013-07-16 11:37:48 -07001166 size_t mNormalFrameCount; // normal mixer and effects
1167
Andy Hung8d672e02023-09-15 18:19:28 -07001168 // throttle the thread processing
1169 bool mThreadThrottle GUARDED_BY(ThreadBase_ThreadLoop);
1170
1171 // throttle time for MIXER threads - atomic as read by dump()
1172 std::atomic<uint32_t> mThreadThrottleTimeMs;
1173
1174 // notify once per throttling
1175 uint32_t mThreadThrottleEndMs GUARDED_BY(ThreadBase_ThreadLoop);
1176
1177 // half the buffer size in milliseconds
1178 uint32_t mHalfBufferMs GUARDED_BY(ThreadBase_ThreadLoop);
Andy Hung08fb1742015-05-31 23:22:10 -07001179
Andy Hung010a1a12014-03-13 13:57:33 -07001180 void* mSinkBuffer; // frame size aligned sink buffer
Eric Laurent81784c32012-11-19 14:55:58 -08001181
Andy Hung98ef9782014-03-04 14:46:50 -08001182 // TODO:
1183 // Rearrange the buffer info into a struct/class with
1184 // clear, copy, construction, destruction methods.
1185 //
1186 // mSinkBuffer also has associated with it:
1187 //
1188 // mSinkBufferSize: Sink Buffer Size
1189 // mFormat: Sink Buffer Format
1190
Andy Hung69aed5f2014-02-25 17:24:40 -08001191 // Mixer Buffer (mMixerBuffer*)
1192 //
1193 // In the case of floating point or multichannel data, which is not in the
1194 // sink format, it is required to accumulate in a higher precision or greater channel count
1195 // buffer before downmixing or data conversion to the sink buffer.
1196
1197 // Set to "true" to enable the Mixer Buffer otherwise mixer output goes to sink buffer.
Andy Hung8d672e02023-09-15 18:19:28 -07001198 bool mMixerBufferEnabled GUARDED_BY(ThreadBase_ThreadLoop);
Andy Hung69aed5f2014-02-25 17:24:40 -08001199
1200 // Storage, 32 byte aligned (may make this alignment a requirement later).
1201 // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
Andy Hung8d672e02023-09-15 18:19:28 -07001202 void* mMixerBuffer GUARDED_BY(ThreadBase_ThreadLoop);
Andy Hung69aed5f2014-02-25 17:24:40 -08001203
1204 // Size of mMixerBuffer in bytes: mNormalFrameCount * #channels * sampsize.
Andy Hung8d672e02023-09-15 18:19:28 -07001205 size_t mMixerBufferSize GUARDED_BY(ThreadBase_ThreadLoop);
Andy Hung69aed5f2014-02-25 17:24:40 -08001206
1207 // The audio format of mMixerBuffer. Set to AUDIO_FORMAT_PCM_(FLOAT|16_BIT) only.
Andy Hung8d672e02023-09-15 18:19:28 -07001208 audio_format_t mMixerBufferFormat GUARDED_BY(ThreadBase_ThreadLoop);
Andy Hung69aed5f2014-02-25 17:24:40 -08001209
1210 // An internal flag set to true by MixerThread::prepareTracks_l()
1211 // when mMixerBuffer contains valid data after mixing.
Andy Hung8d672e02023-09-15 18:19:28 -07001212 bool mMixerBufferValid GUARDED_BY(ThreadBase_ThreadLoop);
Andy Hung69aed5f2014-02-25 17:24:40 -08001213
Andy Hung98ef9782014-03-04 14:46:50 -08001214 // Effects Buffer (mEffectsBuffer*)
1215 //
1216 // In the case of effects data, which is not in the sink format,
1217 // it is required to accumulate in a different buffer before data conversion
1218 // to the sink buffer.
1219
1220 // Set to "true" to enable the Effects Buffer otherwise effects output goes to sink buffer.
Andy Hung8d672e02023-09-15 18:19:28 -07001221 bool mEffectBufferEnabled;
1222 // NO_THREAD_SAFETY_ANALYSIS: Spatializer access this in addEffectChain_l()
Andy Hung98ef9782014-03-04 14:46:50 -08001223
1224 // Storage, 32 byte aligned (may make this alignment a requirement later).
1225 // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
Andy Hung8d672e02023-09-15 18:19:28 -07001226 void* mEffectBuffer;
1227 // NO_THREAD_SAFETY_ANALYSIS: Spatializer access this in addEffectChain_l()
Andy Hung98ef9782014-03-04 14:46:50 -08001228
1229 // Size of mEffectsBuffer in bytes: mNormalFrameCount * #channels * sampsize.
Andy Hung8d672e02023-09-15 18:19:28 -07001230 size_t mEffectBufferSize;
1231 // NO_THREAD_SAFETY_ANALYSIS: Spatializer access this in addEffectChain_l()
Andy Hung98ef9782014-03-04 14:46:50 -08001232
1233 // The audio format of mEffectsBuffer. Set to AUDIO_FORMAT_PCM_16_BIT only.
Andy Hung8d672e02023-09-15 18:19:28 -07001234 // NO_THREAD_SAFETY_ANALYSIS: Spatializer access this in addEffectChain_l()
1235 audio_format_t mEffectBufferFormat;
Andy Hung98ef9782014-03-04 14:46:50 -08001236
1237 // An internal flag set to true by MixerThread::prepareTracks_l()
1238 // when mEffectsBuffer contains valid data after mixing.
1239 //
1240 // When this is set, all mixer data is routed into the effects buffer
1241 // for any processing (including output processing).
Andy Hung8d672e02023-09-15 18:19:28 -07001242 bool mEffectBufferValid GUARDED_BY(ThreadBase_ThreadLoop);
Andy Hung98ef9782014-03-04 14:46:50 -08001243
jiabinc658e452022-10-21 20:52:21 +00001244 // Set to "true" to enable when data has already copied to sink
Andy Hung8d672e02023-09-15 18:19:28 -07001245 bool mHasDataCopiedToSinkBuffer GUARDED_BY(ThreadBase_ThreadLoop) = false;
jiabinc658e452022-10-21 20:52:21 +00001246
Eric Laurentb62d0362021-10-26 17:40:18 +02001247 // Frame size aligned buffer used as input and output to all post processing effects
1248 // except the Spatializer in a SPATIALIZER thread. Non spatialized tracks are mixed into
1249 // this buffer so that post processing effects can be applied.
Andy Hung8d672e02023-09-15 18:19:28 -07001250 void* mPostSpatializerBuffer GUARDED_BY(mutex()) = nullptr;
Eric Laurentb62d0362021-10-26 17:40:18 +02001251
1252 // Size of mPostSpatializerBuffer in bytes
Andy Hung8d672e02023-09-15 18:19:28 -07001253 size_t mPostSpatializerBufferSize GUARDED_BY(mutex());
Eric Laurent39095982021-08-24 18:29:27 +02001254
Eric Laurent81784c32012-11-19 14:55:58 -08001255 // suspend count, > 0 means suspended. While suspended, the thread continues to pull from
1256 // tracks and mix, but doesn't write to HAL. A2DP and SCO HAL implementations can't handle
1257 // concurrent use of both of them, so Audio Policy Service suspends one of the threads to
1258 // workaround that restriction.
1259 // 'volatile' means accessed via atomic operations and no lock.
Andy Hung8d672e02023-09-15 18:19:28 -07001260 std::atomic<int32_t> mSuspended;
Eric Laurent81784c32012-11-19 14:55:58 -08001261
Andy Hung818e7a32016-02-16 18:08:07 -08001262 int64_t mBytesWritten;
Andy Hung8d672e02023-09-15 18:19:28 -07001263 std::atomic<int64_t> mFramesWritten; // not reset on standby
Dean Wheatley12473e92021-03-18 23:00:55 +11001264 int64_t mLastFramesWritten = -1; // track changes in timestamp
1265 // server frames written.
Andy Hung238fa3d2016-07-28 10:53:22 -07001266 int64_t mSuspendedFrames; // not reset on standby
jiabin245cdd92018-12-07 17:55:15 -08001267
1268 // mHapticChannelMask and mHapticChannelCount will only be valid when the thread support
1269 // haptic playback.
1270 audio_channel_mask_t mHapticChannelMask = AUDIO_CHANNEL_NONE;
1271 uint32_t mHapticChannelCount = 0;
Eric Laurentf1f22e72021-07-13 14:04:14 +02001272
1273 audio_channel_mask_t mMixerChannelMask = AUDIO_CHANNEL_NONE;
1274
Eric Laurent81784c32012-11-19 14:55:58 -08001275 // mMasterMute is in both PlaybackThread and in AudioFlinger. When a
1276 // PlaybackThread needs to find out if master-muted, it checks it's local
1277 // copy rather than the one in AudioFlinger. This optimization saves a lock.
Andy Hung8d672e02023-09-15 18:19:28 -07001278 bool mMasterMute GUARDED_BY(mutex());
1279 void setMasterMute_l(bool muted) REQUIRES(mutex()) { mMasterMute = muted; }
Dean Wheatley12473e92021-03-18 23:00:55 +11001280
1281 auto discontinuityForStandbyOrFlush() const { // call on threadLoop or with lock.
1282 return ((mType == DIRECT && !audio_is_linear_pcm(mFormat))
1283 || mType == OFFLOAD)
1284 ? mTimestampVerifier.DISCONTINUITY_MODE_ZERO
1285 : mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS;
1286 }
1287
Andy Hung8d31fd22023-06-26 19:20:57 -07001288 ActiveTracks<IAfTrack> mActiveTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08001289
Eric Laurent81784c32012-11-19 14:55:58 -08001290 // Time to sleep between cycles when:
1291 virtual uint32_t activeSleepTimeUs() const; // mixer state MIXER_TRACKS_ENABLED
1292 virtual uint32_t idleSleepTimeUs() const = 0; // mixer state MIXER_IDLE
1293 virtual uint32_t suspendSleepTimeUs() const = 0; // audio policy manager suspended us
1294 // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write()
1295 // No sleep in standby mode; waits on a condition
1296
1297 // Code snippets that are temporarily lifted up out of threadLoop() until the merge
Andy Hungab65b182023-09-06 19:41:47 -07001298
1299 // consider unification with MMapThread
1300 virtual void checkSilentMode_l() final REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001301
1302 // Non-trivial for DUPLICATING only
Andy Hung8d672e02023-09-15 18:19:28 -07001303 virtual void saveOutputTracks() REQUIRES(ThreadBase_ThreadLoop) {}
1304 virtual void clearOutputTracks() REQUIRES(ThreadBase_ThreadLoop) {}
Eric Laurent81784c32012-11-19 14:55:58 -08001305
1306 // Cache various calculated values, at threadLoop() entry and after a parameter change
Andy Hung8d672e02023-09-15 18:19:28 -07001307 virtual void cacheParameters_l() REQUIRES(mutex(), ThreadBase_ThreadLoop);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001308 void setCheckOutputStageEffects() override {
1309 mCheckOutputStageEffects.store(true);
1310 }
Eric Laurent81784c32012-11-19 14:55:58 -08001311
Andy Hungab65b182023-09-06 19:41:47 -07001312 virtual uint32_t correctLatency_l(uint32_t latency) const REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001313
Eric Laurent1c333e22014-05-20 10:48:17 -07001314 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
Andy Hungab65b182023-09-06 19:41:47 -07001315 audio_patch_handle_t *handle) REQUIRES(mutex());
1316 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle)
1317 REQUIRES(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -07001318
Andy Hungab65b182023-09-06 19:41:47 -07001319 // NO_THREAD_SAFETY_ANALYSIS - fix this to use atomics
Andy Hung87c693c2023-07-06 20:56:16 -07001320 bool usesHwAvSync() const final { return mType == DIRECT && mOutput != nullptr
Phil Burk6fc2a7c2015-04-30 16:08:10 -07001321 && mHwSupportsPause
1322 && (mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC); }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08001323
Andy Hung1bc088a2018-02-09 15:57:31 -08001324 uint32_t trackCountForUid_l(uid_t uid) const;
Eric Laurentad7dd962016-09-22 12:38:37 -07001325
jiabineb3bda02020-06-30 14:07:03 -07001326 void invalidateTracksForAudioSession_l(
Andy Hungab65b182023-09-06 19:41:47 -07001327 audio_session_t sessionId) const override REQUIRES(mutex()) {
jiabineb3bda02020-06-30 14:07:03 -07001328 ThreadBase::invalidateTracksForAudioSession_l(sessionId, mTracks);
1329 }
1330
Mikhail Naganovbf493082017-04-17 17:37:12 -07001331 DISALLOW_COPY_AND_ASSIGN(PlaybackThread);
Eric Laurent81784c32012-11-19 14:55:58 -08001332
Andy Hungab65b182023-09-06 19:41:47 -07001333 status_t addTrack_l(const sp<IAfTrack>& track) final REQUIRES(mutex());
1334 bool destroyTrack_l(const sp<IAfTrack>& track) final REQUIRES(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07001335
Andy Hungab65b182023-09-06 19:41:47 -07001336 void removeTrack_l(const sp<IAfTrack>& track) REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001337
Andy Hungab65b182023-09-06 19:41:47 -07001338 void readOutputParameters_l() REQUIRES(mutex());
1339 MetadataUpdate updateMetadata_l() final REQUIRES(mutex());
1340 virtual void sendMetadataToBackend_l(const StreamOutHalInterface::SourceMetadata& metadata)
1341 REQUIRES(mutex()) ;
Eric Laurent81784c32012-11-19 14:55:58 -08001342
Andy Hung8d672e02023-09-15 18:19:28 -07001343 void collectTimestamps_l() REQUIRES(mutex(), ThreadBase_ThreadLoop);
Dean Wheatley12473e92021-03-18 23:00:55 +11001344
Andy Hungc0691382018-09-12 18:01:57 -07001345 // The Tracks class manages tracks added and removed from the Thread.
Andy Hung1bc088a2018-02-09 15:57:31 -08001346 template <typename T>
1347 class Tracks {
1348 public:
Andy Hung920f6572022-10-06 12:09:49 -07001349 explicit Tracks(bool saveDeletedTrackIds) :
Andy Hungc0691382018-09-12 18:01:57 -07001350 mSaveDeletedTrackIds(saveDeletedTrackIds) { }
Andy Hung1bc088a2018-02-09 15:57:31 -08001351
1352 // SortedVector methods
Andy Hungc0691382018-09-12 18:01:57 -07001353 ssize_t add(const sp<T> &track) {
1354 const ssize_t index = mTracks.add(track);
1355 LOG_ALWAYS_FATAL_IF(index < 0, "cannot add track");
1356 return index;
1357 }
Andy Hung1bc088a2018-02-09 15:57:31 -08001358 ssize_t remove(const sp<T> &track);
1359 size_t size() const {
1360 return mTracks.size();
1361 }
1362 bool isEmpty() const {
1363 return mTracks.isEmpty();
1364 }
1365 ssize_t indexOf(const sp<T> &item) {
1366 return mTracks.indexOf(item);
1367 }
1368 sp<T> operator[](size_t index) const {
1369 return mTracks[index];
1370 }
1371 typename SortedVector<sp<T>>::iterator begin() {
1372 return mTracks.begin();
1373 }
1374 typename SortedVector<sp<T>>::iterator end() {
1375 return mTracks.end();
1376 }
1377
Andy Hung920f6572022-10-06 12:09:49 -07001378 size_t processDeletedTrackIds(const std::function<void(int)>& f) {
Andy Hungc0691382018-09-12 18:01:57 -07001379 for (const int trackId : mDeletedTrackIds) {
1380 f(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08001381 }
Andy Hungc0691382018-09-12 18:01:57 -07001382 return mDeletedTrackIds.size();
Andy Hung1bc088a2018-02-09 15:57:31 -08001383 }
1384
Andy Hungc0691382018-09-12 18:01:57 -07001385 void clearDeletedTrackIds() { mDeletedTrackIds.clear(); }
Andy Hung1bc088a2018-02-09 15:57:31 -08001386
1387 private:
Andy Hungc0691382018-09-12 18:01:57 -07001388 // Tracks pending deletion for MIXER type threads
1389 const bool mSaveDeletedTrackIds; // true to enable tracking
1390 std::set<int> mDeletedTrackIds;
Andy Hung1bc088a2018-02-09 15:57:31 -08001391
1392 SortedVector<sp<T>> mTracks; // wrapped SortedVector.
1393 };
1394
Andy Hung8d31fd22023-06-26 19:20:57 -07001395 Tracks<IAfTrack> mTracks;
Andy Hung1bc088a2018-02-09 15:57:31 -08001396
Eric Laurent223fd5c2014-11-11 13:43:36 -08001397 stream_type_t mStreamTypes[AUDIO_STREAM_CNT];
Andy Hungee58e4a2023-07-07 13:47:37 -07001398
Eric Laurent81784c32012-11-19 14:55:58 -08001399 AudioStreamOut *mOutput;
1400
1401 float mMasterVolume;
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001402 std::atomic<float> mMasterBalance{};
1403 audio_utils::Balance mBalance;
Eric Laurent81784c32012-11-19 14:55:58 -08001404 int mNumWrites;
1405 int mNumDelayedWrites;
1406 bool mInWrite;
1407
1408 // FIXME rename these former local variables of threadLoop to standard "m" names
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001409 nsecs_t mStandbyTimeNs;
Andy Hung25c2dac2014-02-27 14:56:00 -08001410 size_t mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001411
1412 // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l()
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001413 uint32_t mActiveSleepTimeUs;
1414 uint32_t mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08001415
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001416 uint32_t mSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08001417
1418 // mixer status returned by prepareTracks_l()
Andy Hung8d672e02023-09-15 18:19:28 -07001419 mixer_state mMixerStatus GUARDED_BY(ThreadBase_ThreadLoop); // current cycle
Eric Laurent81784c32012-11-19 14:55:58 -08001420 // previous cycle when in prepareTracks_l()
Andy Hung8d672e02023-09-15 18:19:28 -07001421 mixer_state mMixerStatusIgnoringFastTracks GUARDED_BY(ThreadBase_ThreadLoop);
Eric Laurent81784c32012-11-19 14:55:58 -08001422 // FIXME or a separate ready state per track
1423
1424 // FIXME move these declarations into the specific sub-class that needs them
1425 // MIXER only
Andy Hung8d672e02023-09-15 18:19:28 -07001426 uint32_t sleepTimeShift GUARDED_BY(ThreadBase_ThreadLoop);
Eric Laurent81784c32012-11-19 14:55:58 -08001427
1428 // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value
Andy Hung8d672e02023-09-15 18:19:28 -07001429 nsecs_t mStandbyDelayNs; // GUARDED_BY(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001430
1431 // MIXER only
1432 nsecs_t maxPeriod;
1433
1434 // DUPLICATING only
1435 uint32_t writeFrames;
1436
Andy Hung8d672e02023-09-15 18:19:28 -07001437 size_t mBytesRemaining GUARDED_BY(ThreadBase_ThreadLoop);
1438 size_t mCurrentWriteLength GUARDED_BY(ThreadBase_ThreadLoop);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001439 bool mUseAsyncWrite;
Eric Laurent3b4529e2013-09-05 18:09:19 -07001440 // mWriteAckSequence contains current write sequence on bits 31-1. The write sequence is
1441 // incremented each time a write(), a flush() or a standby() occurs.
1442 // Bit 0 is set when a write blocks and indicates a callback is expected.
1443 // Bit 0 is reset by the async callback thread calling resetWriteBlocked(). Out of sequence
1444 // callbacks are ignored.
1445 uint32_t mWriteAckSequence;
1446 // mDrainSequence contains current drain sequence on bits 31-1. The drain sequence is
1447 // incremented each time a drain is requested or a flush() or standby() occurs.
1448 // Bit 0 is set when the drain() command is called at the HAL and indicates a callback is
1449 // expected.
1450 // Bit 0 is reset by the async callback thread calling resetDraining(). Out of sequence
1451 // callbacks are ignored.
1452 uint32_t mDrainSequence;
Andy Hungee58e4a2023-07-07 13:47:37 -07001453
Eric Laurentbfb1b832013-01-07 09:53:42 -08001454 sp<AsyncCallbackThread> mCallbackThread;
1455
Andy Hungc5007f82023-08-29 14:26:09 -07001456 audio_utils::mutex& audioTrackCbMutex() const { return mAudioTrackCbMutex; }
1457 mutable audio_utils::mutex mAudioTrackCbMutex;
jiabinf6eb4c32020-02-25 14:06:25 -08001458 // Record of IAudioTrackCallback
Andy Hung8d31fd22023-06-26 19:20:57 -07001459 std::map<sp<IAfTrack>, sp<media::IAudioTrackCallback>> mAudioTrackCallbacks;
jiabinf6eb4c32020-02-25 14:06:25 -08001460
Eric Laurent81784c32012-11-19 14:55:58 -08001461 // The HAL output sink is treated as non-blocking, but current implementation is blocking
1462 sp<NBAIO_Sink> mOutputSink;
1463 // If a fast mixer is present, the blocking pipe sink, otherwise clear
1464 sp<NBAIO_Sink> mPipeSink;
1465 // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink
1466 sp<NBAIO_Sink> mNormalSink;
Andy Hungee58e4a2023-07-07 13:47:37 -07001467
Eric Laurent81784c32012-11-19 14:55:58 -08001468 uint32_t mScreenState; // cached copy of gScreenState
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07001469 // TODO: add comment and adjust size as needed
Glenn Kasteneef598c2017-04-03 14:41:13 -07001470 static const size_t kFastMixerLogSize = 8 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -08001471 sp<NBLog::Writer> mFastMixerNBLogWriter;
Andy Hung2148bf02016-11-28 19:01:02 -08001472
Dean Wheatley30d28422018-11-06 10:27:40 +11001473 // Downstream patch latency, available if mDownstreamLatencyStatMs.getN() > 0.
1474 audio_utils::Statistics<double> mDownstreamLatencyStatMs{0.999};
Andy Hung2148bf02016-11-28 19:01:02 -08001475
Eric Laurent19952e12023-04-20 10:08:29 +02001476 // output stream start detection based on render position returned by the kernel
1477 // condition signalled when the output stream has started
Andy Hungc5007f82023-08-29 14:26:09 -07001478 audio_utils::condition_variable mWaitHalStartCV;
Eric Laurent19952e12023-04-20 10:08:29 +02001479 // true when the output stream render position has moved, reset to false in standby
1480 bool mHalStarted = false;
1481 // last kernel render position saved when entering standby
1482 int64_t mKernelPositionOnStandby = 0;
1483
Eric Laurent81784c32012-11-19 14:55:58 -08001484public:
Andy Hung440901d2023-06-29 21:19:25 -07001485 FastTrackUnderruns getFastTrackUnderruns(size_t /* fastIndex */) const override
1486 { return {}; }
1487 const std::atomic<int64_t>& framesWritten() const final { return mFramesWritten; }
Eric Laurent81784c32012-11-19 14:55:58 -08001488
1489protected:
1490 // accessed by both binder threads and within threadLoop(), lock on mutex needed
Andy Hungab65b182023-09-06 19:41:47 -07001491 uint32_t& fastTrackAvailMask_l() final REQUIRES(mutex()) { return mFastTrackAvailMask; }
Andy Hung87c693c2023-07-06 20:56:16 -07001492 uint32_t mFastTrackAvailMask; // bit i set if fast track [i] is available
Eric Laurentd1f69b02014-12-15 14:33:13 -08001493 bool mHwSupportsPause;
1494 bool mHwPaused;
1495 bool mFlushPending;
Eric Laurent7c29ec92017-09-20 17:54:22 -07001496 // volumes last sent to audio HAL with stream->setVolume()
1497 float mLeftVolFloat;
1498 float mRightVolFloat;
Eric Laurent74c38dc2020-12-23 18:19:44 +01001499
1500 // audio patch used by the downstream software patch.
1501 // Only used if ThreadBase::mIsMsdDevice is true.
1502 struct audio_patch mDownStreamPatch;
Eric Laurentb3f315a2021-07-13 15:09:05 +02001503
1504 std::atomic_bool mCheckOutputStageEffects{};
ziyangch8f194f12021-12-01 13:48:04 -08001505
ziyangch8f194f12021-12-01 13:48:04 -08001506
Brian Lindahl65e90012022-07-27 18:01:07 +02001507 // Provides periodic checking for timestamp advancement for underrun detection.
1508 class IsTimestampAdvancing {
1509 public:
1510 // The timestamp will not be checked any faster than the specified time.
Andy Hung920f6572022-10-06 12:09:49 -07001511 explicit IsTimestampAdvancing(nsecs_t minimumTimeBetweenChecksNs)
Brian Lindahl65e90012022-07-27 18:01:07 +02001512 : mMinimumTimeBetweenChecksNs(minimumTimeBetweenChecksNs)
1513 {
1514 clear();
1515 }
1516 // Check if the presentation position has advanced in the last periodic time.
1517 bool check(AudioStreamOut * output);
1518 // Clear the internal state when the playback state changes for the output
1519 // stream.
1520 void clear();
1521 private:
1522 // The minimum time between timestamp checks.
1523 const nsecs_t mMinimumTimeBetweenChecksNs;
1524 // Add differential check on the timestamps to see if there is a change in the
1525 // timestamp frame position between the last call to check.
1526 uint64_t mPreviousPosition;
1527 // The time at which the last check occurred, to ensure we don't check too
1528 // frequently, giving the Audio HAL enough time to update its timestamps.
1529 nsecs_t mPreviousNs;
1530 // The valued is latched so we don't check timestamps too frequently.
1531 bool mLatchedValue;
1532 };
1533 IsTimestampAdvancing mIsTimestampAdvancing;
ziyangch8f194f12021-12-01 13:48:04 -08001534
Brian Lindahl65e90012022-07-27 18:01:07 +02001535 virtual void flushHw_l() {
1536 mIsTimestampAdvancing.clear();
1537 }
Eric Laurent81784c32012-11-19 14:55:58 -08001538};
1539
Eric Laurentb0463942022-12-20 16:31:10 +01001540class MixerThread : public PlaybackThread,
1541 public StreamOutHalInterfaceLatencyModeCallback {
Eric Laurent81784c32012-11-19 14:55:58 -08001542public:
Andy Hung583043b2023-07-17 17:05:00 -07001543 MixerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08001544 AudioStreamOut* output,
1545 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001546 bool systemReady,
Eric Laurentf1f22e72021-07-13 14:04:14 +02001547 type_t type = MIXER,
1548 audio_config_base_t *mixerConfig = nullptr);
Andy Hung440901d2023-06-29 21:19:25 -07001549 ~MixerThread() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001550
Eric Laurentb0463942022-12-20 16:31:10 +01001551 // RefBase
Andy Hung440901d2023-06-29 21:19:25 -07001552 void onFirstRef() override;
Eric Laurentb0463942022-12-20 16:31:10 +01001553
1554 // StreamOutHalInterfaceLatencyModeCallback
1555 void onRecommendedLatencyModeChanged(
Andy Hung440901d2023-06-29 21:19:25 -07001556 std::vector<audio_latency_mode_t> modes) final;
Eric Laurentb0463942022-12-20 16:31:10 +01001557
Eric Laurent81784c32012-11-19 14:55:58 -08001558 // Thread virtuals
1559
Andy Hungab65b182023-09-06 19:41:47 -07001560 bool checkForNewParameter_l(const String8& keyValuePair, status_t& status) final
1561 REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001562
Andy Hung440901d2023-06-29 21:19:25 -07001563 bool isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08001564 audio_channel_mask_t channelMask, audio_format_t format,
Andy Hungab65b182023-09-06 19:41:47 -07001565 audio_session_t sessionId, uid_t uid) const final REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001566protected:
Andy Hung8d672e02023-09-15 18:19:28 -07001567 mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove) override
1568 REQUIRES(mutex(), ThreadBase_ThreadLoop);
Andy Hung440901d2023-06-29 21:19:25 -07001569 uint32_t idleSleepTimeUs() const final;
1570 uint32_t suspendSleepTimeUs() const final;
Andy Hung8d672e02023-09-15 18:19:28 -07001571 void cacheParameters_l() override REQUIRES(mutex(), ThreadBase_ThreadLoop);
Eric Laurent81784c32012-11-19 14:55:58 -08001572
Andy Hungab65b182023-09-06 19:41:47 -07001573 void acquireWakeLock_l() final REQUIRES(mutex()) {
Andy Hungdae27702016-10-31 14:01:16 -07001574 PlaybackThread::acquireWakeLock_l();
Andy Hung818e7a32016-02-16 18:08:07 -08001575 if (hasFastMixer()) {
1576 mFastMixer->setBoottimeOffset(
1577 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME]);
1578 }
1579 }
1580
Andy Hungab65b182023-09-06 19:41:47 -07001581 void dumpInternals_l(int fd, const Vector<String16>& args) override REQUIRES(mutex());
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001582
Eric Laurent81784c32012-11-19 14:55:58 -08001583 // threadLoop snippets
Andy Hung8d672e02023-09-15 18:19:28 -07001584 ssize_t threadLoop_write() override REQUIRES(ThreadBase_ThreadLoop);
1585 void threadLoop_standby() override REQUIRES(ThreadBase_ThreadLoop);
1586 void threadLoop_mix() override REQUIRES(ThreadBase_ThreadLoop);
1587 void threadLoop_sleepTime() override REQUIRES(ThreadBase_ThreadLoop);
Andy Hungab65b182023-09-06 19:41:47 -07001588 uint32_t correctLatency_l(uint32_t latency) const final REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001589
Andy Hung440901d2023-06-29 21:19:25 -07001590 status_t createAudioPatch_l(
Andy Hungab65b182023-09-06 19:41:47 -07001591 const struct audio_patch* patch, audio_patch_handle_t* handle)
1592 final REQUIRES(mutex());
1593 status_t releaseAudioPatch_l(const audio_patch_handle_t handle) final REQUIRES(mutex());
Eric Laurent054d9d32015-04-24 08:48:48 -07001594
Eric Laurent81784c32012-11-19 14:55:58 -08001595 AudioMixer* mAudioMixer; // normal mixer
Eric Laurentb0463942022-12-20 16:31:10 +01001596
1597 // Support low latency mode by default as unless explicitly indicated by the audio HAL
1598 // we assume the audio path is compatible with the head tracking latency requirements
1599 std::vector<audio_latency_mode_t> mSupportedLatencyModes = {AUDIO_LATENCY_MODE_LOW};
1600 // default to invalid value to force first update to the audio HAL
1601 audio_latency_mode_t mSetLatencyMode =
1602 (audio_latency_mode_t)AUDIO_LATENCY_MODE_INVALID;
1603
1604 // Bluetooth Variable latency control logic is enabled or disabled for this thread
1605 std::atomic_bool mBluetoothLatencyModesEnabled;
1606
Eric Laurent81784c32012-11-19 14:55:58 -08001607private:
1608 // one-time initialization, no locks required
Glenn Kasten4d23ca32014-05-13 10:39:51 -07001609 sp<FastMixer> mFastMixer; // non-0 if there is also a fast mixer
Eric Laurent81784c32012-11-19 14:55:58 -08001610 sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread
1611
1612 // contents are not guaranteed to be consistent, no locks required
1613 FastMixerDumpState mFastMixerDumpState;
1614#ifdef STATE_QUEUE_DUMP
1615 StateQueueObserverDump mStateQueueObserverDump;
1616 StateQueueMutatorDump mStateQueueMutatorDump;
1617#endif
1618 AudioWatchdogDump mAudioWatchdogDump;
1619
1620 // accessible only within the threadLoop(), no locks required
1621 // mFastMixer->sq() // for mutating and pushing state
Andy Hung8d672e02023-09-15 18:19:28 -07001622 int32_t mFastMixerFutex GUARDED_BY(ThreadBase_ThreadLoop); // for cold idle
Eric Laurent81784c32012-11-19 14:55:58 -08001623
Andy Hung2ddee192015-12-18 17:34:44 -08001624 std::atomic_bool mMasterMono;
Eric Laurent81784c32012-11-19 14:55:58 -08001625public:
Glenn Kasten4d23ca32014-05-13 10:39:51 -07001626 virtual bool hasFastMixer() const { return mFastMixer != 0; }
Eric Laurent81784c32012-11-19 14:55:58 -08001627 virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const {
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001628 ALOG_ASSERT(fastIndex < FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08001629 return mFastMixerDumpState.mTracks[fastIndex].mUnderruns;
1630 }
Eric Laurent83b88082014-06-20 18:31:16 -07001631
Andy Hungab65b182023-09-06 19:41:47 -07001632 status_t threadloop_getHalTimestamp_l(
Andy Hung8d672e02023-09-15 18:19:28 -07001633 ExtendedTimestamp *timestamp) const override
1634 REQUIRES(mutex(), ThreadBase_ThreadLoop) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07001635 if (mNormalSink.get() != nullptr) {
1636 return mNormalSink->getTimestamp(*timestamp);
1637 }
1638 return INVALID_OPERATION;
1639 }
1640
Eric Laurentb0463942022-12-20 16:31:10 +01001641 status_t getSupportedLatencyModes(
1642 std::vector<audio_latency_mode_t>* modes) override;
1643
1644 status_t setBluetoothVariableLatencyEnabled(bool enabled) override;
1645
Andy Hung2ddee192015-12-18 17:34:44 -08001646protected:
1647 virtual void setMasterMono_l(bool mono) {
1648 mMasterMono.store(mono);
1649 if (mFastMixer != nullptr) { /* hasFastMixer() */
1650 mFastMixer->setMasterMono(mMasterMono);
1651 }
1652 }
1653 // the FastMixer performs mono blend if it exists.
Glenn Kasten03c48d52016-01-27 17:25:17 -08001654 // Blending with limiter is not idempotent,
1655 // and blending without limiter is idempotent but inefficient to do twice.
Andy Hung2ddee192015-12-18 17:34:44 -08001656 virtual bool requireMonoBlend() { return mMasterMono.load() && !hasFastMixer(); }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001657
Andy Hungab65b182023-09-06 19:41:47 -07001658 void setMasterBalance(float balance) override EXCLUDES_ThreadBase_Mutex {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001659 mMasterBalance.store(balance);
1660 if (hasFastMixer()) {
1661 mFastMixer->setMasterBalance(balance);
1662 }
1663 }
Eric Laurentb0463942022-12-20 16:31:10 +01001664
Andy Hungab65b182023-09-06 19:41:47 -07001665 void updateHalSupportedLatencyModes_l() REQUIRES(mutex());
1666 void onHalLatencyModesChanged_l() override REQUIRES(mutex());
1667 void setHalLatencyMode_l() override REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001668};
1669
Andy Hung87c693c2023-07-06 20:56:16 -07001670class DirectOutputThread : public PlaybackThread, public virtual IAfDirectOutputThread {
Eric Laurent81784c32012-11-19 14:55:58 -08001671public:
1672
Andy Hung87c693c2023-07-06 20:56:16 -07001673 sp<IAfDirectOutputThread> asIAfDirectOutputThread() final {
1674 return sp<IAfDirectOutputThread>::fromExisting(this);
1675 }
1676
Andy Hung583043b2023-07-17 17:05:00 -07001677 DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Gareth Fennb18c1a32022-10-05 13:42:36 -07001678 audio_io_handle_t id, bool systemReady,
1679 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07001680 : DirectOutputThread(afThreadCallback, output, id, DIRECT, systemReady, offloadInfo) { }
Andy Hung48f59ed2019-01-28 15:06:59 -08001681
Andy Hungab65b182023-09-06 19:41:47 -07001682 ~DirectOutputThread() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001683
Andy Hung87c693c2023-07-06 20:56:16 -07001684 status_t selectPresentation(int presentationId, int programId) final;
Mikhail Naganovac917ac2018-11-28 14:03:52 -08001685
Eric Laurent81784c32012-11-19 14:55:58 -08001686 // Thread virtuals
1687
Eric Laurent10351942014-05-08 18:49:52 -07001688 virtual bool checkForNewParameter_l(const String8& keyValuePair,
Andy Hungab65b182023-09-06 19:41:47 -07001689 status_t& status) REQUIRES(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001690
Andy Hung8d672e02023-09-15 18:19:28 -07001691 void flushHw_l() override REQUIRES(mutex(), ThreadBase_ThreadLoop);
Eric Laurent81784c32012-11-19 14:55:58 -08001692
Andy Hungab65b182023-09-06 19:41:47 -07001693 void setMasterBalance(float balance) override EXCLUDES_ThreadBase_Mutex;
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001694
Eric Laurent81784c32012-11-19 14:55:58 -08001695protected:
Eric Laurent81784c32012-11-19 14:55:58 -08001696 virtual uint32_t activeSleepTimeUs() const;
1697 virtual uint32_t idleSleepTimeUs() const;
1698 virtual uint32_t suspendSleepTimeUs() const;
Andy Hung8d672e02023-09-15 18:19:28 -07001699 virtual void cacheParameters_l() REQUIRES(mutex(), ThreadBase_ThreadLoop);
Eric Laurent81784c32012-11-19 14:55:58 -08001700
Andy Hungab65b182023-09-06 19:41:47 -07001701 void dumpInternals_l(int fd, const Vector<String16>& args) override REQUIRES(mutex());
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001702
Eric Laurent81784c32012-11-19 14:55:58 -08001703 // threadLoop snippets
Andy Hung8d672e02023-09-15 18:19:28 -07001704 virtual mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove)
1705 REQUIRES(mutex(), ThreadBase_ThreadLoop);
1706 virtual void threadLoop_mix() REQUIRES(ThreadBase_ThreadLoop);
1707 virtual void threadLoop_sleepTime() REQUIRES(ThreadBase_ThreadLoop);
1708 virtual void threadLoop_exit() REQUIRES(ThreadBase_ThreadLoop);
Andy Hungab65b182023-09-06 19:41:47 -07001709 virtual bool shouldStandby_l() REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001710
Andy Hungab65b182023-09-06 19:41:47 -07001711 virtual void onAddNewTrack_l() REQUIRES(mutex());
Phil Burk43b4dcc2015-06-09 16:53:44 -07001712
Gareth Fennb18c1a32022-10-05 13:42:36 -07001713 const audio_offload_info_t mOffloadInfo;
Andy Hung398ffa22022-12-13 19:19:53 -08001714
1715 audioflinger::MonotonicFrameCounter mMonotonicFrameCounter; // for VolumeShaper
Andy Hung48f59ed2019-01-28 15:06:59 -08001716 bool mVolumeShaperActive = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001717
Andy Hung583043b2023-07-17 17:05:00 -07001718 DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Gareth Fennb18c1a32022-10-05 13:42:36 -07001719 audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
1720 const audio_offload_info_t& offloadInfo);
Andy Hungab65b182023-09-06 19:41:47 -07001721 void processVolume_l(IAfTrack *track, bool lastTrack) REQUIRES(mutex());
Gareth Fennb18c1a32022-10-05 13:42:36 -07001722 bool isTunerStream() const { return (mOffloadInfo.content_id > 0); }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001723
Eric Laurent81784c32012-11-19 14:55:58 -08001724 // prepareTracks_l() tells threadLoop_mix() the name of the single active track
Andy Hung8d31fd22023-06-26 19:20:57 -07001725 sp<IAfTrack> mActiveTrack;
Phil Burk43b4dcc2015-06-09 16:53:44 -07001726
Andy Hung8d31fd22023-06-26 19:20:57 -07001727 wp<IAfTrack> mPreviousTrack; // used to detect track switch
Phil Burk43b4dcc2015-06-09 16:53:44 -07001728
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001729 // This must be initialized for initial condition of mMasterBalance = 0 (disabled).
1730 float mMasterBalanceLeft = 1.f;
1731 float mMasterBalanceRight = 1.f;
1732
Eric Laurent81784c32012-11-19 14:55:58 -08001733public:
1734 virtual bool hasFastMixer() const { return false; }
Andy Hung10cbff12017-02-21 17:30:14 -08001735
Andy Hungab65b182023-09-06 19:41:47 -07001736 virtual int64_t computeWaitTimeNs_l() const override REQUIRES(mutex());
Andy Hungf3234512018-07-03 14:51:47 -07001737
1738 status_t threadloop_getHalTimestamp_l(ExtendedTimestamp *timestamp) const override {
1739 // For DIRECT and OFFLOAD threads, query the output sink directly.
1740 if (mOutput != nullptr) {
1741 uint64_t uposition64;
1742 struct timespec time;
1743 if (mOutput->getPresentationPosition(
1744 &uposition64, &time) == OK) {
1745 timestamp->mPosition[ExtendedTimestamp::LOCATION_KERNEL]
1746 = (int64_t)uposition64;
1747 timestamp->mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
1748 = audio_utils_ns_from_timespec(&time);
1749 return NO_ERROR;
1750 }
1751 }
1752 return INVALID_OPERATION;
1753 }
Eric Laurent81784c32012-11-19 14:55:58 -08001754};
1755
Eric Laurentbfb1b832013-01-07 09:53:42 -08001756class OffloadThread : public DirectOutputThread {
1757public:
1758
Andy Hung583043b2023-07-17 17:05:00 -07001759 OffloadThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Gareth Fennb18c1a32022-10-05 13:42:36 -07001760 audio_io_handle_t id, bool systemReady,
1761 const audio_offload_info_t& offloadInfo);
Eric Laurent6a51d7e2013-10-17 18:59:26 -07001762 virtual ~OffloadThread() {};
Andy Hung8d672e02023-09-15 18:19:28 -07001763 void flushHw_l() final REQUIRES(mutex(), ThreadBase_ThreadLoop);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001764
1765protected:
1766 // threadLoop snippets
Andy Hungab65b182023-09-06 19:41:47 -07001767 mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove) final
Andy Hung8d672e02023-09-15 18:19:28 -07001768 REQUIRES(mutex(), ThreadBase_ThreadLoop);
1769 void threadLoop_exit() final REQUIRES(ThreadBase_ThreadLoop);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001770
Andy Hungab65b182023-09-06 19:41:47 -07001771 bool waitingAsyncCallback() final;
1772 bool waitingAsyncCallback_l() final REQUIRES(mutex());
1773 void invalidateTracks(audio_stream_type_t streamType) final EXCLUDES_ThreadBase_Mutex;
1774 void invalidateTracks(std::set<audio_port_handle_t>& portIds) final EXCLUDES_ThreadBase_Mutex;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001775
Andy Hungab65b182023-09-06 19:41:47 -07001776 bool keepWakeLock() const final { return (mKeepWakeLock || (mDrainSequence & 1)); }
Eric Laurent64667972016-03-30 18:19:46 -07001777
Eric Laurentbfb1b832013-01-07 09:53:42 -08001778private:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001779 size_t mPausedWriteLength; // length in bytes of write interrupted by pause
1780 size_t mPausedBytesRemaining; // bytes still waiting in mixbuffer after resume
Eric Laurent64667972016-03-30 18:19:46 -07001781 bool mKeepWakeLock; // keep wake lock while waiting for write callback
Eric Laurentbfb1b832013-01-07 09:53:42 -08001782};
1783
1784class AsyncCallbackThread : public Thread {
1785public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001786 explicit AsyncCallbackThread(const wp<PlaybackThread>& playbackThread);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001787
Eric Laurentbfb1b832013-01-07 09:53:42 -08001788 // Thread virtuals
Andy Hung8d672e02023-09-15 18:19:28 -07001789 bool threadLoop() final;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001790
1791 // RefBase
Andy Hung8d672e02023-09-15 18:19:28 -07001792 void onFirstRef() final;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001793
1794 void exit();
Eric Laurent3b4529e2013-09-05 18:09:19 -07001795 void setWriteBlocked(uint32_t sequence);
1796 void resetWriteBlocked();
1797 void setDraining(uint32_t sequence);
1798 void resetDraining();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07001799 void setAsyncError();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001800
1801private:
Eric Laurent4de95592013-09-26 15:28:21 -07001802 const wp<PlaybackThread> mPlaybackThread;
Eric Laurent3b4529e2013-09-05 18:09:19 -07001803 // mWriteAckSequence corresponds to the last write sequence passed by the offload thread via
1804 // setWriteBlocked(). The sequence is shifted one bit to the left and the lsb is used
1805 // to indicate that the callback has been received via resetWriteBlocked()
Eric Laurent4de95592013-09-26 15:28:21 -07001806 uint32_t mWriteAckSequence;
Eric Laurent3b4529e2013-09-05 18:09:19 -07001807 // mDrainSequence corresponds to the last drain sequence passed by the offload thread via
1808 // setDraining(). The sequence is shifted one bit to the left and the lsb is used
1809 // to indicate that the callback has been received via resetDraining()
Eric Laurent4de95592013-09-26 15:28:21 -07001810 uint32_t mDrainSequence;
Andy Hungc5007f82023-08-29 14:26:09 -07001811 audio_utils::condition_variable mWaitWorkCV;
1812 mutable audio_utils::mutex mMutex;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07001813 bool mAsyncError;
Andy Hungc5007f82023-08-29 14:26:09 -07001814
Andy Hungab65b182023-09-06 19:41:47 -07001815 audio_utils::mutex& mutex() const RETURN_CAPABILITY(audio_utils::AsyncCallbackThread_Mutex) {
1816 return mMutex;
1817 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001818};
1819
Andy Hung87c693c2023-07-06 20:56:16 -07001820class DuplicatingThread : public MixerThread, public IAfDuplicatingThread {
Eric Laurent81784c32012-11-19 14:55:58 -08001821public:
Andy Hung583043b2023-07-17 17:05:00 -07001822 DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
1823 IAfPlaybackThread* mainThread,
Eric Laurent72e3f392015-05-20 14:43:50 -07001824 audio_io_handle_t id, bool systemReady);
Andy Hung87c693c2023-07-06 20:56:16 -07001825 ~DuplicatingThread() override;
1826
1827 sp<IAfDuplicatingThread> asIAfDuplicatingThread() final {
1828 return sp<IAfDuplicatingThread>::fromExisting(this);
1829 }
Eric Laurent81784c32012-11-19 14:55:58 -08001830
1831 // Thread virtuals
Andy Hungab65b182023-09-06 19:41:47 -07001832 void addOutputTrack(IAfPlaybackThread* thread) final EXCLUDES_ThreadBase_Mutex;
1833 void removeOutputTrack(IAfPlaybackThread* thread) final EXCLUDES_ThreadBase_Mutex;
Andy Hung87c693c2023-07-06 20:56:16 -07001834 uint32_t waitTimeMs() const final { return mWaitTimeMs; }
Kevin Rocard069c2712018-03-29 19:09:14 -07001835
Kevin Rocardc86a7f72018-04-03 09:00:09 -07001836 void sendMetadataToBackend_l(
Andy Hungab65b182023-09-06 19:41:47 -07001837 const StreamOutHalInterface::SourceMetadata& metadata) final REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001838protected:
1839 virtual uint32_t activeSleepTimeUs() const;
Andy Hungab65b182023-09-06 19:41:47 -07001840 void dumpInternals_l(int fd, const Vector<String16>& args) final REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001841
1842private:
Andy Hung8d672e02023-09-15 18:19:28 -07001843 bool outputsReady() REQUIRES(ThreadBase_ThreadLoop);
Eric Laurent81784c32012-11-19 14:55:58 -08001844protected:
1845 // threadLoop snippets
Andy Hung8d672e02023-09-15 18:19:28 -07001846 void threadLoop_mix() final REQUIRES(ThreadBase_ThreadLoop);
1847 void threadLoop_sleepTime() final REQUIRES(ThreadBase_ThreadLoop);
1848 ssize_t threadLoop_write() final REQUIRES(ThreadBase_ThreadLoop);
1849 void threadLoop_standby() final REQUIRES(ThreadBase_ThreadLoop);
1850 void cacheParameters_l() final REQUIRES(mutex(), ThreadBase_ThreadLoop);
Eric Laurent81784c32012-11-19 14:55:58 -08001851
1852private:
1853 // called from threadLoop, addOutputTrack, removeOutputTrack
Andy Hungab65b182023-09-06 19:41:47 -07001854 void updateWaitTime_l() REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001855protected:
Andy Hung8d672e02023-09-15 18:19:28 -07001856 void saveOutputTracks() final REQUIRES(mutex(), ThreadBase_ThreadLoop);
1857 void clearOutputTracks() final REQUIRES(mutex(), ThreadBase_ThreadLoop);
Eric Laurent81784c32012-11-19 14:55:58 -08001858private:
1859
1860 uint32_t mWaitTimeMs;
Andy Hung8d672e02023-09-15 18:19:28 -07001861 // NO_THREAD_SAFETY_ANALYSIS GUARDED_BY(ThreadBase_ThreadLoop)
1862 SortedVector <sp<IAfOutputTrack>> outputTracks;
1863 SortedVector <sp<IAfOutputTrack>> mOutputTracks GUARDED_BY(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001864public:
1865 virtual bool hasFastMixer() const { return false; }
Andy Hung1c86ebe2018-05-29 20:29:08 -07001866 status_t threadloop_getHalTimestamp_l(
Andy Hungab65b182023-09-06 19:41:47 -07001867 ExtendedTimestamp *timestamp) const override REQUIRES(mutex()) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07001868 if (mOutputTracks.size() > 0) {
1869 // forward the first OutputTrack's kernel information for timestamp.
1870 const ExtendedTimestamp trackTimestamp =
1871 mOutputTracks[0]->getClientProxyTimestamp();
1872 if (trackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] > 0) {
1873 timestamp->mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
1874 trackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
1875 timestamp->mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
1876 trackTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
1877 return OK; // discard server timestamp - that's ignored.
1878 }
1879 }
1880 return INVALID_OPERATION;
1881 }
Eric Laurent81784c32012-11-19 14:55:58 -08001882};
1883
Eric Laurentb0463942022-12-20 16:31:10 +01001884class SpatializerThread : public MixerThread {
Eric Laurentb3f315a2021-07-13 15:09:05 +02001885public:
Andy Hung583043b2023-07-17 17:05:00 -07001886 SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02001887 AudioStreamOut* output,
1888 audio_io_handle_t id,
1889 bool systemReady,
1890 audio_config_base_t *mixerConfig);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001891
Andy Hung440901d2023-06-29 21:19:25 -07001892 bool hasFastMixer() const final { return false; }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001893
Eric Laurent68a40a82022-05-03 18:15:04 +02001894 // RefBase
Andy Hung440901d2023-06-29 21:19:25 -07001895 void onFirstRef() final;
Eric Laurent68a40a82022-05-03 18:15:04 +02001896
Andy Hungab65b182023-09-06 19:41:47 -07001897 status_t setRequestedLatencyMode(audio_latency_mode_t mode) final EXCLUDES_ThreadBase_Mutex;
Eric Laurent68a40a82022-05-03 18:15:04 +02001898
Eric Laurentb3f315a2021-07-13 15:09:05 +02001899protected:
Andy Hung8d672e02023-09-15 18:19:28 -07001900 void checkOutputStageEffects() final
1901 REQUIRES(ThreadBase_ThreadLoop) EXCLUDES_ThreadBase_Mutex;
Andy Hungab65b182023-09-06 19:41:47 -07001902 void setHalLatencyMode_l() final REQUIRES(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001903
1904private:
Eric Laurent68a40a82022-05-03 18:15:04 +02001905 // Do not request a specific mode by default
1906 audio_latency_mode_t mRequestedLatencyMode = AUDIO_LATENCY_MODE_FREE;
1907
Andy Hung116bc262023-06-20 18:56:17 -07001908 sp<IAfEffectHandle> mFinalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02001909};
1910
Eric Laurent81784c32012-11-19 14:55:58 -08001911// record thread
Andy Hung87c693c2023-07-06 20:56:16 -07001912class RecordThread : public IAfRecordThread, public ThreadBase
Eric Laurent81784c32012-11-19 14:55:58 -08001913{
Andy Hung8d31fd22023-06-26 19:20:57 -07001914 friend class ResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08001915public:
Andy Hung87c693c2023-07-06 20:56:16 -07001916 sp<IAfRecordThread> asIAfRecordThread() final {
1917 return sp<IAfRecordThread>::fromExisting(this);
1918 }
Eric Laurent81784c32012-11-19 14:55:58 -08001919
Andy Hung583043b2023-07-17 17:05:00 -07001920 RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08001921 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08001922 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001923 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08001924 );
Andy Hung440901d2023-06-29 21:19:25 -07001925 ~RecordThread() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001926
1927 // no addTrack_l ?
Andy Hungab65b182023-09-06 19:41:47 -07001928 void destroyTrack_l(const sp<IAfRecordTrack>& track) final REQUIRES(mutex());
1929 void removeTrack_l(const sp<IAfRecordTrack>& track) final REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001930
Eric Laurent81784c32012-11-19 14:55:58 -08001931 // Thread virtuals
Andy Hung8d672e02023-09-15 18:19:28 -07001932 bool threadLoop() final REQUIRES(ThreadBase_ThreadLoop) EXCLUDES_ThreadBase_Mutex;
Andy Hungab65b182023-09-06 19:41:47 -07001933 void preExit() final EXCLUDES_ThreadBase_Mutex;
Eric Laurent81784c32012-11-19 14:55:58 -08001934
1935 // RefBase
Andy Hungab65b182023-09-06 19:41:47 -07001936 void onFirstRef() final EXCLUDES_ThreadBase_Mutex;
Eric Laurent81784c32012-11-19 14:55:58 -08001937
Andy Hung440901d2023-06-29 21:19:25 -07001938 status_t initCheck() const final { return mInput == nullptr ? NO_INIT : NO_ERROR; }
Glenn Kastene198c362013-08-13 09:13:36 -07001939
Andy Hung440901d2023-06-29 21:19:25 -07001940 sp<MemoryDealer> readOnlyHeap() const final { return mReadOnlyHeap; }
Glenn Kastenb880f5e2014-05-07 08:43:45 -07001941
Andy Hung440901d2023-06-29 21:19:25 -07001942 sp<IMemory> pipeMemory() const final { return mPipeMemory; }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001943
Andy Hung87c693c2023-07-06 20:56:16 -07001944 sp<IAfRecordTrack> createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001945 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001946 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001947 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001948 audio_format_t format,
1949 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001950 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08001951 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001952 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07001953 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00001954 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07001955 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001956 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001957 status_t *status /*non-NULL*/,
Eric Laurentec376dc2021-04-08 20:41:22 +02001958 audio_port_handle_t portId,
Andy Hung972bec12023-08-31 16:13:39 -07001959 int32_t maxSharedAudioHistoryMs) final
Andy Hungab65b182023-09-06 19:41:47 -07001960 REQUIRES(audio_utils::AudioFlinger_Mutex) EXCLUDES_ThreadBase_Mutex;
Eric Laurent81784c32012-11-19 14:55:58 -08001961
Andy Hung8d31fd22023-06-26 19:20:57 -07001962 status_t start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08001963 AudioSystem::sync_event_t event,
Andy Hungab65b182023-09-06 19:41:47 -07001964 audio_session_t triggerSession) final EXCLUDES_ThreadBase_Mutex;
Eric Laurent81784c32012-11-19 14:55:58 -08001965
1966 // ask the thread to stop the specified track, and
1967 // return true if the caller should then do it's part of the stopping process
Andy Hungab65b182023-09-06 19:41:47 -07001968 bool stop(IAfRecordTrack* recordTrack) final EXCLUDES_ThreadBase_Mutex;
Andy Hung87c693c2023-07-06 20:56:16 -07001969 AudioStreamIn* getInput() const final { return mInput; }
1970 AudioStreamIn* clearInput() final;
Eric Laurent81784c32012-11-19 14:55:58 -08001971
Andy Hung99b1ba62023-07-14 11:00:08 -07001972 // TODO(b/291317898) Unify with IAfThreadBase
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001973 virtual sp<StreamHalInterface> stream() const;
Eric Laurent81784c32012-11-19 14:55:58 -08001974
Eric Laurent81784c32012-11-19 14:55:58 -08001975
Andy Hungab65b182023-09-06 19:41:47 -07001976 virtual bool checkForNewParameter_l(const String8& keyValuePair,
1977 status_t& status) REQUIRES(mutex());
Andy Hung8d672e02023-09-15 18:19:28 -07001978 virtual void cacheParameters_l() REQUIRES(mutex(), ThreadBase_ThreadLoop) {}
Andy Hungab65b182023-09-06 19:41:47 -07001979 virtual String8 getParameters(const String8& keys) EXCLUDES_ThreadBase_Mutex;
1980
1981 // Hold either the AudioFlinger::mutex or the ThreadBase::mutex
1982 void ioConfigChanged_l(audio_io_config_event_t event, pid_t pid = 0,
Andy Hung87c693c2023-07-06 20:56:16 -07001983 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final;
Eric Laurent1c333e22014-05-20 10:48:17 -07001984 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
Andy Hungab65b182023-09-06 19:41:47 -07001985 audio_patch_handle_t *handle) REQUIRES(mutex());
1986 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle) REQUIRES(mutex());
1987 void updateOutDevices(const DeviceDescriptorBaseVector& outDevices) override
1988 EXCLUDES_ThreadBase_Mutex;
1989 void resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs) override REQUIRES(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07001990
Andy Hungab65b182023-09-06 19:41:47 -07001991 void addPatchTrack(const sp<IAfPatchRecord>& record) final EXCLUDES_ThreadBase_Mutex;
1992 void deletePatchTrack(const sp<IAfPatchRecord>& record) final EXCLUDES_ThreadBase_Mutex;
Eric Laurent83b88082014-06-20 18:31:16 -07001993
Andy Hungab65b182023-09-06 19:41:47 -07001994 void readInputParameters_l() REQUIRES(mutex());
1995 uint32_t getInputFramesLost() const final EXCLUDES_ThreadBase_Mutex;
Eric Laurent81784c32012-11-19 14:55:58 -08001996
Andy Hungab65b182023-09-06 19:41:47 -07001997 virtual status_t addEffectChain_l(const sp<IAfEffectChain>& chain) REQUIRES(mutex());
1998 virtual size_t removeEffectChain_l(const sp<IAfEffectChain>& chain) REQUIRES(mutex());
1999 uint32_t hasAudioSession_l(audio_session_t sessionId) const override REQUIRES(mutex()) {
Andy Hungc3d62f92019-03-14 13:38:51 -07002000 return ThreadBase::hasAudioSession_l(sessionId, mTracks);
2001 }
Eric Laurent81784c32012-11-19 14:55:58 -08002002
2003 // Return the set of unique session IDs across all tracks.
2004 // The keys are the session IDs, and the associated values are meaningless.
2005 // FIXME replace by Set [and implement Bag/Multiset for other uses].
Glenn Kastend848eb42016-03-08 13:42:11 -08002006 KeyedVector<audio_session_t, bool> sessionIds() const;
Eric Laurent81784c32012-11-19 14:55:58 -08002007
Andy Hungab65b182023-09-06 19:41:47 -07002008 status_t setSyncEvent(const sp<audioflinger::SyncEvent>& event) override
2009 EXCLUDES_ThreadBase_Mutex;
Andy Hung068e08e2023-05-15 19:02:55 -07002010 bool isValidSyncEvent(const sp<audioflinger::SyncEvent>& event) const override;
Eric Laurent81784c32012-11-19 14:55:58 -08002011
Andy Hung068e08e2023-05-15 19:02:55 -07002012 static void syncStartEventCallback(const wp<audioflinger::SyncEvent>& event);
Eric Laurent81784c32012-11-19 14:55:58 -08002013
Glenn Kasten9b58f632013-07-16 11:37:48 -07002014 virtual size_t frameCount() const { return mFrameCount; }
Andy Hung87c693c2023-07-06 20:56:16 -07002015 bool hasFastCapture() const final { return mFastCapture != 0; }
Mikhail Naganovdc769682018-05-04 15:34:08 -07002016 virtual void toAudioPortConfig(struct audio_port_config *config);
Glenn Kasten9b58f632013-07-16 11:37:48 -07002017
Andy Hungab65b182023-09-06 19:41:47 -07002018 virtual status_t checkEffectCompatibility_l(const effect_descriptor_t *desc,
2019 audio_session_t sessionId) REQUIRES(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07002020
Andy Hungab65b182023-09-06 19:41:47 -07002021 virtual void acquireWakeLock_l() REQUIRES(mutex()) {
Andy Hungdae27702016-10-31 14:01:16 -07002022 ThreadBase::acquireWakeLock_l();
Andy Hungab65b182023-09-06 19:41:47 -07002023 mActiveTracks.updatePowerState_l(this, true /* force */);
Andy Hungdae27702016-10-31 14:01:16 -07002024 }
2025
Andy Hungab65b182023-09-06 19:41:47 -07002026 void checkBtNrec() final EXCLUDES_ThreadBase_Mutex;
Eric Laurentd8365c52017-07-16 15:27:05 -07002027
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002028 // Sets the UID records silence
Andy Hungab65b182023-09-06 19:41:47 -07002029 void setRecordSilenced(audio_port_handle_t portId, bool silenced) final
2030 EXCLUDES_ThreadBase_Mutex;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002031
Andy Hung87c693c2023-07-06 20:56:16 -07002032 status_t getActiveMicrophones(
Andy Hungab65b182023-09-06 19:41:47 -07002033 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const final
2034 EXCLUDES_ThreadBase_Mutex;
2035 status_t setPreferredMicrophoneDirection(audio_microphone_direction_t direction) final
2036 EXCLUDES_ThreadBase_Mutex;
2037 status_t setPreferredMicrophoneFieldDimension(float zoom) final EXCLUDES_ThreadBase_Mutex;
Paul McLean03a6e6a2018-12-04 10:54:13 -07002038
Andy Hungab65b182023-09-06 19:41:47 -07002039 MetadataUpdate updateMetadata_l() override REQUIRES(mutex());
Kevin Rocard069c2712018-03-29 19:09:14 -07002040
Andy Hung87c693c2023-07-06 20:56:16 -07002041 bool fastTrackAvailable() const final { return mFastTrackAvail; }
2042 void setFastTrackAvailable(bool available) final { mFastTrackAvail = available; }
jiabin01c8f562018-07-19 17:47:28 -07002043
Andy Hungab65b182023-09-06 19:41:47 -07002044 bool isTimestampCorrectionEnabled_l() const override REQUIRES(mutex()) {
Andy Hungc8fddf32018-08-08 18:32:37 -07002045 // checks popcount for exactly one device.
Atneya Nair497fff12022-01-18 16:23:04 -05002046 // Is currently disabled. Before enabling,
2047 // verify compressed record timestamps.
jiabinc52b1ff2019-10-31 17:20:42 -07002048 return audio_is_input_device(mTimestampCorrectedDevice)
Andy Hungab65b182023-09-06 19:41:47 -07002049 && inDeviceType_l() == mTimestampCorrectedDevice;
Andy Hungc8fddf32018-08-08 18:32:37 -07002050 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002051
Andy Hung87c693c2023-07-06 20:56:16 -07002052 status_t shareAudioHistory(const std::string& sharedAudioPackageName,
Eric Laurentec376dc2021-04-08 20:41:22 +02002053 audio_session_t sharedSessionId = AUDIO_SESSION_NONE,
Andy Hungab65b182023-09-06 19:41:47 -07002054 int64_t sharedAudioStartMs = -1) final EXCLUDES_ThreadBase_Mutex;
Eric Laurentec376dc2021-04-08 20:41:22 +02002055 status_t shareAudioHistory_l(const std::string& sharedAudioPackageName,
2056 audio_session_t sharedSessionId = AUDIO_SESSION_NONE,
Andy Hungab65b182023-09-06 19:41:47 -07002057 int64_t sharedAudioStartMs = -1) REQUIRES(mutex());
2058 void resetAudioHistory_l() final REQUIRES(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02002059
Andy Hung440901d2023-06-29 21:19:25 -07002060 bool isStreamInitialized() const final {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002061 return !(mInput == nullptr || mInput->stream == nullptr);
2062 }
2063
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002064protected:
Andy Hungab65b182023-09-06 19:41:47 -07002065 void dumpInternals_l(int fd, const Vector<String16>& args) override REQUIRES(mutex());
2066 void dumpTracks_l(int fd, const Vector<String16>& args) override REQUIRES(mutex());
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002067
Eric Laurent81784c32012-11-19 14:55:58 -08002068private:
Eric Laurent81784c32012-11-19 14:55:58 -08002069 // Enter standby if not already in standby, and set mStandby flag
Glenn Kasten93e471f2013-08-19 08:40:07 -07002070 void standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08002071
2072 // Call the HAL standby method unconditionally, and don't change mStandby flag
Glenn Kastene198c362013-08-13 09:13:36 -07002073 void inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08002074
Andy Hungab65b182023-09-06 19:41:47 -07002075 void checkBtNrec_l() REQUIRES(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07002076
Andy Hungab65b182023-09-06 19:41:47 -07002077 int32_t getOldestFront_l() REQUIRES(mutex());
2078 void updateFronts_l(int32_t offset) REQUIRES(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02002079
Eric Laurent81784c32012-11-19 14:55:58 -08002080 AudioStreamIn *mInput;
Mikhail Naganov2534b382019-09-25 13:05:02 -07002081 Source *mSource;
Andy Hung8d31fd22023-06-26 19:20:57 -07002082 SortedVector <sp<IAfRecordTrack>> mTracks;
Glenn Kasten2b806402013-11-20 16:37:38 -08002083 // mActiveTracks has dual roles: it indicates the current active track(s), and
Andy Hungc5007f82023-08-29 14:26:09 -07002084 // is used together with mStartStopCV to indicate start()/stop() progress
Andy Hung8d31fd22023-06-26 19:20:57 -07002085 ActiveTracks<IAfRecordTrack> mActiveTracks;
Andy Hungdae27702016-10-31 14:01:16 -07002086
Andy Hungc5007f82023-08-29 14:26:09 -07002087 audio_utils::condition_variable mStartStopCV;
Glenn Kasten9b58f632013-07-16 11:37:48 -07002088
Glenn Kasten85948432013-08-19 12:09:05 -07002089 // resampler converts input at HAL Hz to output at AudioRecord client Hz
Glenn Kasten1b291842016-07-18 14:55:21 -07002090 void *mRsmpInBuffer; // size = mRsmpInFramesOA
Glenn Kasten85948432013-08-19 12:09:05 -07002091 size_t mRsmpInFrames; // size of resampler input in frames
2092 size_t mRsmpInFramesP2;// size rounded up to a power-of-2
Glenn Kasten1b291842016-07-18 14:55:21 -07002093 size_t mRsmpInFramesOA;// mRsmpInFramesP2 + over-allocation
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002094
2095 // rolling index that is never cleared
Glenn Kasten85948432013-08-19 12:09:05 -07002096 int32_t mRsmpInRear; // last filled frame + 1
Glenn Kasten85948432013-08-19 12:09:05 -07002097
Eric Laurent81784c32012-11-19 14:55:58 -08002098 // For dumpsys
Glenn Kastenb880f5e2014-05-07 08:43:45 -07002099 const sp<MemoryDealer> mReadOnlyHeap;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07002100
2101 // one-time initialization, no locks required
Glenn Kastenb187de12014-12-30 08:18:15 -08002102 sp<FastCapture> mFastCapture; // non-0 if there is also
2103 // a fast capture
Eric Laurent72e3f392015-05-20 14:43:50 -07002104
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07002105 // FIXME audio watchdog thread
2106
2107 // contents are not guaranteed to be consistent, no locks required
2108 FastCaptureDumpState mFastCaptureDumpState;
2109#ifdef STATE_QUEUE_DUMP
2110 // FIXME StateQueue observer and mutator dump fields
2111#endif
2112 // FIXME audio watchdog dump
2113
2114 // accessible only within the threadLoop(), no locks required
2115 // mFastCapture->sq() // for mutating and pushing state
2116 int32_t mFastCaptureFutex; // for cold idle
2117
2118 // The HAL input source is treated as non-blocking,
2119 // but current implementation is blocking
2120 sp<NBAIO_Source> mInputSource;
2121 // The source for the normal capture thread to read from: mInputSource or mPipeSource
2122 sp<NBAIO_Source> mNormalSource;
2123 // If a fast capture is present, the non-blocking pipe sink written to by fast capture,
2124 // otherwise clear
2125 sp<NBAIO_Sink> mPipeSink;
2126 // If a fast capture is present, the non-blocking pipe source read by normal thread,
2127 // otherwise clear
2128 sp<NBAIO_Source> mPipeSource;
2129 // Depth of pipe from fast capture to normal thread and fast clients, always power of 2
2130 size_t mPipeFramesP2;
2131 // If a fast capture is present, the Pipe as IMemory, otherwise clear
2132 sp<IMemory> mPipeMemory;
2133
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002134 // TODO: add comment and adjust size as needed
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07002135 static const size_t kFastCaptureLogSize = 4 * 1024;
2136 sp<NBLog::Writer> mFastCaptureNBLogWriter;
2137
2138 bool mFastTrackAvail; // true if fast track available
Eric Laurentd8365c52017-07-16 15:27:05 -07002139 // common state to all record threads
2140 std::atomic_bool mBtNrecSuspended;
Andy Hung6427e442018-08-09 12:51:02 -07002141
2142 int64_t mFramesRead = 0; // continuous running counter.
jiabinc52b1ff2019-10-31 17:20:42 -07002143
2144 DeviceDescriptorBaseVector mOutDevices;
Eric Laurentec376dc2021-04-08 20:41:22 +02002145
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02002146 int32_t mMaxSharedAudioHistoryMs = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02002147 std::string mSharedAudioPackageName = {};
Eric Laurent2407ce32021-04-26 14:56:03 +02002148 int32_t mSharedAudioStartFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02002149 audio_session_t mSharedAudioSessionId = AUDIO_SESSION_NONE;
Eric Laurent81784c32012-11-19 14:55:58 -08002150};
Eric Laurent6acd1d42017-01-04 14:23:29 -08002151
Andy Hung7aa7d102023-07-07 15:58:48 -07002152class MmapThread : public ThreadBase, public virtual IAfMmapThread
Eric Laurent6acd1d42017-01-04 14:23:29 -08002153{
2154 public:
Andy Hung583043b2023-07-17 17:05:00 -07002155 MmapThread(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -07002156 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady,
Andy Hungcf10d742020-04-28 15:38:24 -07002157 bool isOut);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002158
Andy Hung7aa7d102023-07-07 15:58:48 -07002159 void configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08002160 audio_stream_type_t streamType,
2161 audio_session_t sessionId,
2162 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07002163 audio_port_handle_t deviceId,
Andy Hung8d672e02023-09-15 18:19:28 -07002164 audio_port_handle_t portId) override EXCLUDES_ThreadBase_Mutex {
2165 audio_utils::lock_guard l(mutex());
2166 configure_l(attr, streamType, sessionId, callback, deviceId, portId);
2167 }
2168
2169 void configure_l(const audio_attributes_t* attr,
2170 audio_stream_type_t streamType,
2171 audio_session_t sessionId,
2172 const sp<MmapStreamCallback>& callback,
2173 audio_port_handle_t deviceId,
2174 audio_port_handle_t portId) REQUIRES(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002175
Andy Hungab65b182023-09-06 19:41:47 -07002176 void disconnect() final EXCLUDES_ThreadBase_Mutex;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002177
Andy Hung440901d2023-06-29 21:19:25 -07002178 // MmapStreamInterface for adapter.
Andy Hung3f49ebb2023-09-19 14:48:41 -07002179 status_t createMmapBuffer(int32_t minSizeFrames, struct audio_mmap_buffer_info* info) final
2180 EXCLUDES_ThreadBase_Mutex;
2181 status_t getMmapPosition(struct audio_mmap_position* position) const override
2182 EXCLUDES_ThreadBase_Mutex;
Andy Hung7aa7d102023-07-07 15:58:48 -07002183 status_t start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07002184 const audio_attributes_t *attr,
Andy Hungab65b182023-09-06 19:41:47 -07002185 audio_port_handle_t* handle) final EXCLUDES_ThreadBase_Mutex;
2186 status_t stop(audio_port_handle_t handle) final EXCLUDES_ThreadBase_Mutex;
2187 status_t standby() final EXCLUDES_ThreadBase_Mutex;
Andy Hung3f49ebb2023-09-19 14:48:41 -07002188 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) const
2189 EXCLUDES_ThreadBase_Mutex = 0;
2190 status_t reportData(const void* buffer, size_t frameCount) override EXCLUDES_ThreadBase_Mutex;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002191
2192 // RefBase
Andy Hung440901d2023-06-29 21:19:25 -07002193 void onFirstRef() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002194
2195 // Thread virtuals
Andy Hung8d672e02023-09-15 18:19:28 -07002196 bool threadLoop() final REQUIRES(ThreadBase_ThreadLoop) EXCLUDES_ThreadBase_Mutex;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002197
Andy Hung440901d2023-06-29 21:19:25 -07002198 // Not in ThreadBase
Andy Hung8d672e02023-09-15 18:19:28 -07002199 virtual void threadLoop_exit() final REQUIRES(ThreadBase_ThreadLoop);
2200 virtual void threadLoop_standby() final REQUIRES(ThreadBase_ThreadLoop);
Andy Hungab65b182023-09-06 19:41:47 -07002201 virtual bool shouldStandby_l() final REQUIRES(mutex()){ return false; }
Andy Hungc5007f82023-08-29 14:26:09 -07002202 virtual status_t exitStandby_l() REQUIRES(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002203
Andy Hung440901d2023-06-29 21:19:25 -07002204 status_t initCheck() const final { return mHalStream == nullptr ? NO_INIT : NO_ERROR; }
2205 size_t frameCount() const final { return mFrameCount; }
Andy Hungab65b182023-09-06 19:41:47 -07002206 bool checkForNewParameter_l(const String8& keyValuePair, status_t& status)
2207 final REQUIRES(mutex());
2208 String8 getParameters(const String8& keys) final EXCLUDES_ThreadBase_Mutex;
2209 void ioConfigChanged_l(audio_io_config_event_t event, pid_t pid = 0,
2210 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final
2211 /* holds either AF::mutex or TB::mutex */;
2212 void readHalParameters_l() REQUIRES(mutex());
Andy Hung8d672e02023-09-15 18:19:28 -07002213 void cacheParameters_l() final REQUIRES(mutex(), ThreadBase_ThreadLoop) {}
Andy Hung440901d2023-06-29 21:19:25 -07002214 status_t createAudioPatch_l(
Andy Hungab65b182023-09-06 19:41:47 -07002215 const struct audio_patch* patch, audio_patch_handle_t* handle) final
2216 REQUIRES(mutex());
2217 status_t releaseAudioPatch_l(const audio_patch_handle_t handle) final
2218 REQUIRES(mutex());
Andy Hung3f49ebb2023-09-19 14:48:41 -07002219 // NO_THREAD_SAFETY_ANALYSIS
Andy Hung440901d2023-06-29 21:19:25 -07002220 void toAudioPortConfig(struct audio_port_config* config) override;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002221
Andy Hung440901d2023-06-29 21:19:25 -07002222 sp<StreamHalInterface> stream() const final { return mHalStream; }
Andy Hungab65b182023-09-06 19:41:47 -07002223 status_t addEffectChain_l(const sp<IAfEffectChain>& chain) final REQUIRES(mutex());
2224 size_t removeEffectChain_l(const sp<IAfEffectChain>& chain) final REQUIRES(mutex());
Andy Hung440901d2023-06-29 21:19:25 -07002225 status_t checkEffectCompatibility_l(
Andy Hungab65b182023-09-06 19:41:47 -07002226 const effect_descriptor_t *desc, audio_session_t sessionId) final REQUIRES(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002227
Andy Hungab65b182023-09-06 19:41:47 -07002228 uint32_t hasAudioSession_l(audio_session_t sessionId) const override REQUIRES(mutex()) {
Andy Hungc3d62f92019-03-14 13:38:51 -07002229 // Note: using mActiveTracks as no mTracks here.
2230 return ThreadBase::hasAudioSession_l(sessionId, mActiveTracks);
2231 }
Andy Hung440901d2023-06-29 21:19:25 -07002232 status_t setSyncEvent(const sp<audioflinger::SyncEvent>& event) final;
2233 bool isValidSyncEvent(const sp<audioflinger::SyncEvent>& event) const final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002234
Andy Hungab65b182023-09-06 19:41:47 -07002235 virtual void checkSilentMode_l() REQUIRES(mutex()) {} // cannot be const (RecordThread)
2236 virtual void processVolume_l() REQUIRES(mutex()) {}
Andy Hung8d672e02023-09-15 18:19:28 -07002237 void checkInvalidTracks_l() REQUIRES(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002238
Andy Hung440901d2023-06-29 21:19:25 -07002239 // Not in ThreadBase
Andy Hung3f49ebb2023-09-19 14:48:41 -07002240 virtual audio_stream_type_t streamType_l() const REQUIRES(mutex()) {
2241 return AUDIO_STREAM_DEFAULT;
2242 }
Andy Hungab65b182023-09-06 19:41:47 -07002243 virtual void invalidateTracks(audio_stream_type_t /* streamType */)
2244 EXCLUDES_ThreadBase_Mutex {}
2245 void invalidateTracks(std::set<audio_port_handle_t>& /* portIds */) override
2246 EXCLUDES_ThreadBase_Mutex {}
Eric Laurent6acd1d42017-01-04 14:23:29 -08002247
Eric Laurent331679c2018-04-16 17:03:16 -07002248 // Sets the UID records silence
Andy Hung7aa7d102023-07-07 15:58:48 -07002249 void setRecordSilenced(
Andy Hungab65b182023-09-06 19:41:47 -07002250 audio_port_handle_t /* portId */, bool /* silenced */) override
2251 EXCLUDES_ThreadBase_Mutex {}
Eric Laurent331679c2018-04-16 17:03:16 -07002252
Andy Hung440901d2023-06-29 21:19:25 -07002253 bool isStreamInitialized() const override { return false; }
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002254
Andy Hungab65b182023-09-06 19:41:47 -07002255 void setClientSilencedState_l(audio_port_handle_t portId, bool silenced) REQUIRES(mutex()) {
jiabin09609032022-06-15 19:26:01 +00002256 mClientSilencedStates[portId] = silenced;
2257 }
2258
Andy Hungab65b182023-09-06 19:41:47 -07002259 size_t eraseClientSilencedState_l(audio_port_handle_t portId) REQUIRES(mutex()) {
jiabin09609032022-06-15 19:26:01 +00002260 return mClientSilencedStates.erase(portId);
2261 }
2262
Andy Hungab65b182023-09-06 19:41:47 -07002263 bool isClientSilenced_l(audio_port_handle_t portId) const REQUIRES(mutex()) {
jiabin09609032022-06-15 19:26:01 +00002264 const auto it = mClientSilencedStates.find(portId);
2265 return it != mClientSilencedStates.end() ? it->second : false;
2266 }
2267
Andy Hungab65b182023-09-06 19:41:47 -07002268 void setClientSilencedIfExists_l(audio_port_handle_t portId, bool silenced)
2269 REQUIRES(mutex()) {
jiabin09609032022-06-15 19:26:01 +00002270 const auto it = mClientSilencedStates.find(portId);
2271 if (it != mClientSilencedStates.end()) {
2272 it->second = silenced;
2273 }
2274 }
2275
Eric Laurent6acd1d42017-01-04 14:23:29 -08002276 protected:
Andy Hungab65b182023-09-06 19:41:47 -07002277 void dumpInternals_l(int fd, const Vector<String16>& args) override REQUIRES(mutex());
2278 void dumpTracks_l(int fd, const Vector<String16>& args) final REQUIRES(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002279
jiabinc52b1ff2019-10-31 17:20:42 -07002280 /**
2281 * @brief mDeviceId current device port unique identifier
2282 */
Andy Hung3f49ebb2023-09-19 14:48:41 -07002283 audio_port_handle_t mDeviceId GUARDED_BY(mutex()) = AUDIO_PORT_HANDLE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07002284
Andy Hung3f49ebb2023-09-19 14:48:41 -07002285 audio_attributes_t mAttr GUARDED_BY(mutex());
2286 audio_session_t mSessionId GUARDED_BY(mutex());
2287 audio_port_handle_t mPortId GUARDED_BY(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002288
Andy Hung3f49ebb2023-09-19 14:48:41 -07002289 wp<MmapStreamCallback> mCallback GUARDED_BY(mutex());
2290 sp<StreamHalInterface> mHalStream; // NO_THREAD_SAFETY_ANALYSIS
2291 sp<DeviceHalInterface> mHalDevice GUARDED_BY(mutex());
2292 AudioHwDevice* const mAudioHwDev GUARDED_BY(mutex());
2293 ActiveTracks<IAfMmapTrack> mActiveTracks GUARDED_BY(mutex());
2294 float mHalVolFloat GUARDED_BY(mutex());
2295 std::map<audio_port_handle_t, bool> mClientSilencedStates GUARDED_BY(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -07002296
Andy Hung3f49ebb2023-09-19 14:48:41 -07002297 int32_t mNoCallbackWarningCount GUARDED_BY(mutex());
2298 static constexpr int32_t kMaxNoCallbackWarnings = 5;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002299};
2300
Andy Hung7aa7d102023-07-07 15:58:48 -07002301class MmapPlaybackThread : public MmapThread, public IAfMmapPlaybackThread,
2302 public virtual VolumeInterface {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002303public:
Andy Hung583043b2023-07-17 17:05:00 -07002304 MmapPlaybackThread(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07002305 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002306
Andy Hung7aa7d102023-07-07 15:58:48 -07002307 sp<IAfMmapPlaybackThread> asIAfMmapPlaybackThread() final {
2308 return sp<IAfMmapPlaybackThread>::fromExisting(this);
2309 }
2310
Andy Hung440901d2023-06-29 21:19:25 -07002311 void configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08002312 audio_stream_type_t streamType,
2313 audio_session_t sessionId,
2314 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07002315 audio_port_handle_t deviceId,
Andy Hung8d672e02023-09-15 18:19:28 -07002316 audio_port_handle_t portId) final EXCLUDES_ThreadBase_Mutex;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002317
Andy Hungab65b182023-09-06 19:41:47 -07002318 AudioStreamOut* clearOutput() final EXCLUDES_ThreadBase_Mutex;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002319
2320 // VolumeInterface
Andy Hung440901d2023-06-29 21:19:25 -07002321 void setMasterVolume(float value) final;
Andy Hungab65b182023-09-06 19:41:47 -07002322 // Needs implementation?
2323 void setMasterBalance(float /* value */) final EXCLUDES_ThreadBase_Mutex {}
Andy Hung8d672e02023-09-15 18:19:28 -07002324 void setMasterMute(bool muted) final EXCLUDES_ThreadBase_Mutex;
Andy Hungab65b182023-09-06 19:41:47 -07002325 void setStreamVolume(audio_stream_type_t stream, float value) final EXCLUDES_ThreadBase_Mutex;
2326 void setStreamMute(audio_stream_type_t stream, bool muted) final EXCLUDES_ThreadBase_Mutex;
2327 float streamVolume(audio_stream_type_t stream) const final EXCLUDES_ThreadBase_Mutex;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002328
Andy Hung8d672e02023-09-15 18:19:28 -07002329 void setMasterMute_l(bool muted) REQUIRES(mutex()) { mMasterMute = muted; }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002330
Andy Hungab65b182023-09-06 19:41:47 -07002331 void invalidateTracks(audio_stream_type_t streamType) final EXCLUDES_ThreadBase_Mutex;
2332 void invalidateTracks(std::set<audio_port_handle_t>& portIds) final EXCLUDES_ThreadBase_Mutex;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002333
Andy Hung3f49ebb2023-09-19 14:48:41 -07002334 audio_stream_type_t streamType_l() const final REQUIRES(mutex()) {
Andy Hung8d672e02023-09-15 18:19:28 -07002335 return mStreamType;
2336 }
Andy Hungab65b182023-09-06 19:41:47 -07002337 void checkSilentMode_l() final REQUIRES(mutex());
2338 void processVolume_l() final REQUIRES(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002339
Andy Hungab65b182023-09-06 19:41:47 -07002340 MetadataUpdate updateMetadata_l() final REQUIRES(mutex());
Kevin Rocard069c2712018-03-29 19:09:14 -07002341
Andy Hung440901d2023-06-29 21:19:25 -07002342 void toAudioPortConfig(struct audio_port_config* config) final;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07002343
Andy Hung440901d2023-06-29 21:19:25 -07002344 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) const final;
jiabinb7d8c5a2020-08-26 17:24:52 -07002345
Andy Hung440901d2023-06-29 21:19:25 -07002346 bool isStreamInitialized() const final {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002347 return !(mOutput == nullptr || mOutput->stream == nullptr);
2348 }
2349
Andy Hung440901d2023-06-29 21:19:25 -07002350 status_t reportData(const void* buffer, size_t frameCount) final;
jiabinfc791ee2023-02-15 19:43:40 +00002351
Andy Hung972bec12023-08-31 16:13:39 -07002352 void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) final
2353 REQUIRES(audio_utils::AudioFlinger_Mutex);
2354 void stopMelComputation_l() final
2355 REQUIRES(audio_utils::AudioFlinger_Mutex);
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002356
Eric Laurent6acd1d42017-01-04 14:23:29 -08002357protected:
Andy Hungab65b182023-09-06 19:41:47 -07002358 void dumpInternals_l(int fd, const Vector<String16>& args) final REQUIRES(mutex());
Andy Hung8d672e02023-09-15 18:19:28 -07002359 float streamVolume_l() const REQUIRES(mutex()) {
Eric Laurent1f9b5e62023-07-03 18:14:07 +02002360 return mStreamTypes[mStreamType].volume;
2361 }
Andy Hung8d672e02023-09-15 18:19:28 -07002362 bool streamMuted_l() const REQUIRES(mutex()) {
Eric Laurent1f9b5e62023-07-03 18:14:07 +02002363 return mStreamTypes[mStreamType].mute;
2364 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002365
Andy Hung8d672e02023-09-15 18:19:28 -07002366 stream_type_t mStreamTypes[AUDIO_STREAM_CNT] GUARDED_BY(mutex());
2367 audio_stream_type_t mStreamType GUARDED_BY(mutex());
2368 float mMasterVolume GUARDED_BY(mutex());
2369 bool mMasterMute GUARDED_BY(mutex());
2370 AudioStreamOut* mOutput; // NO_THREAD_SAFETY_ANALYSIS
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002371
Andy Hung8d672e02023-09-15 18:19:28 -07002372 mediautils::atomic_sp<audio_utils::MelProcessor> mMelProcessor; // locked internally
Eric Laurent6acd1d42017-01-04 14:23:29 -08002373};
2374
Andy Hung7aa7d102023-07-07 15:58:48 -07002375class MmapCaptureThread : public MmapThread, public IAfMmapCaptureThread
Eric Laurent6acd1d42017-01-04 14:23:29 -08002376{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002377public:
Andy Hung583043b2023-07-17 17:05:00 -07002378 MmapCaptureThread(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07002379 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002380
Andy Hung7aa7d102023-07-07 15:58:48 -07002381 sp<IAfMmapCaptureThread> asIAfMmapCaptureThread() final {
2382 return sp<IAfMmapCaptureThread>::fromExisting(this);
2383 }
2384
Andy Hungab65b182023-09-06 19:41:47 -07002385 AudioStreamIn* clearInput() final EXCLUDES_ThreadBase_Mutex;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002386
Andy Hungc5007f82023-08-29 14:26:09 -07002387 status_t exitStandby_l() REQUIRES(mutex()) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002388
Andy Hungab65b182023-09-06 19:41:47 -07002389 MetadataUpdate updateMetadata_l() final REQUIRES(mutex());
2390 void processVolume_l() final REQUIRES(mutex());
2391 void setRecordSilenced(audio_port_handle_t portId, bool silenced) final
2392 EXCLUDES_ThreadBase_Mutex;
Kevin Rocard069c2712018-03-29 19:09:14 -07002393
Andy Hung440901d2023-06-29 21:19:25 -07002394 void toAudioPortConfig(struct audio_port_config* config) final;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07002395
Andy Hung440901d2023-06-29 21:19:25 -07002396 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) const final;
jiabinb7d8c5a2020-08-26 17:24:52 -07002397
Andy Hung440901d2023-06-29 21:19:25 -07002398 bool isStreamInitialized() const final {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002399 return !(mInput == nullptr || mInput->stream == nullptr);
2400 }
2401
Eric Laurent6acd1d42017-01-04 14:23:29 -08002402protected:
2403
Andy Hung8d672e02023-09-15 18:19:28 -07002404 AudioStreamIn* mInput; // NO_THREAD_SAFETY_ANALYSIS
Eric Laurent6acd1d42017-01-04 14:23:29 -08002405};
jiabinc658e452022-10-21 20:52:21 +00002406
2407class BitPerfectThread : public MixerThread {
2408public:
Andy Hung583043b2023-07-17 17:05:00 -07002409 BitPerfectThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut *output,
jiabinc658e452022-10-21 20:52:21 +00002410 audio_io_handle_t id, bool systemReady);
2411
2412protected:
Andy Hung8d672e02023-09-15 18:19:28 -07002413 mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove) final
2414 REQUIRES(mutex(), ThreadBase_ThreadLoop);
2415 void threadLoop_mix() final REQUIRES(ThreadBase_ThreadLoop);
jiabinc658e452022-10-21 20:52:21 +00002416
2417private:
Andy Hung8d672e02023-09-15 18:19:28 -07002418 // These variables are only accessed on the threadLoop; hence need no mutex.
2419 bool mIsBitPerfect GUARDED_BY(ThreadBase_ThreadLoop) = false;
2420 float mVolumeLeft GUARDED_BY(ThreadBase_ThreadLoop) = 0.f;
2421 float mVolumeRight GUARDED_BY(ThreadBase_ThreadLoop) = 0.f;
jiabinc658e452022-10-21 20:52:21 +00002422};
Andy Hunga5a7fc92023-06-23 19:27:19 -07002423
Andy Hungee58e4a2023-07-07 13:47:37 -07002424} // namespace android