blob: 1d6e2447dbc27d56bcbe13d13027d612e1c8939b [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>
Andy Hung88a7afe2024-08-12 20:00:46 -070036#include <psh_utils/Token.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070037#include <timing/MonotonicFrameCounter.h>
38#include <utils/Log.h>
39
Andy Hungee58e4a2023-07-07 13:47:37 -070040namespace android {
Andy Hung440901d2023-06-29 21:19:25 -070041
42class AsyncCallbackThread;
43
44class ThreadBase : public virtual IAfThreadBase, public Thread {
Eric Laurent81784c32012-11-19 14:55:58 -080045public:
Glenn Kasten97b7b752014-09-28 13:04:24 -070046 static const char *threadTypeToString(type_t type);
47
Andy Hung8d672e02023-09-15 18:19:28 -070048 // ThreadBase_ThreadLoop is a virtual mutex (always nullptr) that
49 // guards methods and variables that ONLY run and are accessed
50 // on the single threaded threadLoop().
51 //
52 // As access is by a single thread, the variables are thread safe.
53 static audio_utils::mutex* ThreadBase_ThreadLoop;
54
Andy Hung583043b2023-07-17 17:05:00 -070055 IAfThreadCallback* afThreadCallback() const final { return mAfThreadCallback.get(); }
Andy Hung87c693c2023-07-06 20:56:16 -070056
Andy Hung583043b2023-07-17 17:05:00 -070057 ThreadBase(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -070058 type_t type, bool systemReady, bool isOut);
Andy Hung440901d2023-06-29 21:19:25 -070059 ~ThreadBase() override;
Eric Laurent81784c32012-11-19 14:55:58 -080060
Andy Hung440901d2023-06-29 21:19:25 -070061 status_t readyToRun() final;
Andy Hungab65b182023-09-06 19:41:47 -070062 void clearPowerManager() final EXCLUDES_ThreadBase_Mutex;
Eric Laurent81784c32012-11-19 14:55:58 -080063
64 // base for record and playback
65 enum {
66 CFG_EVENT_IO,
Eric Laurent10351942014-05-08 18:49:52 -070067 CFG_EVENT_PRIO,
68 CFG_EVENT_SET_PARAMETER,
Eric Laurent1c333e22014-05-20 10:48:17 -070069 CFG_EVENT_CREATE_AUDIO_PATCH,
70 CFG_EVENT_RELEASE_AUDIO_PATCH,
jiabinc52b1ff2019-10-31 17:20:42 -070071 CFG_EVENT_UPDATE_OUT_DEVICE,
Eric Laurentb3f315a2021-07-13 15:09:05 +020072 CFG_EVENT_RESIZE_BUFFER,
Eric Laurent68a40a82022-05-03 18:15:04 +020073 CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS,
74 CFG_EVENT_HAL_LATENCY_MODES_CHANGED,
Eric Laurent81784c32012-11-19 14:55:58 -080075 };
76
Eric Laurent10351942014-05-08 18:49:52 -070077 class ConfigEventData: public RefBase {
Eric Laurent81784c32012-11-19 14:55:58 -080078 public:
Eric Laurent81784c32012-11-19 14:55:58 -080079 virtual void dump(char *buffer, size_t size) = 0;
Eric Laurent10351942014-05-08 18:49:52 -070080 protected:
Andy Hungab65b182023-09-06 19:41:47 -070081 ConfigEventData() = default;
Eric Laurent81784c32012-11-19 14:55:58 -080082 };
83
Eric Laurent10351942014-05-08 18:49:52 -070084 // Config event sequence by client if status needed (e.g binder thread calling setParameters()):
85 // 1. create SetParameterConfigEvent. This sets mWaitStatus in config event
Andy Hungc5007f82023-08-29 14:26:09 -070086 // 2. Lock mutex()
Eric Laurent10351942014-05-08 18:49:52 -070087 // 3. Call sendConfigEvent_l(): Append to mConfigEvents and mWaitWorkCV.signal
88 // 4. sendConfigEvent_l() reads status from event->mStatus;
89 // 5. sendConfigEvent_l() returns status
90 // 6. Unlock
91 //
92 // Parameter sequence by server: threadLoop calling processConfigEvents_l():
Andy Hungc5007f82023-08-29 14:26:09 -070093 // 1. Lock mutex()
Eric Laurent10351942014-05-08 18:49:52 -070094 // 2. If there is an entry in mConfigEvents proceed ...
95 // 3. Read first entry in mConfigEvents
96 // 4. Remove first entry from mConfigEvents
97 // 5. Process
98 // 6. Set event->mStatus
Andy Hungc5007f82023-08-29 14:26:09 -070099 // 7. event->mCondition.notify_one()
Eric Laurent10351942014-05-08 18:49:52 -0700100 // 8. Unlock
Eric Laurent81784c32012-11-19 14:55:58 -0800101
Eric Laurent10351942014-05-08 18:49:52 -0700102 class ConfigEvent: public RefBase {
103 public:
Eric Laurentb3f315a2021-07-13 15:09:05 +0200104 void dump(char *buffer, size_t size) {
105 snprintf(buffer, size, "Event type: %d\n", mType);
106 if (mData != nullptr) {
107 snprintf(buffer, size, "Data:\n");
108 mData->dump(buffer, size);
109 }
110 }
Eric Laurent10351942014-05-08 18:49:52 -0700111
Andy Hungab65b182023-09-06 19:41:47 -0700112 audio_utils::mutex& mutex() const RETURN_CAPABILITY(audio_utils::ConfigEvent_Mutex) {
113 return mMutex;
114 }
Eric Laurent10351942014-05-08 18:49:52 -0700115 const int mType; // event type e.g. CFG_EVENT_IO
Andy Hunga6f1cbb2023-10-12 18:18:13 -0700116 // mutex associated with mCondition
117 mutable audio_utils::mutex mMutex{audio_utils::MutexOrder::kConfigEvent_Mutex};
Andy Hungc5007f82023-08-29 14:26:09 -0700118 audio_utils::condition_variable mCondition; // condition for status return
Andy Hungab65b182023-09-06 19:41:47 -0700119
120 // NO_THREAD_SAFETY_ANALYSIS Can we add GUARDED_BY?
Eric Laurent10351942014-05-08 18:49:52 -0700121 status_t mStatus; // status communicated to sender
Andy Hungab65b182023-09-06 19:41:47 -0700122
123 bool mWaitStatus GUARDED_BY(mutex()); // true if sender is waiting for status
124 // true if must wait for system ready to enter event queue
125 bool mRequiresSystemReady GUARDED_BY(mutex());
126
127 // NO_THREAD_SAFETY_ANALYSIS Can we add GUARDED_BY?
128 sp<ConfigEventData> mData; // event specific parameter data
Eric Laurent10351942014-05-08 18:49:52 -0700129
130 protected:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700131 explicit ConfigEvent(int type, bool requiresSystemReady = false) :
Eric Laurent72e3f392015-05-20 14:43:50 -0700132 mType(type), mStatus(NO_ERROR), mWaitStatus(false),
133 mRequiresSystemReady(requiresSystemReady), mData(NULL) {}
Eric Laurent10351942014-05-08 18:49:52 -0700134 };
135
136 class IoConfigEventData : public ConfigEventData {
137 public:
Mikhail Naganov88536df2021-07-26 17:30:29 -0700138 IoConfigEventData(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700139 audio_port_handle_t portId) :
140 mEvent(event), mPid(pid), mPortId(portId) {}
Eric Laurent81784c32012-11-19 14:55:58 -0800141
142 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200143 snprintf(buffer, size, "- IO event: event %d\n", mEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800144 }
145
Mikhail Naganov88536df2021-07-26 17:30:29 -0700146 const audio_io_config_event_t mEvent;
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700147 const pid_t mPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -0700148 const audio_port_handle_t mPortId;
Eric Laurent81784c32012-11-19 14:55:58 -0800149 };
150
Eric Laurent10351942014-05-08 18:49:52 -0700151 class IoConfigEvent : public ConfigEvent {
Eric Laurent81784c32012-11-19 14:55:58 -0800152 public:
Mikhail Naganov88536df2021-07-26 17:30:29 -0700153 IoConfigEvent(audio_io_config_event_t event, pid_t pid, audio_port_handle_t portId) :
Eric Laurent10351942014-05-08 18:49:52 -0700154 ConfigEvent(CFG_EVENT_IO) {
Eric Laurent09f1ed22019-04-24 17:45:17 -0700155 mData = new IoConfigEventData(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700156 }
Eric Laurent10351942014-05-08 18:49:52 -0700157 };
Eric Laurent81784c32012-11-19 14:55:58 -0800158
Eric Laurent10351942014-05-08 18:49:52 -0700159 class PrioConfigEventData : public ConfigEventData {
160 public:
Mikhail Naganov83f04272017-02-07 10:45:09 -0800161 PrioConfigEventData(pid_t pid, pid_t tid, int32_t prio, bool forApp) :
162 mPid(pid), mTid(tid), mPrio(prio), mForApp(forApp) {}
Eric Laurent81784c32012-11-19 14:55:58 -0800163
164 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200165 snprintf(buffer, size, "- Prio event: pid %d, tid %d, prio %d, for app? %d\n",
Mikhail Naganov83f04272017-02-07 10:45:09 -0800166 mPid, mTid, mPrio, mForApp);
Eric Laurent81784c32012-11-19 14:55:58 -0800167 }
168
Eric Laurent81784c32012-11-19 14:55:58 -0800169 const pid_t mPid;
170 const pid_t mTid;
171 const int32_t mPrio;
Mikhail Naganov83f04272017-02-07 10:45:09 -0800172 const bool mForApp;
Eric Laurent81784c32012-11-19 14:55:58 -0800173 };
174
Eric Laurent10351942014-05-08 18:49:52 -0700175 class PrioConfigEvent : public ConfigEvent {
176 public:
Mikhail Naganov83f04272017-02-07 10:45:09 -0800177 PrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp) :
Eric Laurent72e3f392015-05-20 14:43:50 -0700178 ConfigEvent(CFG_EVENT_PRIO, true) {
Mikhail Naganov83f04272017-02-07 10:45:09 -0800179 mData = new PrioConfigEventData(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700180 }
Eric Laurent10351942014-05-08 18:49:52 -0700181 };
182
183 class SetParameterConfigEventData : public ConfigEventData {
184 public:
Andy Hung920f6572022-10-06 12:09:49 -0700185 explicit SetParameterConfigEventData(const String8& keyValuePairs) :
Eric Laurent10351942014-05-08 18:49:52 -0700186 mKeyValuePairs(keyValuePairs) {}
187
188 virtual void dump(char *buffer, size_t size) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000189 snprintf(buffer, size, "- KeyValue: %s\n", mKeyValuePairs.c_str());
Eric Laurent10351942014-05-08 18:49:52 -0700190 }
191
192 const String8 mKeyValuePairs;
193 };
194
195 class SetParameterConfigEvent : public ConfigEvent {
196 public:
Andy Hung920f6572022-10-06 12:09:49 -0700197 explicit SetParameterConfigEvent(const String8& keyValuePairs) :
Eric Laurent10351942014-05-08 18:49:52 -0700198 ConfigEvent(CFG_EVENT_SET_PARAMETER) {
199 mData = new SetParameterConfigEventData(keyValuePairs);
200 mWaitStatus = true;
201 }
Eric Laurent10351942014-05-08 18:49:52 -0700202 };
203
Eric Laurent1c333e22014-05-20 10:48:17 -0700204 class CreateAudioPatchConfigEventData : public ConfigEventData {
205 public:
206 CreateAudioPatchConfigEventData(const struct audio_patch patch,
207 audio_patch_handle_t handle) :
208 mPatch(patch), mHandle(handle) {}
209
210 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200211 snprintf(buffer, size, "- Patch handle: %u\n", mHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -0700212 }
213
214 const struct audio_patch mPatch;
Andy Hungab65b182023-09-06 19:41:47 -0700215 audio_patch_handle_t mHandle; // cannot be const
Eric Laurent1c333e22014-05-20 10:48:17 -0700216 };
217
218 class CreateAudioPatchConfigEvent : public ConfigEvent {
219 public:
220 CreateAudioPatchConfigEvent(const struct audio_patch patch,
221 audio_patch_handle_t handle) :
222 ConfigEvent(CFG_EVENT_CREATE_AUDIO_PATCH) {
223 mData = new CreateAudioPatchConfigEventData(patch, handle);
224 mWaitStatus = true;
225 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700226 };
227
228 class ReleaseAudioPatchConfigEventData : public ConfigEventData {
229 public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700230 explicit ReleaseAudioPatchConfigEventData(const audio_patch_handle_t handle) :
Eric Laurent1c333e22014-05-20 10:48:17 -0700231 mHandle(handle) {}
232
233 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200234 snprintf(buffer, size, "- Patch handle: %u\n", mHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -0700235 }
236
Andy Hungab65b182023-09-06 19:41:47 -0700237 const audio_patch_handle_t mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -0700238 };
239
240 class ReleaseAudioPatchConfigEvent : public ConfigEvent {
241 public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700242 explicit ReleaseAudioPatchConfigEvent(const audio_patch_handle_t handle) :
Eric Laurent1c333e22014-05-20 10:48:17 -0700243 ConfigEvent(CFG_EVENT_RELEASE_AUDIO_PATCH) {
244 mData = new ReleaseAudioPatchConfigEventData(handle);
245 mWaitStatus = true;
246 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700247 };
Eric Laurent81784c32012-11-19 14:55:58 -0800248
jiabinc52b1ff2019-10-31 17:20:42 -0700249 class UpdateOutDevicesConfigEventData : public ConfigEventData {
250 public:
251 explicit UpdateOutDevicesConfigEventData(const DeviceDescriptorBaseVector& outDevices) :
252 mOutDevices(outDevices) {}
253
254 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200255 snprintf(buffer, size, "- Devices: %s", android::toString(mOutDevices).c_str());
jiabinc52b1ff2019-10-31 17:20:42 -0700256 }
257
Andy Hungab65b182023-09-06 19:41:47 -0700258 const DeviceDescriptorBaseVector mOutDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700259 };
260
261 class UpdateOutDevicesConfigEvent : public ConfigEvent {
262 public:
263 explicit UpdateOutDevicesConfigEvent(const DeviceDescriptorBaseVector& outDevices) :
264 ConfigEvent(CFG_EVENT_UPDATE_OUT_DEVICE) {
265 mData = new UpdateOutDevicesConfigEventData(outDevices);
266 }
jiabinc52b1ff2019-10-31 17:20:42 -0700267 };
268
Eric Laurentec376dc2021-04-08 20:41:22 +0200269 class ResizeBufferConfigEventData : public ConfigEventData {
270 public:
271 explicit ResizeBufferConfigEventData(int32_t maxSharedAudioHistoryMs) :
272 mMaxSharedAudioHistoryMs(maxSharedAudioHistoryMs) {}
273
274 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200275 snprintf(buffer, size, "- mMaxSharedAudioHistoryMs: %d", mMaxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +0200276 }
277
Andy Hungab65b182023-09-06 19:41:47 -0700278 const int32_t mMaxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +0200279 };
280
281 class ResizeBufferConfigEvent : public ConfigEvent {
282 public:
283 explicit ResizeBufferConfigEvent(int32_t maxSharedAudioHistoryMs) :
284 ConfigEvent(CFG_EVENT_RESIZE_BUFFER) {
285 mData = new ResizeBufferConfigEventData(maxSharedAudioHistoryMs);
286 }
Eric Laurentec376dc2021-04-08 20:41:22 +0200287 };
288
Eric Laurentb3f315a2021-07-13 15:09:05 +0200289 class CheckOutputStageEffectsEvent : public ConfigEvent {
290 public:
291 CheckOutputStageEffectsEvent() :
292 ConfigEvent(CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS) {
293 }
Eric Laurentb3f315a2021-07-13 15:09:05 +0200294 };
295
Eric Laurent68a40a82022-05-03 18:15:04 +0200296 class HalLatencyModesChangedEvent : public ConfigEvent {
297 public:
298 HalLatencyModesChangedEvent() :
299 ConfigEvent(CFG_EVENT_HAL_LATENCY_MODES_CHANGED) {
300 }
Eric Laurent68a40a82022-05-03 18:15:04 +0200301 };
302
Eric Laurentb3f315a2021-07-13 15:09:05 +0200303
Eric Laurent81784c32012-11-19 14:55:58 -0800304 class PMDeathRecipient : public IBinder::DeathRecipient {
305 public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700306 explicit PMDeathRecipient(const wp<ThreadBase>& thread) : mThread(thread) {}
Eric Laurent81784c32012-11-19 14:55:58 -0800307
308 // IBinder::DeathRecipient
Andy Hungab65b182023-09-06 19:41:47 -0700309 void binderDied(const wp<IBinder>& who) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800310
311 private:
Mikhail Naganovbf493082017-04-17 17:37:12 -0700312 DISALLOW_COPY_AND_ASSIGN(PMDeathRecipient);
Eric Laurent81784c32012-11-19 14:55:58 -0800313
Andy Hungab65b182023-09-06 19:41:47 -0700314 const wp<ThreadBase> mThread;
Eric Laurent81784c32012-11-19 14:55:58 -0800315 };
316
Andy Hung440901d2023-06-29 21:19:25 -0700317 type_t type() const final { return mType; }
318 bool isDuplicating() const final { return (mType == DUPLICATING); }
319 audio_io_handle_t id() const final { return mId;}
Eric Laurent81784c32012-11-19 14:55:58 -0800320
Andy Hung440901d2023-06-29 21:19:25 -0700321 uint32_t sampleRate() const final { return mSampleRate; }
322 audio_channel_mask_t channelMask() const final { return mChannelMask; }
323 audio_channel_mask_t mixerChannelMask() const override { return mChannelMask; }
324 audio_format_t format() const final { return mHALFormat; }
325 uint32_t channelCount() const final { return mChannelCount; }
326 audio_channel_mask_t hapticChannelMask() const override { return AUDIO_CHANNEL_NONE; }
Andy Hung87c693c2023-07-06 20:56:16 -0700327 uint32_t hapticChannelCount() const override { return 0; }
Andy Hungab65b182023-09-06 19:41:47 -0700328 uint32_t latency_l() const override { return 0; } // NO_THREAD_SAFETY_ANALYSIS
329 void setVolumeForOutput_l(float /* left */, float /* right */) const override
330 REQUIRES(mutex()) {}
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700331
332 // Return's the HAL's frame count i.e. fast mixer buffer size.
Andy Hung440901d2023-06-29 21:19:25 -0700333 size_t frameCountHAL() const final { return mFrameCount; }
334 size_t frameSize() const final { return mFrameSize; }
Eric Laurent81784c32012-11-19 14:55:58 -0800335
336 // Should be "virtual status_t requestExitAndWait()" and override same
337 // method in Thread, but Thread::requestExitAndWait() is not yet virtual.
Andy Hungab65b182023-09-06 19:41:47 -0700338 void exit() final EXCLUDES_ThreadBase_Mutex;
339 status_t setParameters(const String8& keyValuePairs) final EXCLUDES_ThreadBase_Mutex;
Andy Hung440901d2023-06-29 21:19:25 -0700340
Andy Hungc5007f82023-08-29 14:26:09 -0700341 // sendConfigEvent_l() must be called with ThreadBase::mutex() held
Eric Laurent10351942014-05-08 18:49:52 -0700342 // Can temporarily release the lock if waiting for a reply from
343 // processConfigEvents_l().
Andy Hungab65b182023-09-06 19:41:47 -0700344 status_t sendConfigEvent_l(sp<ConfigEvent>& event) REQUIRES(mutex());
Andy Hung440901d2023-06-29 21:19:25 -0700345 void sendIoConfigEvent(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 EXCLUDES_ThreadBase_Mutex;
Andy Hung440901d2023-06-29 21:19:25 -0700347 void sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid = 0,
Andy Hungab65b182023-09-06 19:41:47 -0700348 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final REQUIRES(mutex());
349 void sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp) final
350 EXCLUDES_ThreadBase_Mutex;
351 void sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio, bool forApp) final
352 REQUIRES(mutex());
353 status_t sendSetParameterConfigEvent_l(const String8& keyValuePair) final REQUIRES(mutex());
Andy Hung440901d2023-06-29 21:19:25 -0700354 status_t sendCreateAudioPatchConfigEvent(const struct audio_patch* patch,
Andy Hungab65b182023-09-06 19:41:47 -0700355 audio_patch_handle_t* handle) final EXCLUDES_ThreadBase_Mutex;
356 status_t sendReleaseAudioPatchConfigEvent(audio_patch_handle_t handle) final
357 EXCLUDES_ThreadBase_Mutex;
Andy Hung440901d2023-06-29 21:19:25 -0700358 status_t sendUpdateOutDeviceConfigEvent(
Andy Hungab65b182023-09-06 19:41:47 -0700359 const DeviceDescriptorBaseVector& outDevices) final EXCLUDES_ThreadBase_Mutex;
360 void sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs) final REQUIRES(mutex());
361 void sendCheckOutputStageEffectsEvent() final EXCLUDES_ThreadBase_Mutex;
362 void sendCheckOutputStageEffectsEvent_l() final REQUIRES(mutex());
363 void sendHalLatencyModesChangedEvent_l() final REQUIRES(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +0200364
Andy Hungab65b182023-09-06 19:41:47 -0700365 void processConfigEvents_l() final REQUIRES(mutex());
Andy Hung440901d2023-06-29 21:19:25 -0700366 void setCheckOutputStageEffects() override {}
367 void updateOutDevices(const DeviceDescriptorBaseVector& outDevices) override;
368 void toAudioPortConfig(struct audio_port_config* config) override;
Andy Hungab65b182023-09-06 19:41:47 -0700369 void resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs) override REQUIRES(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700370
Andy Hung440901d2023-06-29 21:19:25 -0700371 // see note at declaration of mStandby, mOutDevice and mInDevice
372 bool inStandby() const override { return mStandby; }
Andy Hungab65b182023-09-06 19:41:47 -0700373 const DeviceTypeSet outDeviceTypes_l() const final REQUIRES(mutex()) {
Andy Hung440901d2023-06-29 21:19:25 -0700374 return getAudioDeviceTypes(mOutDeviceTypeAddrs);
375 }
Andy Hungab65b182023-09-06 19:41:47 -0700376 audio_devices_t inDeviceType_l() const final REQUIRES(mutex()) {
377 return mInDeviceTypeAddr.mType;
378 }
379 DeviceTypeSet getDeviceTypes_l() const final REQUIRES(mutex()) {
380 return isOutput() ? outDeviceTypes_l() : DeviceTypeSet({inDeviceType_l()});
Andy Hung440901d2023-06-29 21:19:25 -0700381 }
Eric Laurent81784c32012-11-19 14:55:58 -0800382
Liz Pruckaac078262024-07-29 15:39:16 +0000383 const AudioDeviceTypeAddrVector& outDeviceTypeAddrs() const final REQUIRES(mutex()) {
Andy Hung440901d2023-06-29 21:19:25 -0700384 return mOutDeviceTypeAddrs;
385 }
Liz Pruckaac078262024-07-29 15:39:16 +0000386 const AudioDeviceTypeAddr& inDeviceTypeAddr() const final REQUIRES(mutex()) {
Andy Hung440901d2023-06-29 21:19:25 -0700387 return mInDeviceTypeAddr;
388 }
Andy Hung293558a2017-03-21 12:19:20 -0700389
Andy Hung440901d2023-06-29 21:19:25 -0700390 bool isOutput() const final { return mIsOut; }
jiabin8f278ee2019-11-11 12:16:27 -0800391
Andy Hung440901d2023-06-29 21:19:25 -0700392 bool isOffloadOrMmap() const final {
393 switch (mType) {
394 case OFFLOAD:
395 case MMAP_PLAYBACK:
396 case MMAP_CAPTURE:
397 return true;
398 default:
399 return false;
400 }
401 }
Eric Laurent81784c32012-11-19 14:55:58 -0800402
Andy Hung440901d2023-06-29 21:19:25 -0700403 sp<IAfEffectHandle> createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -0700404 const sp<Client>& client,
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700405 const sp<media::IEffectClient>& effectClient,
Eric Laurent81784c32012-11-19 14:55:58 -0800406 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -0800407 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800408 effect_descriptor_t *desc,
409 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -0800410 status_t *status /*non-NULL*/,
Eric Laurent2fe0acd2020-03-13 14:30:46 -0700411 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +0200412 bool probe,
Andy Hung972bec12023-08-31 16:13:39 -0700413 bool notifyFramesProcessed) final
414 REQUIRES(audio_utils::AudioFlinger_Mutex);
Eric Laurent81784c32012-11-19 14:55:58 -0800415
416 // return values for hasAudioSession (bit field)
417 enum effect_state {
418 EFFECT_SESSION = 0x1, // the audio session corresponds to at least one
419 // effect
Eric Laurent4c415062016-06-17 16:14:16 -0700420 TRACK_SESSION = 0x2, // the audio session corresponds to at least one
Eric Laurent81784c32012-11-19 14:55:58 -0800421 // track
Eric Laurentb62d0362021-10-26 17:40:18 +0200422 FAST_SESSION = 0x4, // the audio session corresponds to at least one
Eric Laurent4c415062016-06-17 16:14:16 -0700423 // fast track
jiabinc658e452022-10-21 20:52:21 +0000424 SPATIALIZED_SESSION = 0x8, // the audio session corresponds to at least one
425 // spatialized track
426 BIT_PERFECT_SESSION = 0x10 // the audio session corresponds to at least one
427 // bit-perfect track
Eric Laurent81784c32012-11-19 14:55:58 -0800428 };
429
Andy Hung440901d2023-06-29 21:19:25 -0700430 // get effect chain corresponding to session Id.
431 sp<IAfEffectChain> getEffectChain(audio_session_t sessionId) const final;
432 // same as getEffectChain() but must be called with ThreadBase mutex locked
Andy Hung8d672e02023-09-15 18:19:28 -0700433 sp<IAfEffectChain> getEffectChain_l(audio_session_t sessionId) const final REQUIRES(mutex());
434 std::vector<int> getEffectIds_l(audio_session_t sessionId) const final REQUIRES(mutex());
Andy Hung440901d2023-06-29 21:19:25 -0700435
Eric Laurent81784c32012-11-19 14:55:58 -0800436 // lock all effect chains Mutexes. Must be called before releasing the
437 // ThreadBase mutex before processing the mixer and effects. This guarantees the
438 // integrity of the chains during the process.
439 // Also sets the parameter 'effectChains' to current value of mEffectChains.
Shunkai Yaof4847652024-01-12 00:25:20 +0000440 void lockEffectChains_l(Vector<sp<IAfEffectChain>>& effectChains) final
Shunkai Yaod125e402024-01-20 03:19:06 +0000441 REQUIRES(audio_utils::ThreadBase_Mutex) ACQUIRE(audio_utils::EffectChain_Mutex);
Eric Laurent81784c32012-11-19 14:55:58 -0800442 // unlock effect chains after process
Shunkai Yaod125e402024-01-20 03:19:06 +0000443 void unlockEffectChains(const Vector<sp<IAfEffectChain>>& effectChains) final
444 RELEASE(audio_utils::EffectChain_Mutex);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800445 // get a copy of mEffectChains vector
Andy Hungab65b182023-09-06 19:41:47 -0700446 Vector<sp<IAfEffectChain>> getEffectChains_l() const final REQUIRES(mutex()) {
447 return mEffectChains;
448 }
Eric Laurent81784c32012-11-19 14:55:58 -0800449 // set audio mode to all effect chains
Andy Hung440901d2023-06-29 21:19:25 -0700450 void setMode(audio_mode_t mode) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800451 // get effect module with corresponding ID on specified audio session
Andy Hung440901d2023-06-29 21:19:25 -0700452 sp<IAfEffectModule> getEffect(audio_session_t sessionId, int effectId) const final;
Andy Hungab65b182023-09-06 19:41:47 -0700453 sp<IAfEffectModule> getEffect_l(audio_session_t sessionId, int effectId) const final
454 REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800455 // add and effect module. Also creates the effect chain is none exists for
Eric Laurent6c796322019-04-09 14:13:17 -0700456 // the effects audio session. Only called in a context of moving an effect
457 // from one thread to another
Andy Hung972bec12023-08-31 16:13:39 -0700458 status_t addEffect_ll(const sp<IAfEffectModule>& effect) final
459 REQUIRES(audio_utils::AudioFlinger_Mutex, mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800460 // remove and effect module. Also removes the effect chain is this was the last
461 // effect
Andy Hungab65b182023-09-06 19:41:47 -0700462 void removeEffect_l(const sp<IAfEffectModule>& effect, bool release = false) final
463 REQUIRES(mutex());
Eric Laurent0d5a2ed2016-12-01 15:28:29 -0800464 // disconnect an effect handle from module and destroy module if last handle
Andy Hung440901d2023-06-29 21:19:25 -0700465 void disconnectEffectHandle(IAfEffectHandle* handle, bool unpinIfLast) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800466 // detach all tracks connected to an auxiliary effect
Andy Hungab65b182023-09-06 19:41:47 -0700467 void detachAuxEffect_l(int /* effectId */) override REQUIRES(mutex()) {}
Andy Hung99b1ba62023-07-14 11:00:08 -0700468 // TODO(b/291317898) - remove hasAudioSession_l below.
Andy Hungab65b182023-09-06 19:41:47 -0700469 uint32_t hasAudioSession_l(audio_session_t sessionId) const override REQUIRES(mutex()) = 0;
470 uint32_t hasAudioSession(audio_session_t sessionId) const final EXCLUDES_ThreadBase_Mutex {
Andy Hung8d672e02023-09-15 18:19:28 -0700471 audio_utils::lock_guard _l(mutex());
Andy Hungab65b182023-09-06 19:41:47 -0700472 return hasAudioSession_l(sessionId);
473 }
Eric Laurent4c415062016-06-17 16:14:16 -0700474
Andy Hungc3d62f92019-03-14 13:38:51 -0700475 template <typename T>
Andy Hung8d672e02023-09-15 18:19:28 -0700476 uint32_t hasAudioSession_l(audio_session_t sessionId, const T& tracks) const
477 REQUIRES(mutex()) {
Andy Hungc3d62f92019-03-14 13:38:51 -0700478 uint32_t result = 0;
479 if (getEffectChain_l(sessionId) != 0) {
480 result = EFFECT_SESSION;
481 }
482 for (size_t i = 0; i < tracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -0700483 const sp<IAfTrackBase>& track = tracks[i];
Andy Hungc3d62f92019-03-14 13:38:51 -0700484 if (sessionId == track->sessionId()
485 && !track->isInvalid() // not yet removed from tracks.
486 && !track->isTerminated()) {
487 result |= TRACK_SESSION;
488 if (track->isFastTrack()) {
489 result |= FAST_SESSION; // caution, only represents first track.
490 }
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200491 if (track->isSpatialized()) {
Eric Laurentb62d0362021-10-26 17:40:18 +0200492 result |= SPATIALIZED_SESSION; // caution, only first track.
493 }
jiabinc658e452022-10-21 20:52:21 +0000494 if (track->isBitPerfect()) {
495 result |= BIT_PERFECT_SESSION;
496 }
Andy Hungc3d62f92019-03-14 13:38:51 -0700497 break;
498 }
499 }
500 return result;
501 }
502
Eric Laurent81784c32012-11-19 14:55:58 -0800503 // the value returned by default implementation is not important as the
504 // strategy is only meaningful for PlaybackThread which implements this method
Andy Hung440901d2023-06-29 21:19:25 -0700505 product_strategy_t getStrategyForSession_l(
Andy Hungab65b182023-09-06 19:41:47 -0700506 audio_session_t /* sessionId */) const override REQUIRES(mutex()){
507 return static_cast<product_strategy_t>(0);
508 }
Eric Laurent81784c32012-11-19 14:55:58 -0800509
Eric Laurent81784c32012-11-19 14:55:58 -0800510 // check if some effects must be suspended/restored when an effect is enabled
511 // or disabled
Andy Hung440901d2023-06-29 21:19:25 -0700512 void checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -0800513 audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -0700514 bool threadLocked) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800515
Eric Laurent81784c32012-11-19 14:55:58 -0800516
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700517 // Return a reference to a per-thread heap which can be used to allocate IMemory
518 // objects that will be read-only to client processes, read/write to mediaserver,
519 // and shared by all client processes of the thread.
520 // The heap is per-thread rather than common across all threads, because
521 // clients can't be trusted not to modify the offset of the IMemory they receive.
522 // If a thread does not have such a heap, this method returns 0.
Andy Hung440901d2023-06-29 21:19:25 -0700523 sp<MemoryDealer> readOnlyHeap() const override { return nullptr; }
Eric Laurent81784c32012-11-19 14:55:58 -0800524
Andy Hung440901d2023-06-29 21:19:25 -0700525 sp<IMemory> pipeMemory() const override { return nullptr; }
Glenn Kasten6181ffd2014-05-13 10:41:52 -0700526
Andy Hungab65b182023-09-06 19:41:47 -0700527 void systemReady() final EXCLUDES_ThreadBase_Mutex;
Eric Laurent72e3f392015-05-20 14:43:50 -0700528
Andy Hungab65b182023-09-06 19:41:47 -0700529 void broadcast_l() final REQUIRES(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -0700530
Andy Hungab65b182023-09-06 19:41:47 -0700531 bool isTimestampCorrectionEnabled_l() const override REQUIRES(mutex()) { return false; }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800532
Andy Hung440901d2023-06-29 21:19:25 -0700533 bool isMsdDevice() const final { return mIsMsdDevice; }
Andy Hungc8fddf32018-08-08 18:32:37 -0700534
Andy Hung440901d2023-06-29 21:19:25 -0700535 void dump(int fd, const Vector<String16>& args) override;
Andy Hungdc099c22018-09-18 13:46:39 -0700536
Andy Hungd0979812019-02-21 15:51:44 -0800537 // deliver stats to mediametrics.
Andy Hung8d672e02023-09-15 18:19:28 -0700538 void sendStatistics(bool force) final
539 REQUIRES(ThreadBase_ThreadLoop) EXCLUDES_ThreadBase_Mutex;
Andy Hungd0979812019-02-21 15:51:44 -0800540
Andy Hung972bec12023-08-31 16:13:39 -0700541 audio_utils::mutex& mutex() const final RETURN_CAPABILITY(audio_utils::ThreadBase_Mutex) {
Andy Hungc5007f82023-08-29 14:26:09 -0700542 return mMutex;
Andy Hung440901d2023-06-29 21:19:25 -0700543 }
Andy Hunga6f1cbb2023-10-12 18:18:13 -0700544 mutable audio_utils::mutex mMutex{audio_utils::MutexOrder::kThreadBase_Mutex};
Eric Laurent81784c32012-11-19 14:55:58 -0800545
Andy Hungab65b182023-09-06 19:41:47 -0700546 void onEffectEnable(const sp<IAfEffectModule>& effect) final EXCLUDES_ThreadBase_Mutex;
547 void onEffectDisable() final EXCLUDES_ThreadBase_Mutex;
Eric Laurent6b446ce2019-12-13 10:56:31 -0800548
Andy Hungc5007f82023-08-29 14:26:09 -0700549 // invalidateTracksForAudioSession_l must be called with holding mutex().
Andy Hungab65b182023-09-06 19:41:47 -0700550 void invalidateTracksForAudioSession_l(audio_session_t /* sessionId */) const override
551 REQUIRES(mutex()) {}
jiabineb3bda02020-06-30 14:07:03 -0700552 // Invalidate all the tracks with the given audio session.
Andy Hungab65b182023-09-06 19:41:47 -0700553 void invalidateTracksForAudioSession(audio_session_t sessionId) const final
554 EXCLUDES_ThreadBase_Mutex {
Andy Hung8d672e02023-09-15 18:19:28 -0700555 audio_utils::lock_guard _l(mutex());
jiabineb3bda02020-06-30 14:07:03 -0700556 invalidateTracksForAudioSession_l(sessionId);
557 }
558
559 template <typename T>
Andy Hungab65b182023-09-06 19:41:47 -0700560 void invalidateTracksForAudioSession_l(audio_session_t sessionId,
561 const T& tracks) const REQUIRES(mutex()) {
jiabineb3bda02020-06-30 14:07:03 -0700562 for (size_t i = 0; i < tracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -0700563 const sp<IAfTrackBase>& track = tracks[i];
jiabineb3bda02020-06-30 14:07:03 -0700564 if (sessionId == track->sessionId()) {
565 track->invalidate();
566 }
567 }
568 }
569
Andy Hung972bec12023-08-31 16:13:39 -0700570 void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) override
571 REQUIRES(audio_utils::AudioFlinger_Mutex);
572 void stopMelComputation_l() override
573 REQUIRES(audio_utils::AudioFlinger_Mutex);
Vlad Popa6fbbfbf2023-02-22 15:05:43 +0100574
Andy Hung56ce2ed2024-06-12 16:03:16 -0700575 audio_utils::DeferredExecutor& getThreadloopExecutor() override {
576 return mThreadloopExecutor;
577 }
578
Atneya Nairaa3afcb2024-10-08 16:36:19 -0700579 // Used to print the header for the local log on a particular thread type
580 virtual std::string getLocalLogHeader() const { return {}; };
581
Eric Laurent81784c32012-11-19 14:55:58 -0800582protected:
583
584 // entry describing an effect being suspended in mSuspendedSessions keyed vector
585 class SuspendedSessionDesc : public RefBase {
586 public:
587 SuspendedSessionDesc() : mRefCount(0) {}
588
589 int mRefCount; // number of active suspend requests
590 effect_uuid_t mType; // effect type UUID
591 };
592
Andy Hungab65b182023-09-06 19:41:47 -0700593 void acquireWakeLock() EXCLUDES_ThreadBase_Mutex;
594 virtual void acquireWakeLock_l() REQUIRES(mutex());
595 void releaseWakeLock() EXCLUDES_ThreadBase_Mutex;
596 void releaseWakeLock_l() REQUIRES(mutex());
597 void updateWakeLockUids_l(const SortedVector<uid_t> &uids) REQUIRES(mutex());
598 void getPowerManager_l() REQUIRES(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -0700599 // suspend or restore effects of the specified type (or all if type is NULL)
600 // on a given session. The number of suspend requests is counted and restore
601 // occurs when all suspend requests are cancelled.
Andy Hungab65b182023-09-06 19:41:47 -0700602 void setEffectSuspended_l(const effect_uuid_t *type,
Eric Laurent81784c32012-11-19 14:55:58 -0800603 bool suspend,
Andy Hungab65b182023-09-06 19:41:47 -0700604 audio_session_t sessionId) final REQUIRES(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -0700605 // updated mSuspendedSessions when an effect is suspended or restored
Andy Hungab65b182023-09-06 19:41:47 -0700606 void updateSuspendedSessions_l(const effect_uuid_t *type,
Eric Laurent81784c32012-11-19 14:55:58 -0800607 bool suspend,
Andy Hungab65b182023-09-06 19:41:47 -0700608 audio_session_t sessionId) REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800609 // check if some effects must be suspended when an effect chain is added
Andy Hungab65b182023-09-06 19:41:47 -0700610 void checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain) REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800611
Andy Hung6c498e92023-12-05 17:28:17 -0800612 /**
613 * waitWhileThreadBusy_l() serves as a mutex gate, which does not allow
614 * progress beyond the method while the PlaybackThread is busy (see setThreadBusy_l()).
615 * During the wait, the ThreadBase_Mutex is temporarily unlocked.
616 *
617 * This implementation uses a condition variable. Alternative methods to gate
618 * the thread may use a second mutex (i.e. entry based on scoped_lock(mutex, gating_mutex)),
619 * but those have less flexibility and more lock order issues.
620 *
621 * Current usage by Track::destroy(), Track::start(), Track::stop(), Track::pause(),
622 * and Track::flush() block this way, and the primary caller is through TrackHandle
623 * with no other mutexes held.
624 *
625 * Special tracks like PatchTrack and OutputTrack may also hold the another thread's
626 * ThreadBase_Mutex during this time. No other mutex is held.
627 */
628
Andy Hungf462c6c2024-09-23 18:42:26 -0700629 void waitWhileThreadBusy_l(audio_utils::unique_lock<audio_utils::mutex>& ul)
630 final REQUIRES(mutex()) {
Andy Hung6c498e92023-12-05 17:28:17 -0800631 // the wait returns immediately if the predicate is satisfied.
632 mThreadBusyCv.wait(ul, [&]{ return mThreadBusy == false;});
633 }
634
635 void setThreadBusy_l(bool busy) REQUIRES(mutex()) {
636 if (busy == mThreadBusy) return;
637 mThreadBusy = busy;
638 if (busy == true) return; // no need to wake threads if we become busy.
639 mThreadBusyCv.notify_all();
640 }
641
Kevin Rocard069c2712018-03-29 19:09:14 -0700642 // sends the metadata of the active tracks to the HAL
Vlad Popa7e81cea2023-01-19 16:34:16 +0100643 struct MetadataUpdate {
644 std::vector<playback_track_metadata_v7_t> playbackMetadataUpdate;
645 std::vector<record_track_metadata_v7_t> recordMetadataUpdate;
646 };
Andy Hung8d672e02023-09-15 18:19:28 -0700647 // NO_THREAD_SAFETY_ANALYSIS, updateMetadata_l() should include ThreadBase_ThreadLoop
648 // but MmapThread::start() -> exitStandby_l() -> updateMetadata_l() prevents this.
Andy Hungab65b182023-09-06 19:41:47 -0700649 virtual MetadataUpdate updateMetadata_l() REQUIRES(mutex()) = 0;
Kevin Rocard069c2712018-03-29 19:09:14 -0700650
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100651 String16 getWakeLockTag();
652
Andy Hungab65b182023-09-06 19:41:47 -0700653 virtual void preExit() EXCLUDES_ThreadBase_Mutex {}
654 virtual void setMasterMono_l(bool mono __unused) REQUIRES(mutex()) {}
Andy Hung2ddee192015-12-18 17:34:44 -0800655 virtual bool requireMonoBlend() { return false; }
Eric Laurent81784c32012-11-19 14:55:58 -0800656
Andy Hung1c86ebe2018-05-29 20:29:08 -0700657 // called within the threadLoop to obtain timestamp from the HAL.
Andy Hungab65b182023-09-06 19:41:47 -0700658 virtual status_t threadloop_getHalTimestamp_l(
Andy Hung8d672e02023-09-15 18:19:28 -0700659 ExtendedTimestamp *timestamp __unused) const
660 REQUIRES(mutex(), ThreadBase_ThreadLoop) {
Andy Hung1c86ebe2018-05-29 20:29:08 -0700661 return INVALID_OPERATION;
662 }
Andy Hung116bc262023-06-20 18:56:17 -0700663public:
Andy Hung99b1ba62023-07-14 11:00:08 -0700664// TODO(b/291317898) organize with publics
Eric Laurentd66d7a12021-07-13 13:35:32 +0200665 product_strategy_t getStrategyForStream(audio_stream_type_t stream) const;
Andy Hung116bc262023-06-20 18:56:17 -0700666protected:
Eric Laurentd66d7a12021-07-13 13:35:32 +0200667
Andy Hungab65b182023-09-06 19:41:47 -0700668 virtual void onHalLatencyModesChanged_l() REQUIRES(mutex()) {}
Eric Laurentb0463942022-12-20 16:31:10 +0100669
Andy Hungab65b182023-09-06 19:41:47 -0700670 virtual void dumpInternals_l(int fd __unused, const Vector<String16>& args __unused)
671 REQUIRES(mutex()) {}
672 virtual void dumpTracks_l(int fd __unused, const Vector<String16>& args __unused)
673 REQUIRES(mutex()) {}
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700674
Eric Laurent81784c32012-11-19 14:55:58 -0800675 const type_t mType;
676
677 // Used by parameters, config events, addTrack_l, exit
Andy Hungc5007f82023-08-29 14:26:09 -0700678 audio_utils::condition_variable mWaitWorkCV;
Eric Laurent81784c32012-11-19 14:55:58 -0800679
Andy Hung583043b2023-07-17 17:05:00 -0700680 const sp<IAfThreadCallback> mAfThreadCallback;
Andy Hungcf10d742020-04-28 15:38:24 -0700681 ThreadMetrics mThreadMetrics;
682 const bool mIsOut;
Glenn Kasten9b58f632013-07-16 11:37:48 -0700683
Andy Hung6c498e92023-12-05 17:28:17 -0800684 // mThreadBusy is checked under the ThreadBase_Mutex to ensure that
685 // TrackHandle operations do not proceed while the ThreadBase is busy
686 // with the track. mThreadBusy is only true if the track is active.
687 //
688 bool mThreadBusy = false; // GUARDED_BY(ThreadBase_Mutex) but read in lambda.
689 audio_utils::condition_variable mThreadBusyCv;
690
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800691 // updated by PlaybackThread::readOutputParameters_l() or
692 // RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800693 uint32_t mSampleRate;
694 size_t mFrameCount; // output HAL, direct output, record
Eric Laurent81784c32012-11-19 14:55:58 -0800695 audio_channel_mask_t mChannelMask;
Glenn Kastenf6ed4232013-07-16 11:16:27 -0700696 uint32_t mChannelCount;
Eric Laurent81784c32012-11-19 14:55:58 -0800697 size_t mFrameSize;
Glenn Kasten97b7b752014-09-28 13:04:24 -0700698 // not HAL frame size, this is for output sink (to pipe to fast mixer)
Andy Hung463be252014-07-10 16:56:07 -0700699 audio_format_t mFormat; // Source format for Recording and
700 // Sink format for Playback.
701 // Sink format may be different than
702 // HAL format if Fastmixer is used.
703 audio_format_t mHALFormat;
Glenn Kasten70949c42013-08-06 07:40:12 -0700704 size_t mBufferSize; // HAL buffer size for read() or write()
Andy Hungab65b182023-09-06 19:41:47 -0700705
706 // output device types and addresses
707 AudioDeviceTypeAddrVector mOutDeviceTypeAddrs GUARDED_BY(mutex());
708 AudioDeviceTypeAddr mInDeviceTypeAddr GUARDED_BY(mutex()); // input device type and address
Andy Hung8d672e02023-09-15 18:19:28 -0700709 Vector<sp<ConfigEvent>> mConfigEvents GUARDED_BY(mutex());
710
711 // events awaiting system ready
712 Vector<sp<ConfigEvent>> mPendingConfigEvents GUARDED_BY(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800713
714 // These fields are written and read by thread itself without lock or barrier,
jiabinc52b1ff2019-10-31 17:20:42 -0700715 // and read by other threads without lock or barrier via standby(), outDeviceTypes()
716 // and inDeviceType().
Eric Laurent81784c32012-11-19 14:55:58 -0800717 // Because of the absence of a lock or barrier, any other thread that reads
718 // these fields must use the information in isolation, or be prepared to deal
719 // with possibility that it might be inconsistent with other information.
Glenn Kasten4944acb2013-08-19 08:39:20 -0700720 bool mStandby; // Whether thread is currently in standby.
jiabinc52b1ff2019-10-31 17:20:42 -0700721
Andy Hung8d672e02023-09-15 18:19:28 -0700722 // NO_THREAD_SAFETY_ANALYSIS - mPatch and mAudioSource should be guarded by mutex().
Eric Laurent296fb132015-05-01 11:38:42 -0700723 struct audio_patch mPatch;
Glenn Kastenf59497b2015-01-26 16:35:47 -0800724 audio_source_t mAudioSource;
Eric Laurent81784c32012-11-19 14:55:58 -0800725
726 const audio_io_handle_t mId;
Andy Hung8d672e02023-09-15 18:19:28 -0700727 Vector<sp<IAfEffectChain>> mEffectChains GUARDED_BY(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800728
Glenn Kastend7dca052015-03-05 16:05:54 -0800729 static const int kThreadNameLength = 16; // prctl(PR_SET_NAME) limit
730 char mThreadName[kThreadNameLength]; // guaranteed NUL-terminated
Andy Hung8d672e02023-09-15 18:19:28 -0700731 sp<os::IPowerManager> mPowerManager GUARDED_BY(mutex());
732 sp<IBinder> mWakeLockToken GUARDED_BY(mutex());
Andy Hung88a7afe2024-08-12 20:00:46 -0700733 std::unique_ptr<media::psh_utils::Token> mThreadToken GUARDED_BY(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800734 const sp<PMDeathRecipient> mDeathRecipient;
Glenn Kastend848eb42016-03-08 13:42:11 -0800735 // list of suspended effects per session and per type. The first (outer) vector is
736 // keyed by session ID, the second (inner) by type UUID timeLow field
Eric Laurentd8365c52017-07-16 15:27:05 -0700737 // Updated by updateSuspendedSessions_l() only.
Glenn Kastend848eb42016-03-08 13:42:11 -0800738 KeyedVector< audio_session_t, KeyedVector< int, sp<SuspendedSessionDesc> > >
Eric Laurent81784c32012-11-19 14:55:58 -0800739 mSuspendedSessions;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -0700740 // TODO: add comment and adjust size as needed
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800741 static const size_t kLogSize = 4 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -0800742 sp<NBLog::Writer> mNBLogWriter;
Eric Laurent72e3f392015-05-20 14:43:50 -0700743 bool mSystemReady;
Andy Hung8d672e02023-09-15 18:19:28 -0700744
745 // NO_THREAD_SAFETY_ANALYSIS - mTimestamp and mTimestampVerifier should be
746 // accessed under mutex for the RecordThread.
747 ExtendedTimestamp mTimestamp;
748 TimestampVerifier<int64_t /* frame count */, int64_t /* time ns */> mTimestampVerifier;
Dean Wheatley12473e92021-03-18 23:00:55 +1100749 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush
750 // TODO: add confirmation checks:
751 // 1) DIRECT threads and linear PCM format really resets to 0?
752 // 2) Is frame count really valid if not linear pcm?
753 // 3) Are all 64 bits of position returned, not just lowest 32 bits?
jiabinc52b1ff2019-10-31 17:20:42 -0700754 // Timestamp corrected device should be a single device.
Andy Hung8d672e02023-09-15 18:19:28 -0700755
756 audio_devices_t mTimestampCorrectedDevice = AUDIO_DEVICE_NONE; // CONST set in ctor
Andy Hung446f4df2019-02-21 12:26:41 -0800757
758 // ThreadLoop statistics per iteration.
Andy Hung8d672e02023-09-15 18:19:28 -0700759 std::atomic<int64_t> mLastIoBeginNs = -1; // set in threadLoop, read by dump()
760 int64_t mLastIoEndNs GUARDED_BY(ThreadBase_ThreadLoop) = -1;
Andy Hung446f4df2019-02-21 12:26:41 -0800761
Andy Hung44d648b2022-04-08 17:33:40 -0700762 // ThreadSnapshot is thread-safe (internally locked)
763 mediautils::ThreadSnapshot mThreadSnapshot;
764
Andy Hung8d672e02023-09-15 18:19:28 -0700765 audio_utils::Statistics<double> mIoJitterMs GUARDED_BY(mutex()) {0.995 /* alpha */};
766 audio_utils::Statistics<double> mProcessTimeMs GUARDED_BY(mutex()) {0.995 /* alpha */};
767
768 // NO_THREAD_SAFETY_ANALYSIS GUARDED_BY(mutex())
Andy Hunge6c37112019-02-26 17:38:10 -0800769 audio_utils::Statistics<double> mLatencyMs{0.995 /* alpha */};
Robert Wu06db0a32021-08-10 19:05:34 +0000770 audio_utils::Statistics<double> mMonopipePipeDepthStats{0.999 /* alpha */};
Andy Hung446f4df2019-02-21 12:26:41 -0800771
Andy Hungd0979812019-02-21 15:51:44 -0800772 // Save the last count when we delivered statistics to mediametrics.
773 int64_t mLastRecordedTimestampVerifierN = 0;
774 int64_t mLastRecordedTimeNs = 0; // BOOTTIME to include suspend.
775
Andy Hungc8fddf32018-08-08 18:32:37 -0700776 bool mIsMsdDevice = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800777 // A condition that must be evaluated by the thread loop has changed and
778 // we must not wait for async write callback in the thread loop before evaluating it
779 bool mSignalPending;
Andy Hungdae27702016-10-31 14:01:16 -0700780
Andy Hung8946a282018-04-19 20:04:56 -0700781#ifdef TEE_SINK
782 NBAIO_Tee mTee;
783#endif
Andy Hungdae27702016-10-31 14:01:16 -0700784 // ActiveTracks is a sorted vector of track type T representing the
785 // active tracks of threadLoop() to be considered by the locked prepare portion.
786 // ActiveTracks should be accessed with the ThreadBase lock held.
787 //
788 // During processing and I/O, the threadLoop does not hold the lock;
789 // hence it does not directly use ActiveTracks. Care should be taken
790 // to hold local strong references or defer removal of tracks
791 // if the threadLoop may still be accessing those tracks due to mix, etc.
792 //
793 // This class updates power information appropriately.
794 //
795
796 template <typename T>
797 class ActiveTracks {
798 public:
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700799 explicit ActiveTracks(SimpleLog *localLog = nullptr)
Andy Hungdae27702016-10-31 14:01:16 -0700800 : mActiveTracksGeneration(0)
801 , mLastActiveTracksGeneration(0)
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700802 , mLocalLog(localLog)
Andy Hungdae27702016-10-31 14:01:16 -0700803 { }
804
805 ~ActiveTracks() {
806 ALOGW_IF(!mActiveTracks.isEmpty(),
807 "ActiveTracks should be empty in destructor");
808 }
809 // returns the last track added (even though it may have been
810 // subsequently removed from ActiveTracks).
811 //
812 // Used for DirectOutputThread to ensure a flush is called when transitioning
813 // to a new track (even though it may be on the same session).
814 // Used for OffloadThread to ensure that volume and mixer state is
815 // taken from the latest track added.
816 //
817 // The latest track is saved with a weak pointer to prevent keeping an
818 // otherwise useless track alive. Thus the function will return nullptr
819 // if the latest track has subsequently been removed and destroyed.
820 sp<T> getLatest() {
821 return mLatestActiveTrack.promote();
822 }
823
824 // SortedVector methods
825 ssize_t add(const sp<T> &track);
826 ssize_t remove(const sp<T> &track);
827 size_t size() const {
828 return mActiveTracks.size();
829 }
Eric Tan39ec8d62018-07-24 09:49:29 -0700830 bool isEmpty() const {
831 return mActiveTracks.isEmpty();
832 }
Andy Hung87c693c2023-07-06 20:56:16 -0700833 ssize_t indexOf(const sp<T>& item) const {
Andy Hungdae27702016-10-31 14:01:16 -0700834 return mActiveTracks.indexOf(item);
835 }
836 sp<T> operator[](size_t index) const {
837 return mActiveTracks[index];
838 }
839 typename SortedVector<sp<T>>::iterator begin() {
840 return mActiveTracks.begin();
841 }
842 typename SortedVector<sp<T>>::iterator end() {
843 return mActiveTracks.end();
844 }
Andy Hung6b137d12024-08-27 22:35:17 +0000845 typename SortedVector<const sp<T>>::iterator begin() const {
846 return mActiveTracks.begin();
847 }
848 typename SortedVector<const sp<T>>::iterator end() const {
849 return mActiveTracks.end();
850 }
Andy Hungdae27702016-10-31 14:01:16 -0700851
852 // Due to Binder recursion optimization, clear() and updatePowerState()
853 // cannot be called from a Binder thread because they may call back into
854 // the original calling process (system server) for BatteryNotifier
855 // (which requires a Java environment that may not be present).
856 // Hence, call clear() and updatePowerState() only from the
857 // ThreadBase thread.
858 void clear();
859 // periodically called in the threadLoop() to update power state uids.
Andy Hungab65b182023-09-06 19:41:47 -0700860 void updatePowerState_l(const sp<ThreadBase>& thread, bool force = false)
861 REQUIRES(audio_utils::ThreadBase_Mutex);
Andy Hungdae27702016-10-31 14:01:16 -0700862
Kevin Rocardc86a7f72018-04-03 09:00:09 -0700863 /** @return true if one or move active tracks was added or removed since the
Jasmine Chaeaa10e42021-05-11 10:11:14 +0800864 * last time this function was called or the vector was created.
865 * true if volume of one of active tracks was changed.
866 */
Kevin Rocard069c2712018-03-29 19:09:14 -0700867 bool readAndClearHasChanged();
868
Eric Laurentdda206a2022-07-08 17:28:35 +0200869 /** Force updating track metadata to audio HAL stream next time
870 * readAndClearHasChanged() is called.
871 */
872 void setHasChanged() { mHasChanged = true; }
873
Andy Hungdae27702016-10-31 14:01:16 -0700874 private:
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700875 void logTrack(const char *funcName, const sp<T> &track) const;
876
Andy Hungd01b0f12016-11-07 16:10:30 -0800877 SortedVector<uid_t> getWakeLockUids() {
878 SortedVector<uid_t> wakeLockUids;
Andy Hungdae27702016-10-31 14:01:16 -0700879 for (const sp<T> &track : mActiveTracks) {
880 wakeLockUids.add(track->uid());
881 }
882 return wakeLockUids; // moved by underlying SharedBuffer
883 }
884
Andy Hungdae27702016-10-31 14:01:16 -0700885 SortedVector<sp<T>> mActiveTracks;
886 int mActiveTracksGeneration;
887 int mLastActiveTracksGeneration;
888 wp<T> mLatestActiveTrack; // latest track added to ActiveTracks
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700889 SimpleLog * const mLocalLog;
Kevin Rocardc86a7f72018-04-03 09:00:09 -0700890 // If the vector has changed since last call to readAndClearHasChanged
Kevin Rocard069c2712018-03-29 19:09:14 -0700891 bool mHasChanged = false;
Andy Hungdae27702016-10-31 14:01:16 -0700892 };
Andy Hung293558a2017-03-21 12:19:20 -0700893
Atneya Nair0423af92024-10-07 21:23:29 -0700894 SimpleLog mLocalLog {/* maxLogLines= */ 120}; // locked internally
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700895
Andy Hung56ce2ed2024-06-12 16:03:16 -0700896 // mThreadloopExecutor contains deferred functors and object (dtors) to
897 // be executed at the end of the processing period, without any
898 // mutexes held.
899 //
900 // mThreadloopExecutor is locked internally, so its methods are thread-safe
901 // for access.
902 audio_utils::DeferredExecutor mThreadloopExecutor;
903
Andy Hung6c498e92023-12-05 17:28:17 -0800904 private:
Andy Hungab65b182023-09-06 19:41:47 -0700905 void dumpBase_l(int fd, const Vector<String16>& args) REQUIRES(mutex());
906 void dumpEffectChains_l(int fd, const Vector<String16>& args) REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800907};
908
909// --- PlaybackThread ---
Andy Hung440901d2023-06-29 21:19:25 -0700910class PlaybackThread : public ThreadBase, public virtual IAfPlaybackThread,
911 public StreamOutHalInterfaceCallback,
Andy Hung87c693c2023-07-06 20:56:16 -0700912 public virtual VolumeInterface, public StreamOutHalInterfaceEventCallback {
Eric Laurent81784c32012-11-19 14:55:58 -0800913public:
Andy Hung87c693c2023-07-06 20:56:16 -0700914 sp<IAfPlaybackThread> asIAfPlaybackThread() final {
915 return sp<IAfPlaybackThread>::fromExisting(this);
916 }
Eric Laurent81784c32012-11-19 14:55:58 -0800917
Eric Laurente93cc032016-05-05 10:15:10 -0700918 // retry count before removing active track in case of underrun on offloaded thread:
919 // we need to make sure that AudioTrack client has enough time to send large buffers
920 //FIXME may be more appropriate if expressed in time units. Need to revise how underrun is
921 // handled for offloaded tracks
922 static const int8_t kMaxTrackRetriesOffload = 20;
923 static const int8_t kMaxTrackStartupRetriesOffload = 100;
Andy Hung8ed196a2018-01-05 13:21:11 -0800924 static constexpr uint32_t kMaxTracksPerUid = 40;
Andy Hung1bc088a2018-02-09 15:57:31 -0800925 static constexpr size_t kMaxTracks = 256;
Eric Laurente93cc032016-05-05 10:15:10 -0700926
rago1bb90822017-05-02 18:31:48 -0700927 // Maximum delay (in nanoseconds) for upcoming buffers in suspend mode, otherwise
928 // if delay is greater, the estimated time for timeLoopNextNs is reset.
929 // This allows for catch-up to be done for small delays, while resetting the estimate
930 // for initial conditions or large delays.
931 static const nsecs_t kMaxNextBufferDelayNs = 100000000;
932
Andy Hung583043b2023-07-17 17:05:00 -0700933 PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +0200934 audio_io_handle_t id, type_t type, bool systemReady,
935 audio_config_base_t *mixerConfig = nullptr);
Andy Hung440901d2023-06-29 21:19:25 -0700936 ~PlaybackThread() override;
Eric Laurent81784c32012-11-19 14:55:58 -0800937
Eric Laurent81784c32012-11-19 14:55:58 -0800938 // Thread virtuals
Andy Hung8d672e02023-09-15 18:19:28 -0700939 bool threadLoop() final REQUIRES(ThreadBase_ThreadLoop) EXCLUDES_ThreadBase_Mutex;
Eric Laurent81784c32012-11-19 14:55:58 -0800940
941 // RefBase
Andy Hung440901d2023-06-29 21:19:25 -0700942 void onFirstRef() override;
Eric Laurent81784c32012-11-19 14:55:58 -0800943
Andy Hung440901d2023-06-29 21:19:25 -0700944 status_t checkEffectCompatibility_l(
Andy Hungab65b182023-09-06 19:41:47 -0700945 const effect_descriptor_t* desc, audio_session_t sessionId) final REQUIRES(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -0700946
Andy Hungab65b182023-09-06 19:41:47 -0700947 void addOutputTrack_l(const sp<IAfTrack>& track) final REQUIRES(mutex()) {
Andy Hung87c693c2023-07-06 20:56:16 -0700948 mTracks.add(track);
949 }
950
Eric Laurent81784c32012-11-19 14:55:58 -0800951protected:
952 // Code snippets that were lifted up out of threadLoop()
Andy Hung8d672e02023-09-15 18:19:28 -0700953 virtual void threadLoop_mix() REQUIRES(ThreadBase_ThreadLoop) = 0;
954 virtual void threadLoop_sleepTime() REQUIRES(ThreadBase_ThreadLoop) = 0;
955 virtual ssize_t threadLoop_write() REQUIRES(ThreadBase_ThreadLoop);
956 virtual void threadLoop_drain() REQUIRES(ThreadBase_ThreadLoop);
957 virtual void threadLoop_standby() REQUIRES(ThreadBase_ThreadLoop);
958 virtual void threadLoop_exit() REQUIRES(ThreadBase_ThreadLoop);
959 virtual void threadLoop_removeTracks(const Vector<sp<IAfTrack>>& tracksToRemove)
960 REQUIRES(ThreadBase_ThreadLoop);
Eric Laurent81784c32012-11-19 14:55:58 -0800961
962 // prepareTracks_l reads and writes mActiveTracks, and returns
963 // the pending set of tracks to remove via Vector 'tracksToRemove'. The caller
964 // is responsible for clearing or destroying this Vector later on, when it
965 // is safe to do so. That will drop the final ref count and destroy the tracks.
Andy Hung8d672e02023-09-15 18:19:28 -0700966 virtual mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove)
967 REQUIRES(mutex(), ThreadBase_ThreadLoop) = 0;
968
969 void removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove) REQUIRES(mutex());
970 status_t handleVoipVolume_l(float *volume) REQUIRES(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -0800971
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700972 // StreamOutHalInterfaceCallback implementation
973 virtual void onWriteReady();
974 virtual void onDrainReady();
Mikhail Naganovbf203ce2024-05-23 16:27:59 -0700975 virtual void onError(bool /*isHardError*/);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800976
Andy Hungee58e4a2023-07-07 13:47:37 -0700977public: // AsyncCallbackThread
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700978 void resetWriteBlocked(uint32_t sequence);
979 void resetDraining(uint32_t sequence);
Andy Hungee58e4a2023-07-07 13:47:37 -0700980protected:
Eric Laurentbfb1b832013-01-07 09:53:42 -0800981
982 virtual bool waitingAsyncCallback();
Andy Hungab65b182023-09-06 19:41:47 -0700983 virtual bool waitingAsyncCallback_l() REQUIRES(mutex());
Andy Hung8d672e02023-09-15 18:19:28 -0700984 virtual bool shouldStandby_l() REQUIRES(mutex(), ThreadBase_ThreadLoop);
Andy Hungab65b182023-09-06 19:41:47 -0700985 virtual void onAddNewTrack_l() REQUIRES(mutex());
Andy Hungee58e4a2023-07-07 13:47:37 -0700986public: // AsyncCallbackThread
Mikhail Naganovbf203ce2024-05-23 16:27:59 -0700987 void onAsyncError(bool isHardError); // error reported by AsyncCallbackThread
Andy Hungee58e4a2023-07-07 13:47:37 -0700988protected:
jiabinf6eb4c32020-02-25 14:06:25 -0800989 // StreamHalInterfaceCodecFormatCallback implementation
990 void onCodecFormatChanged(
Ryan Prichard78c5e452024-02-08 16:16:57 -0800991 const std::vector<uint8_t>& metadataBs) final;
jiabinf6eb4c32020-02-25 14:06:25 -0800992
Eric Laurent81784c32012-11-19 14:55:58 -0800993 // ThreadBase virtuals
Andy Hungab65b182023-09-06 19:41:47 -0700994 void preExit() final EXCLUDES_ThreadBase_Mutex;
Eric Laurent81784c32012-11-19 14:55:58 -0800995
Eric Laurent64667972016-03-30 18:19:46 -0700996 virtual bool keepWakeLock() const { return true; }
Andy Hungab65b182023-09-06 19:41:47 -0700997 virtual void acquireWakeLock_l() REQUIRES(mutex()) {
Andy Hungdae27702016-10-31 14:01:16 -0700998 ThreadBase::acquireWakeLock_l();
Andy Hungab65b182023-09-06 19:41:47 -0700999 mActiveTracks.updatePowerState_l(this, true /* force */);
Andy Hungdae27702016-10-31 14:01:16 -07001000 }
Eric Laurent64667972016-03-30 18:19:46 -07001001
Andy Hung8d672e02023-09-15 18:19:28 -07001002 virtual void checkOutputStageEffects()
1003 REQUIRES(ThreadBase_ThreadLoop) EXCLUDES_ThreadBase_Mutex {}
Eric Laurent68a40a82022-05-03 18:15:04 +02001004 virtual void setHalLatencyMode_l() {}
1005
Eric Laurentb3f315a2021-07-13 15:09:05 +02001006
Andy Hungab65b182023-09-06 19:41:47 -07001007 void dumpInternals_l(int fd, const Vector<String16>& args) override REQUIRES(mutex());
1008 void dumpTracks_l(int fd, const Vector<String16>& args) final REQUIRES(mutex());
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001009
Eric Laurent81784c32012-11-19 14:55:58 -08001010public:
1011
Andy Hung440901d2023-06-29 21:19:25 -07001012 status_t initCheck() const final { return mOutput == nullptr ? NO_INIT : NO_ERROR; }
Eric Laurent81784c32012-11-19 14:55:58 -08001013
1014 // return estimated latency in milliseconds, as reported by HAL
Andy Hung440901d2023-06-29 21:19:25 -07001015 uint32_t latency() const final;
Eric Laurent81784c32012-11-19 14:55:58 -08001016 // same, but lock must already be held
Andy Hungab65b182023-09-06 19:41:47 -07001017 uint32_t latency_l() const final /* REQUIRES(mutex()) */; // NO_THREAD_SAFETY_ANALYSIS
Eric Laurent81784c32012-11-19 14:55:58 -08001018
Eric Laurent6acd1d42017-01-04 14:23:29 -08001019 // VolumeInterface
Andy Hung440901d2023-06-29 21:19:25 -07001020 void setMasterVolume(float value) final;
Andy Hungab65b182023-09-06 19:41:47 -07001021 void setMasterBalance(float balance) override EXCLUDES_ThreadBase_Mutex;
Andy Hung440901d2023-06-29 21:19:25 -07001022 void setMasterMute(bool muted) final;
Vlad Popa1e865e62024-08-15 19:11:42 -07001023 void setStreamVolume(audio_stream_type_t stream, float value, bool muted) final
1024 EXCLUDES_ThreadBase_Mutex;
Andy Hungab65b182023-09-06 19:41:47 -07001025 void setStreamMute(audio_stream_type_t stream, bool muted) final EXCLUDES_ThreadBase_Mutex;
1026 float streamVolume(audio_stream_type_t stream) const final EXCLUDES_ThreadBase_Mutex;
Vlad Popa1e865e62024-08-15 19:11:42 -07001027 status_t setPortsVolume(const std::vector<audio_port_handle_t>& portIds, float volume,
1028 bool muted) final EXCLUDES_ThreadBase_Mutex;
Andy Hung6b137d12024-08-27 22:35:17 +00001029
Andy Hung440901d2023-06-29 21:19:25 -07001030 void setVolumeForOutput_l(float left, float right) const final;
Eric Laurent81784c32012-11-19 14:55:58 -08001031
Andy Hung440901d2023-06-29 21:19:25 -07001032 sp<IAfTrack> createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001033 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001034 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001035 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08001036 uint32_t *sampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001037 audio_format_t format,
1038 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001039 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08001040 size_t *pNotificationFrameCount,
1041 uint32_t notificationsPerBuffer,
1042 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08001043 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001044 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001045 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07001046 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00001047 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08001048 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001049 status_t *status /*non-NULL*/,
jiabinf6eb4c32020-02-25 14:06:25 -08001050 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001051 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00001052 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +00001053 bool isBitPerfect,
Andy Hung6b137d12024-08-27 22:35:17 +00001054 audio_output_flags_t* afTrackFlags,
Vlad Popa1e865e62024-08-15 19:11:42 -07001055 float volume,
1056 bool muted) final
Andy Hung972bec12023-08-31 16:13:39 -07001057 REQUIRES(audio_utils::AudioFlinger_Mutex);
Eric Laurent81784c32012-11-19 14:55:58 -08001058
Andy Hung87c693c2023-07-06 20:56:16 -07001059 bool isTrackActive(const sp<IAfTrack>& track) const final {
1060 return mActiveTracks.indexOf(track) >= 0;
1061 }
1062
Andy Hungab65b182023-09-06 19:41:47 -07001063 AudioStreamOut* getOutput_l() const final REQUIRES(mutex()) { return mOutput; }
Andy Hung8d672e02023-09-15 18:19:28 -07001064 AudioStreamOut* getOutput() const final EXCLUDES_ThreadBase_Mutex;
1065 AudioStreamOut* clearOutput() final EXCLUDES_ThreadBase_Mutex;
1066
1067 // NO_THREAD_SAFETY_ANALYSIS -- probably needs a lock.
Andy Hung440901d2023-06-29 21:19:25 -07001068 sp<StreamHalInterface> stream() const final;
Eric Laurent81784c32012-11-19 14:55:58 -08001069
Andy Hung8d672e02023-09-15 18:19:28 -07001070 // suspend(), restore(), and isSuspended() are implemented atomically.
1071 void suspend() final { ++mSuspended; }
1072 void restore() final {
1073 // if restore() is done without suspend(), get back into
1074 // range so that the next suspend() will operate correctly
1075 while (true) {
1076 int32_t suspended = mSuspended;
1077 if (suspended <= 0) {
1078 ALOGW("%s: invalid mSuspended %d <= 0", __func__, suspended);
1079 return;
1080 }
1081 const int32_t desired = suspended - 1;
1082 if (mSuspended.compare_exchange_weak(suspended, desired)) return;
1083 }
1084 }
1085 bool isSuspended() const final { return mSuspended > 0; }
Eric Laurent81784c32012-11-19 14:55:58 -08001086
Andy Hungab65b182023-09-06 19:41:47 -07001087 String8 getParameters(const String8& keys) EXCLUDES_ThreadBase_Mutex;
1088
1089 // Hold either the AudioFlinger::mutex or the ThreadBase::mutex
1090 void ioConfigChanged_l(audio_io_config_event_t event, pid_t pid = 0,
Andy Hung440901d2023-06-29 21:19:25 -07001091 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final;
Andy Hungab65b182023-09-06 19:41:47 -07001092 status_t getRenderPosition(uint32_t* halFrames, uint32_t* dspFrames) const final
1093 EXCLUDES_ThreadBase_Mutex;
Andy Hung010a1a12014-03-13 13:57:33 -07001094 // Consider also removing and passing an explicit mMainBuffer initialization
Andy Hung8d31fd22023-06-26 19:20:57 -07001095 // parameter to AF::IAfTrack::Track().
Andy Hung440901d2023-06-29 21:19:25 -07001096 float* sinkBuffer() const final {
Andy Hung319587b2023-05-23 14:01:03 -07001097 return reinterpret_cast<float *>(mSinkBuffer); };
Eric Laurent81784c32012-11-19 14:55:58 -08001098
Andy Hungab65b182023-09-06 19:41:47 -07001099 void detachAuxEffect_l(int effectId) final REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001100
Andy Hungab65b182023-09-06 19:41:47 -07001101 status_t attachAuxEffect(const sp<IAfTrack>& track, int EffectId) final
1102 EXCLUDES_ThreadBase_Mutex;
1103 status_t attachAuxEffect_l(const sp<IAfTrack>& track, int EffectId) final REQUIRES(mutex());
Andy Hung440901d2023-06-29 21:19:25 -07001104
Andy Hungab65b182023-09-06 19:41:47 -07001105 status_t addEffectChain_l(const sp<IAfEffectChain>& chain) final REQUIRES(mutex());
1106 size_t removeEffectChain_l(const sp<IAfEffectChain>& chain) final REQUIRES(mutex());
1107 uint32_t hasAudioSession_l(audio_session_t sessionId) const final REQUIRES(mutex()) {
Andy Hungc3d62f92019-03-14 13:38:51 -07001108 return ThreadBase::hasAudioSession_l(sessionId, mTracks);
1109 }
Andy Hungab65b182023-09-06 19:41:47 -07001110 product_strategy_t getStrategyForSession_l(audio_session_t sessionId) const final
1111 REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001112
1113
Andy Hungab65b182023-09-06 19:41:47 -07001114 status_t setSyncEvent(const sp<audioflinger::SyncEvent>& event) final
1115 EXCLUDES_ThreadBase_Mutex;
1116 // could be static.
Andy Hung440901d2023-06-29 21:19:25 -07001117 bool isValidSyncEvent(const sp<audioflinger::SyncEvent>& event) const final;
Glenn Kastenfb1fdc92013-07-10 17:03:19 -07001118
Andy Hungab65b182023-09-06 19:41:47 -07001119 // Does this require the AudioFlinger mutex as well?
1120 bool invalidateTracks_l(audio_stream_type_t streamType) final
1121 REQUIRES(mutex());
1122 bool invalidateTracks_l(std::set<audio_port_handle_t>& portIds) final
1123 REQUIRES(mutex());
Andy Hung440901d2023-06-29 21:19:25 -07001124 void invalidateTracks(audio_stream_type_t streamType) override;
jiabinc44b3462022-12-08 12:52:31 -08001125 // Invalidate tracks by a set of port ids. The port id will be removed from
1126 // the given set if the corresponding track is found and invalidated.
Andy Hungab65b182023-09-06 19:41:47 -07001127 void invalidateTracks(std::set<audio_port_handle_t>& portIds) override
1128 EXCLUDES_ThreadBase_Mutex;
Eric Laurent81784c32012-11-19 14:55:58 -08001129
Andy Hung87c693c2023-07-06 20:56:16 -07001130 size_t frameCount() const final { return mNormalFrameCount; }
Glenn Kasten9b58f632013-07-16 11:37:48 -07001131
Andy Hung440901d2023-06-29 21:19:25 -07001132 audio_channel_mask_t mixerChannelMask() const final {
Eric Laurentf1f22e72021-07-13 14:04:14 +02001133 return mMixerChannelMask;
1134 }
1135
Andy Hung8d672e02023-09-15 18:19:28 -07001136 status_t getTimestamp_l(AudioTimestamp& timestamp) final
1137 REQUIRES(mutex(), ThreadBase_ThreadLoop);
Eric Laurent83b88082014-06-20 18:31:16 -07001138
Andy Hungab65b182023-09-06 19:41:47 -07001139 void addPatchTrack(const sp<IAfPatchTrack>& track) final EXCLUDES_ThreadBase_Mutex;
1140 void deletePatchTrack(const sp<IAfPatchTrack>& track) final EXCLUDES_ThreadBase_Mutex;
Eric Laurent83b88082014-06-20 18:31:16 -07001141
Andy Hungab65b182023-09-06 19:41:47 -07001142 // NO_THREAD_SAFETY_ANALYSIS - fix this to use atomics.
Andy Hung440901d2023-06-29 21:19:25 -07001143 void toAudioPortConfig(struct audio_port_config* config) final;
Eric Laurentaccc1472013-09-20 09:36:34 -07001144
Andy Hung10cbff12017-02-21 17:30:14 -08001145 // Return the asynchronous signal wait time.
Andy Hungab65b182023-09-06 19:41:47 -07001146 int64_t computeWaitTimeNs_l() const override REQUIRES(mutex()) { return INT64_MAX; }
Andy Hung1bc088a2018-02-09 15:57:31 -08001147 // returns true if the track is allowed to be added to the thread.
Andy Hung440901d2023-06-29 21:19:25 -07001148 bool isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08001149 audio_channel_mask_t channelMask __unused,
1150 audio_format_t format __unused,
1151 audio_session_t sessionId __unused,
Andy Hungab65b182023-09-06 19:41:47 -07001152 uid_t uid) const override REQUIRES(mutex()) {
Andy Hung1bc088a2018-02-09 15:57:31 -08001153 return trackCountForUid_l(uid) < PlaybackThread::kMaxTracksPerUid
1154 && mTracks.size() < PlaybackThread::kMaxTracks;
1155 }
1156
Andy Hungab65b182023-09-06 19:41:47 -07001157 bool isTimestampCorrectionEnabled_l() const final REQUIRES(mutex()) {
1158 return audio_is_output_devices(mTimestampCorrectedDevice)
1159 && outDeviceTypes_l().count(mTimestampCorrectedDevice) != 0;
Andy Hungc8fddf32018-08-08 18:32:37 -07001160 }
jiabinc52b1ff2019-10-31 17:20:42 -07001161
Andy Hungab65b182023-09-06 19:41:47 -07001162 // NO_THREAD_SAFETY_ANALYSIS - fix this to be atomic.
Andy Hung440901d2023-06-29 21:19:25 -07001163 bool isStreamInitialized() const final {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001164 return !(mOutput == nullptr || mOutput->stream == nullptr);
1165 }
1166
Andy Hung440901d2023-06-29 21:19:25 -07001167 audio_channel_mask_t hapticChannelMask() const final {
jiabineb3bda02020-06-30 14:07:03 -07001168 return mHapticChannelMask;
1169 }
Andy Hung87c693c2023-07-06 20:56:16 -07001170
1171 uint32_t hapticChannelCount() const final {
1172 return mHapticChannelCount;
1173 }
1174
Andy Hung440901d2023-06-29 21:19:25 -07001175 bool supportsHapticPlayback() const final {
jiabineb3bda02020-06-30 14:07:03 -07001176 return (mHapticChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE;
1177 }
1178
Andy Hungab65b182023-09-06 19:41:47 -07001179 void setDownStreamPatch(const struct audio_patch* patch) final EXCLUDES_ThreadBase_Mutex {
Andy Hung8d672e02023-09-15 18:19:28 -07001180 audio_utils::lock_guard _l(mutex());
Eric Laurent74c38dc2020-12-23 18:19:44 +01001181 mDownStreamPatch = *patch;
1182 }
1183
Andy Hungab65b182023-09-06 19:41:47 -07001184 IAfTrack* getTrackById_l(audio_port_handle_t trackId) final REQUIRES(mutex());
jiabinf042b9b2021-05-07 23:46:28 +00001185
Andy Hung440901d2023-06-29 21:19:25 -07001186 bool hasMixer() const final {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001187 return mType == MIXER || mType == DUPLICATING || mType == SPATIALIZER;
Eric Laurentb3f315a2021-07-13 15:09:05 +02001188 }
Eric Laurent68a40a82022-05-03 18:15:04 +02001189
Andy Hung440901d2023-06-29 21:19:25 -07001190 status_t setRequestedLatencyMode(
1191 audio_latency_mode_t /* mode */) override { return INVALID_OPERATION; }
Eric Laurent68a40a82022-05-03 18:15:04 +02001192
Andy Hung440901d2023-06-29 21:19:25 -07001193 status_t getSupportedLatencyModes(
1194 std::vector<audio_latency_mode_t>* /* modes */) override {
Eric Laurent68a40a82022-05-03 18:15:04 +02001195 return INVALID_OPERATION;
1196 }
1197
Andy Hung440901d2023-06-29 21:19:25 -07001198 status_t setBluetoothVariableLatencyEnabled(bool /* enabled */) override{
Eric Laurentb0463942022-12-20 16:31:10 +01001199 return INVALID_OPERATION;
1200 }
Eric Laurent52057642022-12-16 11:45:07 +01001201
Andy Hung972bec12023-08-31 16:13:39 -07001202 void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) override
1203 REQUIRES(audio_utils::AudioFlinger_Mutex);
1204 void stopMelComputation_l() override
1205 REQUIRES(audio_utils::AudioFlinger_Mutex);
Vlad Popab042ee62022-10-20 18:05:00 +02001206
Andy Hung8d672e02023-09-15 18:19:28 -07001207 void setStandby() final EXCLUDES_ThreadBase_Mutex {
1208 audio_utils::lock_guard _l(mutex());
Eric Laurent19952e12023-04-20 10:08:29 +02001209 setStandby_l();
1210 }
1211
Andy Hungab65b182023-09-06 19:41:47 -07001212 void setStandby_l() final REQUIRES(mutex()) {
Eric Laurent19952e12023-04-20 10:08:29 +02001213 mStandby = true;
1214 mHalStarted = false;
1215 mKernelPositionOnStandby =
1216 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
1217 }
1218
Andy Hungab65b182023-09-06 19:41:47 -07001219 bool waitForHalStart() final EXCLUDES_ThreadBase_Mutex {
Andy Hungc5007f82023-08-29 14:26:09 -07001220 audio_utils::unique_lock _l(mutex());
Eric Laurent19952e12023-04-20 10:08:29 +02001221 static const nsecs_t kWaitHalTimeoutNs = seconds(2);
1222 nsecs_t endWaitTimetNs = systemTime() + kWaitHalTimeoutNs;
1223 while (!mHalStarted) {
1224 nsecs_t timeNs = systemTime();
1225 if (timeNs >= endWaitTimetNs) {
1226 break;
1227 }
1228 nsecs_t waitTimeLeftNs = endWaitTimetNs - timeNs;
Andy Hungc5007f82023-08-29 14:26:09 -07001229 mWaitHalStartCV.wait_for(_l, std::chrono::nanoseconds(waitTimeLeftNs));
Eric Laurent19952e12023-04-20 10:08:29 +02001230 }
1231 return mHalStarted;
1232 }
jiabin220eea12024-05-17 17:55:20 +00001233
1234 void setTracksInternalMute(std::map<audio_port_handle_t, bool>* /* tracksInternalMute */)
1235 override EXCLUDES_ThreadBase_Mutex {
1236 // Do nothing. It is only used for bit perfect thread
1237 }
Atneya Nairaa3afcb2024-10-08 16:36:19 -07001238
1239 std::string getLocalLogHeader() const override;
1240
Eric Laurent81784c32012-11-19 14:55:58 -08001241protected:
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001242 // updated by readOutputParameters_l()
Glenn Kasten9b58f632013-07-16 11:37:48 -07001243 size_t mNormalFrameCount; // normal mixer and effects
1244
Andy Hung8d672e02023-09-15 18:19:28 -07001245 // throttle the thread processing
1246 bool mThreadThrottle GUARDED_BY(ThreadBase_ThreadLoop);
1247
1248 // throttle time for MIXER threads - atomic as read by dump()
1249 std::atomic<uint32_t> mThreadThrottleTimeMs;
1250
1251 // notify once per throttling
1252 uint32_t mThreadThrottleEndMs GUARDED_BY(ThreadBase_ThreadLoop);
1253
1254 // half the buffer size in milliseconds
1255 uint32_t mHalfBufferMs GUARDED_BY(ThreadBase_ThreadLoop);
Andy Hung08fb1742015-05-31 23:22:10 -07001256
Andy Hung010a1a12014-03-13 13:57:33 -07001257 void* mSinkBuffer; // frame size aligned sink buffer
Eric Laurent81784c32012-11-19 14:55:58 -08001258
Andy Hung98ef9782014-03-04 14:46:50 -08001259 // TODO:
1260 // Rearrange the buffer info into a struct/class with
1261 // clear, copy, construction, destruction methods.
1262 //
1263 // mSinkBuffer also has associated with it:
1264 //
1265 // mSinkBufferSize: Sink Buffer Size
1266 // mFormat: Sink Buffer Format
1267
Andy Hung69aed5f2014-02-25 17:24:40 -08001268 // Mixer Buffer (mMixerBuffer*)
1269 //
1270 // In the case of floating point or multichannel data, which is not in the
1271 // sink format, it is required to accumulate in a higher precision or greater channel count
1272 // buffer before downmixing or data conversion to the sink buffer.
1273
1274 // Set to "true" to enable the Mixer Buffer otherwise mixer output goes to sink buffer.
Andy Hung8d672e02023-09-15 18:19:28 -07001275 bool mMixerBufferEnabled GUARDED_BY(ThreadBase_ThreadLoop);
Andy Hung69aed5f2014-02-25 17:24:40 -08001276
1277 // Storage, 32 byte aligned (may make this alignment a requirement later).
1278 // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
Andy Hung8d672e02023-09-15 18:19:28 -07001279 void* mMixerBuffer GUARDED_BY(ThreadBase_ThreadLoop);
Andy Hung69aed5f2014-02-25 17:24:40 -08001280
1281 // Size of mMixerBuffer in bytes: mNormalFrameCount * #channels * sampsize.
Andy Hung8d672e02023-09-15 18:19:28 -07001282 size_t mMixerBufferSize GUARDED_BY(ThreadBase_ThreadLoop);
Andy Hung69aed5f2014-02-25 17:24:40 -08001283
1284 // The audio format of mMixerBuffer. Set to AUDIO_FORMAT_PCM_(FLOAT|16_BIT) only.
Andy Hung8d672e02023-09-15 18:19:28 -07001285 audio_format_t mMixerBufferFormat GUARDED_BY(ThreadBase_ThreadLoop);
Andy Hung69aed5f2014-02-25 17:24:40 -08001286
1287 // An internal flag set to true by MixerThread::prepareTracks_l()
1288 // when mMixerBuffer contains valid data after mixing.
Andy Hung8d672e02023-09-15 18:19:28 -07001289 bool mMixerBufferValid GUARDED_BY(ThreadBase_ThreadLoop);
Andy Hung69aed5f2014-02-25 17:24:40 -08001290
Andy Hung98ef9782014-03-04 14:46:50 -08001291 // Effects Buffer (mEffectsBuffer*)
1292 //
1293 // In the case of effects data, which is not in the sink format,
1294 // it is required to accumulate in a different buffer before data conversion
1295 // to the sink buffer.
1296
1297 // Set to "true" to enable the Effects Buffer otherwise effects output goes to sink buffer.
Andy Hung8d672e02023-09-15 18:19:28 -07001298 bool mEffectBufferEnabled;
1299 // NO_THREAD_SAFETY_ANALYSIS: Spatializer access this in addEffectChain_l()
Andy Hung98ef9782014-03-04 14:46:50 -08001300
1301 // Storage, 32 byte aligned (may make this alignment a requirement later).
1302 // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
Andy Hung8d672e02023-09-15 18:19:28 -07001303 void* mEffectBuffer;
1304 // NO_THREAD_SAFETY_ANALYSIS: Spatializer access this in addEffectChain_l()
Andy Hung98ef9782014-03-04 14:46:50 -08001305
1306 // Size of mEffectsBuffer in bytes: mNormalFrameCount * #channels * sampsize.
Andy Hung8d672e02023-09-15 18:19:28 -07001307 size_t mEffectBufferSize;
1308 // NO_THREAD_SAFETY_ANALYSIS: Spatializer access this in addEffectChain_l()
Andy Hung98ef9782014-03-04 14:46:50 -08001309
1310 // The audio format of mEffectsBuffer. Set to AUDIO_FORMAT_PCM_16_BIT only.
Andy Hung8d672e02023-09-15 18:19:28 -07001311 // NO_THREAD_SAFETY_ANALYSIS: Spatializer access this in addEffectChain_l()
1312 audio_format_t mEffectBufferFormat;
Andy Hung98ef9782014-03-04 14:46:50 -08001313
1314 // An internal flag set to true by MixerThread::prepareTracks_l()
1315 // when mEffectsBuffer contains valid data after mixing.
1316 //
1317 // When this is set, all mixer data is routed into the effects buffer
1318 // for any processing (including output processing).
Andy Hung8d672e02023-09-15 18:19:28 -07001319 bool mEffectBufferValid GUARDED_BY(ThreadBase_ThreadLoop);
Andy Hung98ef9782014-03-04 14:46:50 -08001320
jiabinc658e452022-10-21 20:52:21 +00001321 // Set to "true" to enable when data has already copied to sink
Andy Hung8d672e02023-09-15 18:19:28 -07001322 bool mHasDataCopiedToSinkBuffer GUARDED_BY(ThreadBase_ThreadLoop) = false;
jiabinc658e452022-10-21 20:52:21 +00001323
Eric Laurentb62d0362021-10-26 17:40:18 +02001324 // Frame size aligned buffer used as input and output to all post processing effects
1325 // except the Spatializer in a SPATIALIZER thread. Non spatialized tracks are mixed into
1326 // this buffer so that post processing effects can be applied.
Andy Hung8d672e02023-09-15 18:19:28 -07001327 void* mPostSpatializerBuffer GUARDED_BY(mutex()) = nullptr;
Eric Laurentb62d0362021-10-26 17:40:18 +02001328
1329 // Size of mPostSpatializerBuffer in bytes
Andy Hung8d672e02023-09-15 18:19:28 -07001330 size_t mPostSpatializerBufferSize GUARDED_BY(mutex());
Eric Laurent39095982021-08-24 18:29:27 +02001331
Eric Laurent81784c32012-11-19 14:55:58 -08001332 // suspend count, > 0 means suspended. While suspended, the thread continues to pull from
1333 // tracks and mix, but doesn't write to HAL. A2DP and SCO HAL implementations can't handle
1334 // concurrent use of both of them, so Audio Policy Service suspends one of the threads to
1335 // workaround that restriction.
1336 // 'volatile' means accessed via atomic operations and no lock.
Andy Hung8d672e02023-09-15 18:19:28 -07001337 std::atomic<int32_t> mSuspended;
Eric Laurent81784c32012-11-19 14:55:58 -08001338
Andy Hung818e7a32016-02-16 18:08:07 -08001339 int64_t mBytesWritten;
Andy Hung8d672e02023-09-15 18:19:28 -07001340 std::atomic<int64_t> mFramesWritten; // not reset on standby
Dean Wheatley12473e92021-03-18 23:00:55 +11001341 int64_t mLastFramesWritten = -1; // track changes in timestamp
1342 // server frames written.
Andy Hung238fa3d2016-07-28 10:53:22 -07001343 int64_t mSuspendedFrames; // not reset on standby
jiabin245cdd92018-12-07 17:55:15 -08001344
1345 // mHapticChannelMask and mHapticChannelCount will only be valid when the thread support
1346 // haptic playback.
1347 audio_channel_mask_t mHapticChannelMask = AUDIO_CHANNEL_NONE;
1348 uint32_t mHapticChannelCount = 0;
Eric Laurentf1f22e72021-07-13 14:04:14 +02001349
1350 audio_channel_mask_t mMixerChannelMask = AUDIO_CHANNEL_NONE;
1351
Eric Laurent81784c32012-11-19 14:55:58 -08001352 // mMasterMute is in both PlaybackThread and in AudioFlinger. When a
1353 // PlaybackThread needs to find out if master-muted, it checks it's local
1354 // copy rather than the one in AudioFlinger. This optimization saves a lock.
Andy Hung8d672e02023-09-15 18:19:28 -07001355 bool mMasterMute GUARDED_BY(mutex());
1356 void setMasterMute_l(bool muted) REQUIRES(mutex()) { mMasterMute = muted; }
Dean Wheatley12473e92021-03-18 23:00:55 +11001357
1358 auto discontinuityForStandbyOrFlush() const { // call on threadLoop or with lock.
1359 return ((mType == DIRECT && !audio_is_linear_pcm(mFormat))
1360 || mType == OFFLOAD)
1361 ? mTimestampVerifier.DISCONTINUITY_MODE_ZERO
1362 : mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS;
1363 }
1364
Andy Hung8d31fd22023-06-26 19:20:57 -07001365 ActiveTracks<IAfTrack> mActiveTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08001366
Eric Laurent81784c32012-11-19 14:55:58 -08001367 // Time to sleep between cycles when:
1368 virtual uint32_t activeSleepTimeUs() const; // mixer state MIXER_TRACKS_ENABLED
1369 virtual uint32_t idleSleepTimeUs() const = 0; // mixer state MIXER_IDLE
1370 virtual uint32_t suspendSleepTimeUs() const = 0; // audio policy manager suspended us
1371 // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write()
1372 // No sleep in standby mode; waits on a condition
1373
1374 // Code snippets that are temporarily lifted up out of threadLoop() until the merge
Andy Hungab65b182023-09-06 19:41:47 -07001375
1376 // consider unification with MMapThread
1377 virtual void checkSilentMode_l() final REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001378
1379 // Non-trivial for DUPLICATING only
Andy Hung8d672e02023-09-15 18:19:28 -07001380 virtual void saveOutputTracks() REQUIRES(ThreadBase_ThreadLoop) {}
1381 virtual void clearOutputTracks() REQUIRES(ThreadBase_ThreadLoop) {}
Eric Laurent81784c32012-11-19 14:55:58 -08001382
1383 // Cache various calculated values, at threadLoop() entry and after a parameter change
Andy Hung8d672e02023-09-15 18:19:28 -07001384 virtual void cacheParameters_l() REQUIRES(mutex(), ThreadBase_ThreadLoop);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001385 void setCheckOutputStageEffects() override {
1386 mCheckOutputStageEffects.store(true);
1387 }
Eric Laurent81784c32012-11-19 14:55:58 -08001388
Andy Hungab65b182023-09-06 19:41:47 -07001389 virtual uint32_t correctLatency_l(uint32_t latency) const REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001390
Eric Laurent1c333e22014-05-20 10:48:17 -07001391 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
Andy Hungab65b182023-09-06 19:41:47 -07001392 audio_patch_handle_t *handle) REQUIRES(mutex());
1393 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle)
1394 REQUIRES(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -07001395
Andy Hungab65b182023-09-06 19:41:47 -07001396 // NO_THREAD_SAFETY_ANALYSIS - fix this to use atomics
Andy Hung87c693c2023-07-06 20:56:16 -07001397 bool usesHwAvSync() const final { return mType == DIRECT && mOutput != nullptr
Phil Burk6fc2a7c2015-04-30 16:08:10 -07001398 && mHwSupportsPause
1399 && (mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC); }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08001400
Andy Hung1bc088a2018-02-09 15:57:31 -08001401 uint32_t trackCountForUid_l(uid_t uid) const;
Eric Laurentad7dd962016-09-22 12:38:37 -07001402
jiabineb3bda02020-06-30 14:07:03 -07001403 void invalidateTracksForAudioSession_l(
Andy Hungab65b182023-09-06 19:41:47 -07001404 audio_session_t sessionId) const override REQUIRES(mutex()) {
jiabineb3bda02020-06-30 14:07:03 -07001405 ThreadBase::invalidateTracksForAudioSession_l(sessionId, mTracks);
1406 }
1407
Mikhail Naganovbf493082017-04-17 17:37:12 -07001408 DISALLOW_COPY_AND_ASSIGN(PlaybackThread);
Eric Laurent81784c32012-11-19 14:55:58 -08001409
Andy Hungab65b182023-09-06 19:41:47 -07001410 status_t addTrack_l(const sp<IAfTrack>& track) final REQUIRES(mutex());
1411 bool destroyTrack_l(const sp<IAfTrack>& track) final REQUIRES(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07001412
Andy Hungab65b182023-09-06 19:41:47 -07001413 void removeTrack_l(const sp<IAfTrack>& track) REQUIRES(mutex());
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07001414 std::set<audio_port_handle_t> getTrackPortIds_l() REQUIRES(mutex());
1415 std::set<audio_port_handle_t> getTrackPortIds();
Eric Laurent81784c32012-11-19 14:55:58 -08001416
Andy Hungab65b182023-09-06 19:41:47 -07001417 void readOutputParameters_l() REQUIRES(mutex());
1418 MetadataUpdate updateMetadata_l() final REQUIRES(mutex());
1419 virtual void sendMetadataToBackend_l(const StreamOutHalInterface::SourceMetadata& metadata)
1420 REQUIRES(mutex()) ;
Eric Laurent81784c32012-11-19 14:55:58 -08001421
Andy Hung8d672e02023-09-15 18:19:28 -07001422 void collectTimestamps_l() REQUIRES(mutex(), ThreadBase_ThreadLoop);
Dean Wheatley12473e92021-03-18 23:00:55 +11001423
Andy Hungc0691382018-09-12 18:01:57 -07001424 // The Tracks class manages tracks added and removed from the Thread.
Andy Hung1bc088a2018-02-09 15:57:31 -08001425 template <typename T>
1426 class Tracks {
1427 public:
Andy Hung920f6572022-10-06 12:09:49 -07001428 explicit Tracks(bool saveDeletedTrackIds) :
Andy Hungc0691382018-09-12 18:01:57 -07001429 mSaveDeletedTrackIds(saveDeletedTrackIds) { }
Andy Hung1bc088a2018-02-09 15:57:31 -08001430
1431 // SortedVector methods
Andy Hungc0691382018-09-12 18:01:57 -07001432 ssize_t add(const sp<T> &track) {
1433 const ssize_t index = mTracks.add(track);
1434 LOG_ALWAYS_FATAL_IF(index < 0, "cannot add track");
1435 return index;
1436 }
Andy Hung1bc088a2018-02-09 15:57:31 -08001437 ssize_t remove(const sp<T> &track);
1438 size_t size() const {
1439 return mTracks.size();
1440 }
1441 bool isEmpty() const {
1442 return mTracks.isEmpty();
1443 }
1444 ssize_t indexOf(const sp<T> &item) {
1445 return mTracks.indexOf(item);
1446 }
1447 sp<T> operator[](size_t index) const {
1448 return mTracks[index];
1449 }
1450 typename SortedVector<sp<T>>::iterator begin() {
1451 return mTracks.begin();
1452 }
1453 typename SortedVector<sp<T>>::iterator end() {
1454 return mTracks.end();
1455 }
1456
Andy Hung920f6572022-10-06 12:09:49 -07001457 size_t processDeletedTrackIds(const std::function<void(int)>& f) {
Andy Hungc0691382018-09-12 18:01:57 -07001458 for (const int trackId : mDeletedTrackIds) {
1459 f(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08001460 }
Andy Hungc0691382018-09-12 18:01:57 -07001461 return mDeletedTrackIds.size();
Andy Hung1bc088a2018-02-09 15:57:31 -08001462 }
1463
Andy Hungc0691382018-09-12 18:01:57 -07001464 void clearDeletedTrackIds() { mDeletedTrackIds.clear(); }
Andy Hung1bc088a2018-02-09 15:57:31 -08001465
1466 private:
Andy Hungc0691382018-09-12 18:01:57 -07001467 // Tracks pending deletion for MIXER type threads
1468 const bool mSaveDeletedTrackIds; // true to enable tracking
1469 std::set<int> mDeletedTrackIds;
Andy Hung1bc088a2018-02-09 15:57:31 -08001470
1471 SortedVector<sp<T>> mTracks; // wrapped SortedVector.
1472 };
1473
Andy Hung8d31fd22023-06-26 19:20:57 -07001474 Tracks<IAfTrack> mTracks;
Andy Hung1bc088a2018-02-09 15:57:31 -08001475
Eric Laurent223fd5c2014-11-11 13:43:36 -08001476 stream_type_t mStreamTypes[AUDIO_STREAM_CNT];
Andy Hungee58e4a2023-07-07 13:47:37 -07001477
Eric Laurent81784c32012-11-19 14:55:58 -08001478 AudioStreamOut *mOutput;
1479
1480 float mMasterVolume;
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001481 std::atomic<float> mMasterBalance{};
1482 audio_utils::Balance mBalance;
Eric Laurent81784c32012-11-19 14:55:58 -08001483 int mNumWrites;
1484 int mNumDelayedWrites;
1485 bool mInWrite;
1486
1487 // FIXME rename these former local variables of threadLoop to standard "m" names
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001488 nsecs_t mStandbyTimeNs;
Andy Hung25c2dac2014-02-27 14:56:00 -08001489 size_t mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001490
1491 // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l()
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001492 uint32_t mActiveSleepTimeUs;
1493 uint32_t mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08001494
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001495 uint32_t mSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08001496
1497 // mixer status returned by prepareTracks_l()
Andy Hung8d672e02023-09-15 18:19:28 -07001498 mixer_state mMixerStatus GUARDED_BY(ThreadBase_ThreadLoop); // current cycle
Eric Laurent81784c32012-11-19 14:55:58 -08001499 // previous cycle when in prepareTracks_l()
Andy Hung8d672e02023-09-15 18:19:28 -07001500 mixer_state mMixerStatusIgnoringFastTracks GUARDED_BY(ThreadBase_ThreadLoop);
Eric Laurent81784c32012-11-19 14:55:58 -08001501 // FIXME or a separate ready state per track
1502
1503 // FIXME move these declarations into the specific sub-class that needs them
1504 // MIXER only
Andy Hung8d672e02023-09-15 18:19:28 -07001505 uint32_t sleepTimeShift GUARDED_BY(ThreadBase_ThreadLoop);
Eric Laurent81784c32012-11-19 14:55:58 -08001506
1507 // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value
Andy Hung8d672e02023-09-15 18:19:28 -07001508 nsecs_t mStandbyDelayNs; // GUARDED_BY(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001509
1510 // MIXER only
1511 nsecs_t maxPeriod;
1512
1513 // DUPLICATING only
1514 uint32_t writeFrames;
1515
Andy Hung8d672e02023-09-15 18:19:28 -07001516 size_t mBytesRemaining GUARDED_BY(ThreadBase_ThreadLoop);
1517 size_t mCurrentWriteLength GUARDED_BY(ThreadBase_ThreadLoop);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001518 bool mUseAsyncWrite;
Eric Laurent3b4529e2013-09-05 18:09:19 -07001519 // mWriteAckSequence contains current write sequence on bits 31-1. The write sequence is
1520 // incremented each time a write(), a flush() or a standby() occurs.
1521 // Bit 0 is set when a write blocks and indicates a callback is expected.
1522 // Bit 0 is reset by the async callback thread calling resetWriteBlocked(). Out of sequence
1523 // callbacks are ignored.
1524 uint32_t mWriteAckSequence;
1525 // mDrainSequence contains current drain sequence on bits 31-1. The drain sequence is
1526 // incremented each time a drain is requested or a flush() or standby() occurs.
1527 // Bit 0 is set when the drain() command is called at the HAL and indicates a callback is
1528 // expected.
1529 // Bit 0 is reset by the async callback thread calling resetDraining(). Out of sequence
1530 // callbacks are ignored.
1531 uint32_t mDrainSequence;
Andy Hungee58e4a2023-07-07 13:47:37 -07001532
Eric Laurentbfb1b832013-01-07 09:53:42 -08001533 sp<AsyncCallbackThread> mCallbackThread;
1534
Andy Hungc5007f82023-08-29 14:26:09 -07001535 audio_utils::mutex& audioTrackCbMutex() const { return mAudioTrackCbMutex; }
Andy Hunga6f1cbb2023-10-12 18:18:13 -07001536 mutable audio_utils::mutex mAudioTrackCbMutex{
1537 audio_utils::MutexOrder::kPlaybackThread_AudioTrackCbMutex};
jiabinf6eb4c32020-02-25 14:06:25 -08001538 // Record of IAudioTrackCallback
Andy Hung8d31fd22023-06-26 19:20:57 -07001539 std::map<sp<IAfTrack>, sp<media::IAudioTrackCallback>> mAudioTrackCallbacks;
jiabinf6eb4c32020-02-25 14:06:25 -08001540
Eric Laurent81784c32012-11-19 14:55:58 -08001541 // The HAL output sink is treated as non-blocking, but current implementation is blocking
1542 sp<NBAIO_Sink> mOutputSink;
1543 // If a fast mixer is present, the blocking pipe sink, otherwise clear
1544 sp<NBAIO_Sink> mPipeSink;
1545 // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink
1546 sp<NBAIO_Sink> mNormalSink;
Andy Hungee58e4a2023-07-07 13:47:37 -07001547
Eric Laurent81784c32012-11-19 14:55:58 -08001548 uint32_t mScreenState; // cached copy of gScreenState
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07001549 // TODO: add comment and adjust size as needed
Glenn Kasteneef598c2017-04-03 14:41:13 -07001550 static const size_t kFastMixerLogSize = 8 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -08001551 sp<NBLog::Writer> mFastMixerNBLogWriter;
Andy Hung2148bf02016-11-28 19:01:02 -08001552
Dean Wheatley30d28422018-11-06 10:27:40 +11001553 // Downstream patch latency, available if mDownstreamLatencyStatMs.getN() > 0.
1554 audio_utils::Statistics<double> mDownstreamLatencyStatMs{0.999};
Andy Hung2148bf02016-11-28 19:01:02 -08001555
Eric Laurent19952e12023-04-20 10:08:29 +02001556 // output stream start detection based on render position returned by the kernel
1557 // condition signalled when the output stream has started
Andy Hungc5007f82023-08-29 14:26:09 -07001558 audio_utils::condition_variable mWaitHalStartCV;
Eric Laurent19952e12023-04-20 10:08:29 +02001559 // true when the output stream render position has moved, reset to false in standby
1560 bool mHalStarted = false;
1561 // last kernel render position saved when entering standby
1562 int64_t mKernelPositionOnStandby = 0;
1563
Eric Laurent81784c32012-11-19 14:55:58 -08001564public:
Andy Hung440901d2023-06-29 21:19:25 -07001565 FastTrackUnderruns getFastTrackUnderruns(size_t /* fastIndex */) const override
1566 { return {}; }
1567 const std::atomic<int64_t>& framesWritten() const final { return mFramesWritten; }
Eric Laurent81784c32012-11-19 14:55:58 -08001568
1569protected:
1570 // accessed by both binder threads and within threadLoop(), lock on mutex needed
Andy Hungab65b182023-09-06 19:41:47 -07001571 uint32_t& fastTrackAvailMask_l() final REQUIRES(mutex()) { return mFastTrackAvailMask; }
Andy Hung87c693c2023-07-06 20:56:16 -07001572 uint32_t mFastTrackAvailMask; // bit i set if fast track [i] is available
Eric Laurentd1f69b02014-12-15 14:33:13 -08001573 bool mHwSupportsPause;
1574 bool mHwPaused;
1575 bool mFlushPending;
Eric Laurent7c29ec92017-09-20 17:54:22 -07001576 // volumes last sent to audio HAL with stream->setVolume()
1577 float mLeftVolFloat;
1578 float mRightVolFloat;
Eric Laurent74c38dc2020-12-23 18:19:44 +01001579
1580 // audio patch used by the downstream software patch.
1581 // Only used if ThreadBase::mIsMsdDevice is true.
1582 struct audio_patch mDownStreamPatch;
Eric Laurentb3f315a2021-07-13 15:09:05 +02001583
1584 std::atomic_bool mCheckOutputStageEffects{};
ziyangch8f194f12021-12-01 13:48:04 -08001585
ziyangch8f194f12021-12-01 13:48:04 -08001586
Brian Lindahl65e90012022-07-27 18:01:07 +02001587 // Provides periodic checking for timestamp advancement for underrun detection.
1588 class IsTimestampAdvancing {
1589 public:
1590 // The timestamp will not be checked any faster than the specified time.
Andy Hung920f6572022-10-06 12:09:49 -07001591 explicit IsTimestampAdvancing(nsecs_t minimumTimeBetweenChecksNs)
Brian Lindahl65e90012022-07-27 18:01:07 +02001592 : mMinimumTimeBetweenChecksNs(minimumTimeBetweenChecksNs)
1593 {
1594 clear();
1595 }
1596 // Check if the presentation position has advanced in the last periodic time.
1597 bool check(AudioStreamOut * output);
1598 // Clear the internal state when the playback state changes for the output
1599 // stream.
1600 void clear();
1601 private:
1602 // The minimum time between timestamp checks.
1603 const nsecs_t mMinimumTimeBetweenChecksNs;
1604 // Add differential check on the timestamps to see if there is a change in the
1605 // timestamp frame position between the last call to check.
1606 uint64_t mPreviousPosition;
1607 // The time at which the last check occurred, to ensure we don't check too
1608 // frequently, giving the Audio HAL enough time to update its timestamps.
1609 nsecs_t mPreviousNs;
1610 // The valued is latched so we don't check timestamps too frequently.
1611 bool mLatchedValue;
1612 };
1613 IsTimestampAdvancing mIsTimestampAdvancing;
ziyangch8f194f12021-12-01 13:48:04 -08001614
Brian Lindahl65e90012022-07-27 18:01:07 +02001615 virtual void flushHw_l() {
1616 mIsTimestampAdvancing.clear();
1617 }
Eric Laurent81784c32012-11-19 14:55:58 -08001618};
1619
Eric Laurentb0463942022-12-20 16:31:10 +01001620class MixerThread : public PlaybackThread,
1621 public StreamOutHalInterfaceLatencyModeCallback {
Eric Laurent81784c32012-11-19 14:55:58 -08001622public:
Andy Hung583043b2023-07-17 17:05:00 -07001623 MixerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08001624 AudioStreamOut* output,
1625 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001626 bool systemReady,
Eric Laurentf1f22e72021-07-13 14:04:14 +02001627 type_t type = MIXER,
1628 audio_config_base_t *mixerConfig = nullptr);
Andy Hung440901d2023-06-29 21:19:25 -07001629 ~MixerThread() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001630
Eric Laurentb0463942022-12-20 16:31:10 +01001631 // RefBase
Andy Hung440901d2023-06-29 21:19:25 -07001632 void onFirstRef() override;
Eric Laurentb0463942022-12-20 16:31:10 +01001633
1634 // StreamOutHalInterfaceLatencyModeCallback
1635 void onRecommendedLatencyModeChanged(
Andy Hung440901d2023-06-29 21:19:25 -07001636 std::vector<audio_latency_mode_t> modes) final;
Eric Laurentb0463942022-12-20 16:31:10 +01001637
Eric Laurent81784c32012-11-19 14:55:58 -08001638 // Thread virtuals
1639
Andy Hungab65b182023-09-06 19:41:47 -07001640 bool checkForNewParameter_l(const String8& keyValuePair, status_t& status) final
1641 REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001642
Andy Hung440901d2023-06-29 21:19:25 -07001643 bool isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08001644 audio_channel_mask_t channelMask, audio_format_t format,
Andy Hungab65b182023-09-06 19:41:47 -07001645 audio_session_t sessionId, uid_t uid) const final REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001646protected:
Andy Hung8d672e02023-09-15 18:19:28 -07001647 mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove) override
1648 REQUIRES(mutex(), ThreadBase_ThreadLoop);
Andy Hung440901d2023-06-29 21:19:25 -07001649 uint32_t idleSleepTimeUs() const final;
1650 uint32_t suspendSleepTimeUs() const final;
Andy Hung8d672e02023-09-15 18:19:28 -07001651 void cacheParameters_l() override REQUIRES(mutex(), ThreadBase_ThreadLoop);
Eric Laurent81784c32012-11-19 14:55:58 -08001652
Andy Hungab65b182023-09-06 19:41:47 -07001653 void acquireWakeLock_l() final REQUIRES(mutex()) {
Andy Hungdae27702016-10-31 14:01:16 -07001654 PlaybackThread::acquireWakeLock_l();
Andy Hung818e7a32016-02-16 18:08:07 -08001655 if (hasFastMixer()) {
1656 mFastMixer->setBoottimeOffset(
1657 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME]);
1658 }
1659 }
1660
Andy Hungab65b182023-09-06 19:41:47 -07001661 void dumpInternals_l(int fd, const Vector<String16>& args) override REQUIRES(mutex());
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001662
Eric Laurent81784c32012-11-19 14:55:58 -08001663 // threadLoop snippets
Andy Hung8d672e02023-09-15 18:19:28 -07001664 ssize_t threadLoop_write() override REQUIRES(ThreadBase_ThreadLoop);
1665 void threadLoop_standby() override REQUIRES(ThreadBase_ThreadLoop);
1666 void threadLoop_mix() override REQUIRES(ThreadBase_ThreadLoop);
1667 void threadLoop_sleepTime() override REQUIRES(ThreadBase_ThreadLoop);
Andy Hungab65b182023-09-06 19:41:47 -07001668 uint32_t correctLatency_l(uint32_t latency) const final REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001669
Andy Hung440901d2023-06-29 21:19:25 -07001670 status_t createAudioPatch_l(
Andy Hungab65b182023-09-06 19:41:47 -07001671 const struct audio_patch* patch, audio_patch_handle_t* handle)
1672 final REQUIRES(mutex());
1673 status_t releaseAudioPatch_l(const audio_patch_handle_t handle) final REQUIRES(mutex());
Eric Laurent054d9d32015-04-24 08:48:48 -07001674
Eric Laurent81784c32012-11-19 14:55:58 -08001675 AudioMixer* mAudioMixer; // normal mixer
Eric Laurentb0463942022-12-20 16:31:10 +01001676
1677 // Support low latency mode by default as unless explicitly indicated by the audio HAL
1678 // we assume the audio path is compatible with the head tracking latency requirements
1679 std::vector<audio_latency_mode_t> mSupportedLatencyModes = {AUDIO_LATENCY_MODE_LOW};
1680 // default to invalid value to force first update to the audio HAL
1681 audio_latency_mode_t mSetLatencyMode =
1682 (audio_latency_mode_t)AUDIO_LATENCY_MODE_INVALID;
1683
1684 // Bluetooth Variable latency control logic is enabled or disabled for this thread
1685 std::atomic_bool mBluetoothLatencyModesEnabled;
1686
Eric Laurent81784c32012-11-19 14:55:58 -08001687private:
1688 // one-time initialization, no locks required
Glenn Kasten4d23ca32014-05-13 10:39:51 -07001689 sp<FastMixer> mFastMixer; // non-0 if there is also a fast mixer
Eric Laurent81784c32012-11-19 14:55:58 -08001690 sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread
1691
1692 // contents are not guaranteed to be consistent, no locks required
1693 FastMixerDumpState mFastMixerDumpState;
1694#ifdef STATE_QUEUE_DUMP
1695 StateQueueObserverDump mStateQueueObserverDump;
1696 StateQueueMutatorDump mStateQueueMutatorDump;
1697#endif
1698 AudioWatchdogDump mAudioWatchdogDump;
1699
1700 // accessible only within the threadLoop(), no locks required
1701 // mFastMixer->sq() // for mutating and pushing state
Andy Hung8d672e02023-09-15 18:19:28 -07001702 int32_t mFastMixerFutex GUARDED_BY(ThreadBase_ThreadLoop); // for cold idle
Eric Laurent81784c32012-11-19 14:55:58 -08001703
Andy Hung2ddee192015-12-18 17:34:44 -08001704 std::atomic_bool mMasterMono;
Eric Laurent81784c32012-11-19 14:55:58 -08001705public:
Glenn Kasten4d23ca32014-05-13 10:39:51 -07001706 virtual bool hasFastMixer() const { return mFastMixer != 0; }
Eric Laurent81784c32012-11-19 14:55:58 -08001707 virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const {
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001708 ALOG_ASSERT(fastIndex < FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08001709 return mFastMixerDumpState.mTracks[fastIndex].mUnderruns;
1710 }
Eric Laurent83b88082014-06-20 18:31:16 -07001711
Andy Hungab65b182023-09-06 19:41:47 -07001712 status_t threadloop_getHalTimestamp_l(
Andy Hung8d672e02023-09-15 18:19:28 -07001713 ExtendedTimestamp *timestamp) const override
1714 REQUIRES(mutex(), ThreadBase_ThreadLoop) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07001715 if (mNormalSink.get() != nullptr) {
1716 return mNormalSink->getTimestamp(*timestamp);
1717 }
1718 return INVALID_OPERATION;
1719 }
1720
Eric Laurentb0463942022-12-20 16:31:10 +01001721 status_t getSupportedLatencyModes(
1722 std::vector<audio_latency_mode_t>* modes) override;
1723
1724 status_t setBluetoothVariableLatencyEnabled(bool enabled) override;
1725
Andy Hung2ddee192015-12-18 17:34:44 -08001726protected:
1727 virtual void setMasterMono_l(bool mono) {
1728 mMasterMono.store(mono);
1729 if (mFastMixer != nullptr) { /* hasFastMixer() */
1730 mFastMixer->setMasterMono(mMasterMono);
1731 }
1732 }
1733 // the FastMixer performs mono blend if it exists.
Glenn Kasten03c48d52016-01-27 17:25:17 -08001734 // Blending with limiter is not idempotent,
1735 // and blending without limiter is idempotent but inefficient to do twice.
Andy Hung2ddee192015-12-18 17:34:44 -08001736 virtual bool requireMonoBlend() { return mMasterMono.load() && !hasFastMixer(); }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001737
Andy Hungab65b182023-09-06 19:41:47 -07001738 void setMasterBalance(float balance) override EXCLUDES_ThreadBase_Mutex {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001739 mMasterBalance.store(balance);
1740 if (hasFastMixer()) {
1741 mFastMixer->setMasterBalance(balance);
1742 }
1743 }
Eric Laurentb0463942022-12-20 16:31:10 +01001744
Andy Hungab65b182023-09-06 19:41:47 -07001745 void updateHalSupportedLatencyModes_l() REQUIRES(mutex());
1746 void onHalLatencyModesChanged_l() override REQUIRES(mutex());
1747 void setHalLatencyMode_l() override REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001748};
1749
Andy Hung87c693c2023-07-06 20:56:16 -07001750class DirectOutputThread : public PlaybackThread, public virtual IAfDirectOutputThread {
Eric Laurent81784c32012-11-19 14:55:58 -08001751public:
1752
Andy Hung87c693c2023-07-06 20:56:16 -07001753 sp<IAfDirectOutputThread> asIAfDirectOutputThread() final {
1754 return sp<IAfDirectOutputThread>::fromExisting(this);
1755 }
1756
Andy Hung583043b2023-07-17 17:05:00 -07001757 DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Gareth Fennb18c1a32022-10-05 13:42:36 -07001758 audio_io_handle_t id, bool systemReady,
1759 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07001760 : DirectOutputThread(afThreadCallback, output, id, DIRECT, systemReady, offloadInfo) { }
Andy Hung48f59ed2019-01-28 15:06:59 -08001761
Andy Hungab65b182023-09-06 19:41:47 -07001762 ~DirectOutputThread() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001763
Andy Hung87c693c2023-07-06 20:56:16 -07001764 status_t selectPresentation(int presentationId, int programId) final;
Mikhail Naganovac917ac2018-11-28 14:03:52 -08001765
Eric Laurent81784c32012-11-19 14:55:58 -08001766 // Thread virtuals
1767
Eric Laurent10351942014-05-08 18:49:52 -07001768 virtual bool checkForNewParameter_l(const String8& keyValuePair,
Andy Hungab65b182023-09-06 19:41:47 -07001769 status_t& status) REQUIRES(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001770
Andy Hung8d672e02023-09-15 18:19:28 -07001771 void flushHw_l() override REQUIRES(mutex(), ThreadBase_ThreadLoop);
Eric Laurent81784c32012-11-19 14:55:58 -08001772
Andy Hungab65b182023-09-06 19:41:47 -07001773 void setMasterBalance(float balance) override EXCLUDES_ThreadBase_Mutex;
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001774
Eric Laurent81784c32012-11-19 14:55:58 -08001775protected:
Eric Laurent81784c32012-11-19 14:55:58 -08001776 virtual uint32_t activeSleepTimeUs() const;
1777 virtual uint32_t idleSleepTimeUs() const;
1778 virtual uint32_t suspendSleepTimeUs() const;
Andy Hung8d672e02023-09-15 18:19:28 -07001779 virtual void cacheParameters_l() REQUIRES(mutex(), ThreadBase_ThreadLoop);
Eric Laurent81784c32012-11-19 14:55:58 -08001780
Andy Hungab65b182023-09-06 19:41:47 -07001781 void dumpInternals_l(int fd, const Vector<String16>& args) override REQUIRES(mutex());
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001782
Eric Laurent81784c32012-11-19 14:55:58 -08001783 // threadLoop snippets
Andy Hung8d672e02023-09-15 18:19:28 -07001784 virtual mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove)
1785 REQUIRES(mutex(), ThreadBase_ThreadLoop);
1786 virtual void threadLoop_mix() REQUIRES(ThreadBase_ThreadLoop);
1787 virtual void threadLoop_sleepTime() REQUIRES(ThreadBase_ThreadLoop);
1788 virtual void threadLoop_exit() REQUIRES(ThreadBase_ThreadLoop);
Andy Hungab65b182023-09-06 19:41:47 -07001789 virtual bool shouldStandby_l() REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001790
Andy Hungab65b182023-09-06 19:41:47 -07001791 virtual void onAddNewTrack_l() REQUIRES(mutex());
Phil Burk43b4dcc2015-06-09 16:53:44 -07001792
Gareth Fennb18c1a32022-10-05 13:42:36 -07001793 const audio_offload_info_t mOffloadInfo;
Andy Hung398ffa22022-12-13 19:19:53 -08001794
1795 audioflinger::MonotonicFrameCounter mMonotonicFrameCounter; // for VolumeShaper
Andy Hung48f59ed2019-01-28 15:06:59 -08001796 bool mVolumeShaperActive = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001797
Andy Hung583043b2023-07-17 17:05:00 -07001798 DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Gareth Fennb18c1a32022-10-05 13:42:36 -07001799 audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
1800 const audio_offload_info_t& offloadInfo);
Andy Hungab65b182023-09-06 19:41:47 -07001801 void processVolume_l(IAfTrack *track, bool lastTrack) REQUIRES(mutex());
Gareth Fennb18c1a32022-10-05 13:42:36 -07001802 bool isTunerStream() const { return (mOffloadInfo.content_id > 0); }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001803
Eric Laurent81784c32012-11-19 14:55:58 -08001804 // prepareTracks_l() tells threadLoop_mix() the name of the single active track
Andy Hung8d31fd22023-06-26 19:20:57 -07001805 sp<IAfTrack> mActiveTrack;
Phil Burk43b4dcc2015-06-09 16:53:44 -07001806
Andy Hung8d31fd22023-06-26 19:20:57 -07001807 wp<IAfTrack> mPreviousTrack; // used to detect track switch
Phil Burk43b4dcc2015-06-09 16:53:44 -07001808
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001809 // This must be initialized for initial condition of mMasterBalance = 0 (disabled).
1810 float mMasterBalanceLeft = 1.f;
1811 float mMasterBalanceRight = 1.f;
1812
Eric Laurent81784c32012-11-19 14:55:58 -08001813public:
1814 virtual bool hasFastMixer() const { return false; }
Andy Hung10cbff12017-02-21 17:30:14 -08001815
Andy Hungab65b182023-09-06 19:41:47 -07001816 virtual int64_t computeWaitTimeNs_l() const override REQUIRES(mutex());
Andy Hungf3234512018-07-03 14:51:47 -07001817
1818 status_t threadloop_getHalTimestamp_l(ExtendedTimestamp *timestamp) const override {
1819 // For DIRECT and OFFLOAD threads, query the output sink directly.
1820 if (mOutput != nullptr) {
1821 uint64_t uposition64;
1822 struct timespec time;
1823 if (mOutput->getPresentationPosition(
1824 &uposition64, &time) == OK) {
1825 timestamp->mPosition[ExtendedTimestamp::LOCATION_KERNEL]
1826 = (int64_t)uposition64;
1827 timestamp->mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
1828 = audio_utils_ns_from_timespec(&time);
1829 return NO_ERROR;
1830 }
1831 }
1832 return INVALID_OPERATION;
1833 }
Eric Laurent81784c32012-11-19 14:55:58 -08001834};
1835
Eric Laurentbfb1b832013-01-07 09:53:42 -08001836class OffloadThread : public DirectOutputThread {
1837public:
1838
Andy Hung583043b2023-07-17 17:05:00 -07001839 OffloadThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Gareth Fennb18c1a32022-10-05 13:42:36 -07001840 audio_io_handle_t id, bool systemReady,
1841 const audio_offload_info_t& offloadInfo);
Eric Laurent6a51d7e2013-10-17 18:59:26 -07001842 virtual ~OffloadThread() {};
Andy Hung8d672e02023-09-15 18:19:28 -07001843 void flushHw_l() final REQUIRES(mutex(), ThreadBase_ThreadLoop);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001844
1845protected:
1846 // threadLoop snippets
Andy Hungab65b182023-09-06 19:41:47 -07001847 mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove) final
Andy Hung8d672e02023-09-15 18:19:28 -07001848 REQUIRES(mutex(), ThreadBase_ThreadLoop);
1849 void threadLoop_exit() final REQUIRES(ThreadBase_ThreadLoop);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001850
Andy Hungab65b182023-09-06 19:41:47 -07001851 bool waitingAsyncCallback() final;
1852 bool waitingAsyncCallback_l() final REQUIRES(mutex());
1853 void invalidateTracks(audio_stream_type_t streamType) final EXCLUDES_ThreadBase_Mutex;
1854 void invalidateTracks(std::set<audio_port_handle_t>& portIds) final EXCLUDES_ThreadBase_Mutex;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001855
Andy Hungab65b182023-09-06 19:41:47 -07001856 bool keepWakeLock() const final { return (mKeepWakeLock || (mDrainSequence & 1)); }
Eric Laurent64667972016-03-30 18:19:46 -07001857
Eric Laurentbfb1b832013-01-07 09:53:42 -08001858private:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001859 size_t mPausedWriteLength; // length in bytes of write interrupted by pause
1860 size_t mPausedBytesRemaining; // bytes still waiting in mixbuffer after resume
Eric Laurent64667972016-03-30 18:19:46 -07001861 bool mKeepWakeLock; // keep wake lock while waiting for write callback
Eric Laurentbfb1b832013-01-07 09:53:42 -08001862};
1863
1864class AsyncCallbackThread : public Thread {
1865public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001866 explicit AsyncCallbackThread(const wp<PlaybackThread>& playbackThread);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001867
Eric Laurentbfb1b832013-01-07 09:53:42 -08001868 // Thread virtuals
Andy Hung8d672e02023-09-15 18:19:28 -07001869 bool threadLoop() final;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001870
1871 // RefBase
Andy Hung8d672e02023-09-15 18:19:28 -07001872 void onFirstRef() final;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001873
1874 void exit();
Eric Laurent3b4529e2013-09-05 18:09:19 -07001875 void setWriteBlocked(uint32_t sequence);
1876 void resetWriteBlocked();
1877 void setDraining(uint32_t sequence);
1878 void resetDraining();
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07001879 void setAsyncError(bool isHardError);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001880
1881private:
Eric Laurent4de95592013-09-26 15:28:21 -07001882 const wp<PlaybackThread> mPlaybackThread;
Eric Laurent3b4529e2013-09-05 18:09:19 -07001883 // mWriteAckSequence corresponds to the last write sequence passed by the offload thread via
1884 // setWriteBlocked(). The sequence is shifted one bit to the left and the lsb is used
1885 // to indicate that the callback has been received via resetWriteBlocked()
Eric Laurent4de95592013-09-26 15:28:21 -07001886 uint32_t mWriteAckSequence;
Eric Laurent3b4529e2013-09-05 18:09:19 -07001887 // mDrainSequence corresponds to the last drain sequence passed by the offload thread via
1888 // setDraining(). The sequence is shifted one bit to the left and the lsb is used
1889 // to indicate that the callback has been received via resetDraining()
Eric Laurent4de95592013-09-26 15:28:21 -07001890 uint32_t mDrainSequence;
Andy Hungc5007f82023-08-29 14:26:09 -07001891 audio_utils::condition_variable mWaitWorkCV;
Andy Hunga6f1cbb2023-10-12 18:18:13 -07001892 mutable audio_utils::mutex mMutex{audio_utils::MutexOrder::kAsyncCallbackThread_Mutex};
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07001893 enum AsyncError { ASYNC_ERROR_NONE, ASYNC_ERROR_SOFT, ASYNC_ERROR_HARD };
1894 AsyncError mAsyncError;
Andy Hungc5007f82023-08-29 14:26:09 -07001895
Andy Hungab65b182023-09-06 19:41:47 -07001896 audio_utils::mutex& mutex() const RETURN_CAPABILITY(audio_utils::AsyncCallbackThread_Mutex) {
1897 return mMutex;
1898 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001899};
1900
Andy Hung87c693c2023-07-06 20:56:16 -07001901class DuplicatingThread : public MixerThread, public IAfDuplicatingThread {
Eric Laurent81784c32012-11-19 14:55:58 -08001902public:
Andy Hung583043b2023-07-17 17:05:00 -07001903 DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
1904 IAfPlaybackThread* mainThread,
Eric Laurent72e3f392015-05-20 14:43:50 -07001905 audio_io_handle_t id, bool systemReady);
Andy Hung87c693c2023-07-06 20:56:16 -07001906 ~DuplicatingThread() override;
1907
1908 sp<IAfDuplicatingThread> asIAfDuplicatingThread() final {
1909 return sp<IAfDuplicatingThread>::fromExisting(this);
1910 }
Eric Laurent81784c32012-11-19 14:55:58 -08001911
1912 // Thread virtuals
Andy Hungab65b182023-09-06 19:41:47 -07001913 void addOutputTrack(IAfPlaybackThread* thread) final EXCLUDES_ThreadBase_Mutex;
1914 void removeOutputTrack(IAfPlaybackThread* thread) final EXCLUDES_ThreadBase_Mutex;
Andy Hung87c693c2023-07-06 20:56:16 -07001915 uint32_t waitTimeMs() const final { return mWaitTimeMs; }
Kevin Rocard069c2712018-03-29 19:09:14 -07001916
Kevin Rocardc86a7f72018-04-03 09:00:09 -07001917 void sendMetadataToBackend_l(
Andy Hungab65b182023-09-06 19:41:47 -07001918 const StreamOutHalInterface::SourceMetadata& metadata) final REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001919protected:
1920 virtual uint32_t activeSleepTimeUs() const;
Andy Hungab65b182023-09-06 19:41:47 -07001921 void dumpInternals_l(int fd, const Vector<String16>& args) final REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001922
1923private:
Andy Hung8d672e02023-09-15 18:19:28 -07001924 bool outputsReady() REQUIRES(ThreadBase_ThreadLoop);
Eric Laurent81784c32012-11-19 14:55:58 -08001925protected:
1926 // threadLoop snippets
Andy Hung8d672e02023-09-15 18:19:28 -07001927 void threadLoop_mix() final REQUIRES(ThreadBase_ThreadLoop);
1928 void threadLoop_sleepTime() final REQUIRES(ThreadBase_ThreadLoop);
1929 ssize_t threadLoop_write() final REQUIRES(ThreadBase_ThreadLoop);
1930 void threadLoop_standby() final REQUIRES(ThreadBase_ThreadLoop);
Andy Hung8a5abfd2023-12-07 19:35:12 -08001931 void threadLoop_exit() final REQUIRES(ThreadBase_ThreadLoop);
Andy Hung8d672e02023-09-15 18:19:28 -07001932 void cacheParameters_l() final REQUIRES(mutex(), ThreadBase_ThreadLoop);
Eric Laurent81784c32012-11-19 14:55:58 -08001933
1934private:
1935 // called from threadLoop, addOutputTrack, removeOutputTrack
Andy Hungab65b182023-09-06 19:41:47 -07001936 void updateWaitTime_l() REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001937protected:
Andy Hung8d672e02023-09-15 18:19:28 -07001938 void saveOutputTracks() final REQUIRES(mutex(), ThreadBase_ThreadLoop);
1939 void clearOutputTracks() final REQUIRES(mutex(), ThreadBase_ThreadLoop);
Eric Laurent81784c32012-11-19 14:55:58 -08001940private:
1941
1942 uint32_t mWaitTimeMs;
Andy Hung8d672e02023-09-15 18:19:28 -07001943 // NO_THREAD_SAFETY_ANALYSIS GUARDED_BY(ThreadBase_ThreadLoop)
1944 SortedVector <sp<IAfOutputTrack>> outputTracks;
1945 SortedVector <sp<IAfOutputTrack>> mOutputTracks GUARDED_BY(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001946public:
1947 virtual bool hasFastMixer() const { return false; }
Andy Hung1c86ebe2018-05-29 20:29:08 -07001948 status_t threadloop_getHalTimestamp_l(
Andy Hungab65b182023-09-06 19:41:47 -07001949 ExtendedTimestamp *timestamp) const override REQUIRES(mutex()) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07001950 if (mOutputTracks.size() > 0) {
1951 // forward the first OutputTrack's kernel information for timestamp.
1952 const ExtendedTimestamp trackTimestamp =
1953 mOutputTracks[0]->getClientProxyTimestamp();
1954 if (trackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] > 0) {
1955 timestamp->mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
1956 trackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
1957 timestamp->mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
1958 trackTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
1959 return OK; // discard server timestamp - that's ignored.
1960 }
1961 }
1962 return INVALID_OPERATION;
1963 }
Eric Laurent81784c32012-11-19 14:55:58 -08001964};
1965
Eric Laurentb0463942022-12-20 16:31:10 +01001966class SpatializerThread : public MixerThread {
Eric Laurentb3f315a2021-07-13 15:09:05 +02001967public:
Andy Hung583043b2023-07-17 17:05:00 -07001968 SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02001969 AudioStreamOut* output,
1970 audio_io_handle_t id,
1971 bool systemReady,
1972 audio_config_base_t *mixerConfig);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001973
Andy Hung440901d2023-06-29 21:19:25 -07001974 bool hasFastMixer() const final { return false; }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001975
Andy Hungab65b182023-09-06 19:41:47 -07001976 status_t setRequestedLatencyMode(audio_latency_mode_t mode) final EXCLUDES_ThreadBase_Mutex;
Eric Laurent68a40a82022-05-03 18:15:04 +02001977
Eric Laurentb3f315a2021-07-13 15:09:05 +02001978protected:
Andy Hung8d672e02023-09-15 18:19:28 -07001979 void checkOutputStageEffects() final
1980 REQUIRES(ThreadBase_ThreadLoop) EXCLUDES_ThreadBase_Mutex;
Andy Hungab65b182023-09-06 19:41:47 -07001981 void setHalLatencyMode_l() final REQUIRES(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001982
Andy Hunge2514462023-12-06 14:59:24 -08001983 void threadLoop_exit() final REQUIRES(ThreadBase_ThreadLoop);
1984
Eric Laurentb3f315a2021-07-13 15:09:05 +02001985private:
Eric Laurent68a40a82022-05-03 18:15:04 +02001986 // Do not request a specific mode by default
1987 audio_latency_mode_t mRequestedLatencyMode = AUDIO_LATENCY_MODE_FREE;
1988
Andy Hung116bc262023-06-20 18:56:17 -07001989 sp<IAfEffectHandle> mFinalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02001990};
1991
Eric Laurent81784c32012-11-19 14:55:58 -08001992// record thread
Andy Hung87c693c2023-07-06 20:56:16 -07001993class RecordThread : public IAfRecordThread, public ThreadBase
Eric Laurent81784c32012-11-19 14:55:58 -08001994{
Andy Hung8d31fd22023-06-26 19:20:57 -07001995 friend class ResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08001996public:
Andy Hung87c693c2023-07-06 20:56:16 -07001997 sp<IAfRecordThread> asIAfRecordThread() final {
1998 return sp<IAfRecordThread>::fromExisting(this);
1999 }
Eric Laurent81784c32012-11-19 14:55:58 -08002000
Andy Hung583043b2023-07-17 17:05:00 -07002001 RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002002 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08002003 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002004 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08002005 );
Andy Hung440901d2023-06-29 21:19:25 -07002006 ~RecordThread() override;
Eric Laurent81784c32012-11-19 14:55:58 -08002007
2008 // no addTrack_l ?
Andy Hungab65b182023-09-06 19:41:47 -07002009 void destroyTrack_l(const sp<IAfRecordTrack>& track) final REQUIRES(mutex());
2010 void removeTrack_l(const sp<IAfRecordTrack>& track) final REQUIRES(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002011
Eric Laurent81784c32012-11-19 14:55:58 -08002012 // Thread virtuals
Andy Hung8d672e02023-09-15 18:19:28 -07002013 bool threadLoop() final REQUIRES(ThreadBase_ThreadLoop) EXCLUDES_ThreadBase_Mutex;
Andy Hungab65b182023-09-06 19:41:47 -07002014 void preExit() final EXCLUDES_ThreadBase_Mutex;
Eric Laurent81784c32012-11-19 14:55:58 -08002015
2016 // RefBase
Andy Hungab65b182023-09-06 19:41:47 -07002017 void onFirstRef() final EXCLUDES_ThreadBase_Mutex;
Eric Laurent81784c32012-11-19 14:55:58 -08002018
Andy Hung440901d2023-06-29 21:19:25 -07002019 status_t initCheck() const final { return mInput == nullptr ? NO_INIT : NO_ERROR; }
Glenn Kastene198c362013-08-13 09:13:36 -07002020
Andy Hung440901d2023-06-29 21:19:25 -07002021 sp<MemoryDealer> readOnlyHeap() const final { return mReadOnlyHeap; }
Glenn Kastenb880f5e2014-05-07 08:43:45 -07002022
Andy Hung440901d2023-06-29 21:19:25 -07002023 sp<IMemory> pipeMemory() const final { return mPipeMemory; }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07002024
Andy Hung87c693c2023-07-06 20:56:16 -07002025 sp<IAfRecordTrack> createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002026 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002027 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002028 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002029 audio_format_t format,
2030 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002031 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08002032 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002033 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002034 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002035 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07002036 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08002037 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002038 status_t *status /*non-NULL*/,
Eric Laurentec376dc2021-04-08 20:41:22 +02002039 audio_port_handle_t portId,
Andy Hung972bec12023-08-31 16:13:39 -07002040 int32_t maxSharedAudioHistoryMs) final
Andy Hungab65b182023-09-06 19:41:47 -07002041 REQUIRES(audio_utils::AudioFlinger_Mutex) EXCLUDES_ThreadBase_Mutex;
Eric Laurent81784c32012-11-19 14:55:58 -08002042
Andy Hung8d31fd22023-06-26 19:20:57 -07002043 status_t start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08002044 AudioSystem::sync_event_t event,
Andy Hungab65b182023-09-06 19:41:47 -07002045 audio_session_t triggerSession) final EXCLUDES_ThreadBase_Mutex;
Eric Laurent81784c32012-11-19 14:55:58 -08002046
2047 // ask the thread to stop the specified track, and
2048 // return true if the caller should then do it's part of the stopping process
Andy Hungab65b182023-09-06 19:41:47 -07002049 bool stop(IAfRecordTrack* recordTrack) final EXCLUDES_ThreadBase_Mutex;
Andy Hung87c693c2023-07-06 20:56:16 -07002050 AudioStreamIn* getInput() const final { return mInput; }
2051 AudioStreamIn* clearInput() final;
Eric Laurent81784c32012-11-19 14:55:58 -08002052
Andy Hung99b1ba62023-07-14 11:00:08 -07002053 // TODO(b/291317898) Unify with IAfThreadBase
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002054 virtual sp<StreamHalInterface> stream() const;
Eric Laurent81784c32012-11-19 14:55:58 -08002055
Eric Laurent81784c32012-11-19 14:55:58 -08002056
Andy Hungab65b182023-09-06 19:41:47 -07002057 virtual bool checkForNewParameter_l(const String8& keyValuePair,
2058 status_t& status) REQUIRES(mutex());
Andy Hung8d672e02023-09-15 18:19:28 -07002059 virtual void cacheParameters_l() REQUIRES(mutex(), ThreadBase_ThreadLoop) {}
Andy Hungab65b182023-09-06 19:41:47 -07002060 virtual String8 getParameters(const String8& keys) EXCLUDES_ThreadBase_Mutex;
2061
2062 // Hold either the AudioFlinger::mutex or the ThreadBase::mutex
2063 void ioConfigChanged_l(audio_io_config_event_t event, pid_t pid = 0,
Andy Hung87c693c2023-07-06 20:56:16 -07002064 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final;
Eric Laurent1c333e22014-05-20 10:48:17 -07002065 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
Andy Hungab65b182023-09-06 19:41:47 -07002066 audio_patch_handle_t *handle) REQUIRES(mutex());
2067 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle) REQUIRES(mutex());
2068 void updateOutDevices(const DeviceDescriptorBaseVector& outDevices) override
2069 EXCLUDES_ThreadBase_Mutex;
2070 void resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs) override REQUIRES(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07002071
Andy Hungab65b182023-09-06 19:41:47 -07002072 void addPatchTrack(const sp<IAfPatchRecord>& record) final EXCLUDES_ThreadBase_Mutex;
2073 void deletePatchTrack(const sp<IAfPatchRecord>& record) final EXCLUDES_ThreadBase_Mutex;
Eric Laurent83b88082014-06-20 18:31:16 -07002074
Andy Hungab65b182023-09-06 19:41:47 -07002075 void readInputParameters_l() REQUIRES(mutex());
2076 uint32_t getInputFramesLost() const final EXCLUDES_ThreadBase_Mutex;
Eric Laurent81784c32012-11-19 14:55:58 -08002077
Andy Hungab65b182023-09-06 19:41:47 -07002078 virtual status_t addEffectChain_l(const sp<IAfEffectChain>& chain) REQUIRES(mutex());
2079 virtual size_t removeEffectChain_l(const sp<IAfEffectChain>& chain) REQUIRES(mutex());
2080 uint32_t hasAudioSession_l(audio_session_t sessionId) const override REQUIRES(mutex()) {
Andy Hungc3d62f92019-03-14 13:38:51 -07002081 return ThreadBase::hasAudioSession_l(sessionId, mTracks);
2082 }
Eric Laurent81784c32012-11-19 14:55:58 -08002083
2084 // Return the set of unique session IDs across all tracks.
2085 // The keys are the session IDs, and the associated values are meaningless.
2086 // FIXME replace by Set [and implement Bag/Multiset for other uses].
Glenn Kastend848eb42016-03-08 13:42:11 -08002087 KeyedVector<audio_session_t, bool> sessionIds() const;
Eric Laurent81784c32012-11-19 14:55:58 -08002088
Andy Hungab65b182023-09-06 19:41:47 -07002089 status_t setSyncEvent(const sp<audioflinger::SyncEvent>& event) override
2090 EXCLUDES_ThreadBase_Mutex;
Andy Hung068e08e2023-05-15 19:02:55 -07002091 bool isValidSyncEvent(const sp<audioflinger::SyncEvent>& event) const override;
Eric Laurent81784c32012-11-19 14:55:58 -08002092
Andy Hung068e08e2023-05-15 19:02:55 -07002093 static void syncStartEventCallback(const wp<audioflinger::SyncEvent>& event);
Eric Laurent81784c32012-11-19 14:55:58 -08002094
Glenn Kasten9b58f632013-07-16 11:37:48 -07002095 virtual size_t frameCount() const { return mFrameCount; }
Andy Hung87c693c2023-07-06 20:56:16 -07002096 bool hasFastCapture() const final { return mFastCapture != 0; }
Mikhail Naganovdc769682018-05-04 15:34:08 -07002097 virtual void toAudioPortConfig(struct audio_port_config *config);
Glenn Kasten9b58f632013-07-16 11:37:48 -07002098
Andy Hungab65b182023-09-06 19:41:47 -07002099 virtual status_t checkEffectCompatibility_l(const effect_descriptor_t *desc,
2100 audio_session_t sessionId) REQUIRES(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07002101
Andy Hungab65b182023-09-06 19:41:47 -07002102 virtual void acquireWakeLock_l() REQUIRES(mutex()) {
Andy Hungdae27702016-10-31 14:01:16 -07002103 ThreadBase::acquireWakeLock_l();
Andy Hungab65b182023-09-06 19:41:47 -07002104 mActiveTracks.updatePowerState_l(this, true /* force */);
Andy Hungdae27702016-10-31 14:01:16 -07002105 }
2106
Andy Hungab65b182023-09-06 19:41:47 -07002107 void checkBtNrec() final EXCLUDES_ThreadBase_Mutex;
Eric Laurentd8365c52017-07-16 15:27:05 -07002108
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002109 // Sets the UID records silence
Andy Hungab65b182023-09-06 19:41:47 -07002110 void setRecordSilenced(audio_port_handle_t portId, bool silenced) final
2111 EXCLUDES_ThreadBase_Mutex;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002112
Andy Hung87c693c2023-07-06 20:56:16 -07002113 status_t getActiveMicrophones(
Andy Hungab65b182023-09-06 19:41:47 -07002114 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const final
2115 EXCLUDES_ThreadBase_Mutex;
2116 status_t setPreferredMicrophoneDirection(audio_microphone_direction_t direction) final
2117 EXCLUDES_ThreadBase_Mutex;
2118 status_t setPreferredMicrophoneFieldDimension(float zoom) final EXCLUDES_ThreadBase_Mutex;
Paul McLean03a6e6a2018-12-04 10:54:13 -07002119
Andy Hungab65b182023-09-06 19:41:47 -07002120 MetadataUpdate updateMetadata_l() override REQUIRES(mutex());
Kevin Rocard069c2712018-03-29 19:09:14 -07002121
Andy Hung87c693c2023-07-06 20:56:16 -07002122 bool fastTrackAvailable() const final { return mFastTrackAvail; }
2123 void setFastTrackAvailable(bool available) final { mFastTrackAvail = available; }
jiabin01c8f562018-07-19 17:47:28 -07002124
Andy Hungab65b182023-09-06 19:41:47 -07002125 bool isTimestampCorrectionEnabled_l() const override REQUIRES(mutex()) {
Andy Hungc8fddf32018-08-08 18:32:37 -07002126 // checks popcount for exactly one device.
Atneya Nair497fff12022-01-18 16:23:04 -05002127 // Is currently disabled. Before enabling,
2128 // verify compressed record timestamps.
jiabinc52b1ff2019-10-31 17:20:42 -07002129 return audio_is_input_device(mTimestampCorrectedDevice)
Andy Hungab65b182023-09-06 19:41:47 -07002130 && inDeviceType_l() == mTimestampCorrectedDevice;
Andy Hungc8fddf32018-08-08 18:32:37 -07002131 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002132
Andy Hung87c693c2023-07-06 20:56:16 -07002133 status_t shareAudioHistory(const std::string& sharedAudioPackageName,
Eric Laurentec376dc2021-04-08 20:41:22 +02002134 audio_session_t sharedSessionId = AUDIO_SESSION_NONE,
Andy Hungab65b182023-09-06 19:41:47 -07002135 int64_t sharedAudioStartMs = -1) final EXCLUDES_ThreadBase_Mutex;
Eric Laurentec376dc2021-04-08 20:41:22 +02002136 status_t shareAudioHistory_l(const std::string& sharedAudioPackageName,
2137 audio_session_t sharedSessionId = AUDIO_SESSION_NONE,
Andy Hungab65b182023-09-06 19:41:47 -07002138 int64_t sharedAudioStartMs = -1) REQUIRES(mutex());
2139 void resetAudioHistory_l() final REQUIRES(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02002140
Andy Hung440901d2023-06-29 21:19:25 -07002141 bool isStreamInitialized() const final {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002142 return !(mInput == nullptr || mInput->stream == nullptr);
2143 }
2144
Atneya Nairaa3afcb2024-10-08 16:36:19 -07002145 std::string getLocalLogHeader() const override;
2146
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002147protected:
Andy Hungab65b182023-09-06 19:41:47 -07002148 void dumpInternals_l(int fd, const Vector<String16>& args) override REQUIRES(mutex());
2149 void dumpTracks_l(int fd, const Vector<String16>& args) override REQUIRES(mutex());
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002150
Eric Laurent81784c32012-11-19 14:55:58 -08002151private:
Eric Laurent81784c32012-11-19 14:55:58 -08002152 // Enter standby if not already in standby, and set mStandby flag
Glenn Kasten93e471f2013-08-19 08:40:07 -07002153 void standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08002154
2155 // Call the HAL standby method unconditionally, and don't change mStandby flag
Glenn Kastene198c362013-08-13 09:13:36 -07002156 void inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08002157
Andy Hungab65b182023-09-06 19:41:47 -07002158 void checkBtNrec_l() REQUIRES(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07002159
Andy Hungab65b182023-09-06 19:41:47 -07002160 int32_t getOldestFront_l() REQUIRES(mutex());
2161 void updateFronts_l(int32_t offset) REQUIRES(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02002162
Eric Laurent81784c32012-11-19 14:55:58 -08002163 AudioStreamIn *mInput;
Mikhail Naganov2534b382019-09-25 13:05:02 -07002164 Source *mSource;
Andy Hung8d31fd22023-06-26 19:20:57 -07002165 SortedVector <sp<IAfRecordTrack>> mTracks;
Glenn Kasten2b806402013-11-20 16:37:38 -08002166 // mActiveTracks has dual roles: it indicates the current active track(s), and
Andy Hungc5007f82023-08-29 14:26:09 -07002167 // is used together with mStartStopCV to indicate start()/stop() progress
Andy Hung8d31fd22023-06-26 19:20:57 -07002168 ActiveTracks<IAfRecordTrack> mActiveTracks;
Andy Hungdae27702016-10-31 14:01:16 -07002169
Andy Hungc5007f82023-08-29 14:26:09 -07002170 audio_utils::condition_variable mStartStopCV;
Glenn Kasten9b58f632013-07-16 11:37:48 -07002171
Glenn Kasten85948432013-08-19 12:09:05 -07002172 // resampler converts input at HAL Hz to output at AudioRecord client Hz
Glenn Kasten1b291842016-07-18 14:55:21 -07002173 void *mRsmpInBuffer; // size = mRsmpInFramesOA
Glenn Kasten85948432013-08-19 12:09:05 -07002174 size_t mRsmpInFrames; // size of resampler input in frames
2175 size_t mRsmpInFramesP2;// size rounded up to a power-of-2
Glenn Kasten1b291842016-07-18 14:55:21 -07002176 size_t mRsmpInFramesOA;// mRsmpInFramesP2 + over-allocation
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08002177
2178 // rolling index that is never cleared
Glenn Kasten85948432013-08-19 12:09:05 -07002179 int32_t mRsmpInRear; // last filled frame + 1
Glenn Kasten85948432013-08-19 12:09:05 -07002180
Eric Laurent81784c32012-11-19 14:55:58 -08002181 // For dumpsys
Glenn Kastenb880f5e2014-05-07 08:43:45 -07002182 const sp<MemoryDealer> mReadOnlyHeap;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07002183
2184 // one-time initialization, no locks required
Glenn Kastenb187de12014-12-30 08:18:15 -08002185 sp<FastCapture> mFastCapture; // non-0 if there is also
2186 // a fast capture
Eric Laurent72e3f392015-05-20 14:43:50 -07002187
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07002188 // FIXME audio watchdog thread
2189
2190 // contents are not guaranteed to be consistent, no locks required
2191 FastCaptureDumpState mFastCaptureDumpState;
2192#ifdef STATE_QUEUE_DUMP
2193 // FIXME StateQueue observer and mutator dump fields
2194#endif
2195 // FIXME audio watchdog dump
2196
2197 // accessible only within the threadLoop(), no locks required
2198 // mFastCapture->sq() // for mutating and pushing state
2199 int32_t mFastCaptureFutex; // for cold idle
2200
2201 // The HAL input source is treated as non-blocking,
2202 // but current implementation is blocking
2203 sp<NBAIO_Source> mInputSource;
2204 // The source for the normal capture thread to read from: mInputSource or mPipeSource
2205 sp<NBAIO_Source> mNormalSource;
2206 // If a fast capture is present, the non-blocking pipe sink written to by fast capture,
2207 // otherwise clear
2208 sp<NBAIO_Sink> mPipeSink;
2209 // If a fast capture is present, the non-blocking pipe source read by normal thread,
2210 // otherwise clear
2211 sp<NBAIO_Source> mPipeSource;
2212 // Depth of pipe from fast capture to normal thread and fast clients, always power of 2
2213 size_t mPipeFramesP2;
2214 // If a fast capture is present, the Pipe as IMemory, otherwise clear
2215 sp<IMemory> mPipeMemory;
2216
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002217 // TODO: add comment and adjust size as needed
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07002218 static const size_t kFastCaptureLogSize = 4 * 1024;
2219 sp<NBLog::Writer> mFastCaptureNBLogWriter;
2220
2221 bool mFastTrackAvail; // true if fast track available
Eric Laurentd8365c52017-07-16 15:27:05 -07002222 // common state to all record threads
2223 std::atomic_bool mBtNrecSuspended;
Andy Hung6427e442018-08-09 12:51:02 -07002224
2225 int64_t mFramesRead = 0; // continuous running counter.
jiabinc52b1ff2019-10-31 17:20:42 -07002226
2227 DeviceDescriptorBaseVector mOutDevices;
Eric Laurentec376dc2021-04-08 20:41:22 +02002228
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02002229 int32_t mMaxSharedAudioHistoryMs = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02002230 std::string mSharedAudioPackageName = {};
Eric Laurent2407ce32021-04-26 14:56:03 +02002231 int32_t mSharedAudioStartFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02002232 audio_session_t mSharedAudioSessionId = AUDIO_SESSION_NONE;
Eric Laurent81784c32012-11-19 14:55:58 -08002233};
Eric Laurent6acd1d42017-01-04 14:23:29 -08002234
Andy Hung7aa7d102023-07-07 15:58:48 -07002235class MmapThread : public ThreadBase, public virtual IAfMmapThread
Eric Laurent6acd1d42017-01-04 14:23:29 -08002236{
2237 public:
Andy Hung583043b2023-07-17 17:05:00 -07002238 MmapThread(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -07002239 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady,
Andy Hungcf10d742020-04-28 15:38:24 -07002240 bool isOut);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002241
Andy Hung7aa7d102023-07-07 15:58:48 -07002242 void configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08002243 audio_stream_type_t streamType,
2244 audio_session_t sessionId,
2245 const sp<MmapStreamCallback>& callback,
Robert Wuaeb1d002024-10-30 23:19:44 +00002246 const DeviceIdVector& deviceIds,
Andy Hung8d672e02023-09-15 18:19:28 -07002247 audio_port_handle_t portId) override EXCLUDES_ThreadBase_Mutex {
2248 audio_utils::lock_guard l(mutex());
Robert Wuaeb1d002024-10-30 23:19:44 +00002249 configure_l(attr, streamType, sessionId, callback, deviceIds, portId);
Andy Hung8d672e02023-09-15 18:19:28 -07002250 }
2251
2252 void configure_l(const audio_attributes_t* attr,
2253 audio_stream_type_t streamType,
2254 audio_session_t sessionId,
2255 const sp<MmapStreamCallback>& callback,
Robert Wuaeb1d002024-10-30 23:19:44 +00002256 const DeviceIdVector& deviceIds,
Andy Hung8d672e02023-09-15 18:19:28 -07002257 audio_port_handle_t portId) REQUIRES(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002258
Andy Hungab65b182023-09-06 19:41:47 -07002259 void disconnect() final EXCLUDES_ThreadBase_Mutex;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002260
Andy Hung440901d2023-06-29 21:19:25 -07002261 // MmapStreamInterface for adapter.
Andy Hung3f49ebb2023-09-19 14:48:41 -07002262 status_t createMmapBuffer(int32_t minSizeFrames, struct audio_mmap_buffer_info* info) final
2263 EXCLUDES_ThreadBase_Mutex;
2264 status_t getMmapPosition(struct audio_mmap_position* position) const override
2265 EXCLUDES_ThreadBase_Mutex;
Andy Hung7aa7d102023-07-07 15:58:48 -07002266 status_t start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07002267 const audio_attributes_t *attr,
Andy Hungab65b182023-09-06 19:41:47 -07002268 audio_port_handle_t* handle) final EXCLUDES_ThreadBase_Mutex;
2269 status_t stop(audio_port_handle_t handle) final EXCLUDES_ThreadBase_Mutex;
2270 status_t standby() final EXCLUDES_ThreadBase_Mutex;
Andy Hung3f49ebb2023-09-19 14:48:41 -07002271 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) const
2272 EXCLUDES_ThreadBase_Mutex = 0;
2273 status_t reportData(const void* buffer, size_t frameCount) override EXCLUDES_ThreadBase_Mutex;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002274
2275 // RefBase
Andy Hung440901d2023-06-29 21:19:25 -07002276 void onFirstRef() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002277
2278 // Thread virtuals
Andy Hung8d672e02023-09-15 18:19:28 -07002279 bool threadLoop() final REQUIRES(ThreadBase_ThreadLoop) EXCLUDES_ThreadBase_Mutex;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002280
Andy Hung440901d2023-06-29 21:19:25 -07002281 // Not in ThreadBase
Andy Hung8d672e02023-09-15 18:19:28 -07002282 virtual void threadLoop_exit() final REQUIRES(ThreadBase_ThreadLoop);
2283 virtual void threadLoop_standby() final REQUIRES(ThreadBase_ThreadLoop);
Andy Hungab65b182023-09-06 19:41:47 -07002284 virtual bool shouldStandby_l() final REQUIRES(mutex()){ return false; }
Andy Hungc5007f82023-08-29 14:26:09 -07002285 virtual status_t exitStandby_l() REQUIRES(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002286
Andy Hung440901d2023-06-29 21:19:25 -07002287 status_t initCheck() const final { return mHalStream == nullptr ? NO_INIT : NO_ERROR; }
2288 size_t frameCount() const final { return mFrameCount; }
Andy Hungab65b182023-09-06 19:41:47 -07002289 bool checkForNewParameter_l(const String8& keyValuePair, status_t& status)
2290 final REQUIRES(mutex());
2291 String8 getParameters(const String8& keys) final EXCLUDES_ThreadBase_Mutex;
2292 void ioConfigChanged_l(audio_io_config_event_t event, pid_t pid = 0,
2293 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final
2294 /* holds either AF::mutex or TB::mutex */;
2295 void readHalParameters_l() REQUIRES(mutex());
Andy Hung8d672e02023-09-15 18:19:28 -07002296 void cacheParameters_l() final REQUIRES(mutex(), ThreadBase_ThreadLoop) {}
Andy Hung440901d2023-06-29 21:19:25 -07002297 status_t createAudioPatch_l(
Andy Hungab65b182023-09-06 19:41:47 -07002298 const struct audio_patch* patch, audio_patch_handle_t* handle) final
2299 REQUIRES(mutex());
2300 status_t releaseAudioPatch_l(const audio_patch_handle_t handle) final
2301 REQUIRES(mutex());
Andy Hung3f49ebb2023-09-19 14:48:41 -07002302 // NO_THREAD_SAFETY_ANALYSIS
Andy Hung440901d2023-06-29 21:19:25 -07002303 void toAudioPortConfig(struct audio_port_config* config) override;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002304
Andy Hung440901d2023-06-29 21:19:25 -07002305 sp<StreamHalInterface> stream() const final { return mHalStream; }
Andy Hungab65b182023-09-06 19:41:47 -07002306 status_t addEffectChain_l(const sp<IAfEffectChain>& chain) final REQUIRES(mutex());
2307 size_t removeEffectChain_l(const sp<IAfEffectChain>& chain) final REQUIRES(mutex());
Andy Hung440901d2023-06-29 21:19:25 -07002308 status_t checkEffectCompatibility_l(
Andy Hungab65b182023-09-06 19:41:47 -07002309 const effect_descriptor_t *desc, audio_session_t sessionId) final REQUIRES(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002310
Andy Hungab65b182023-09-06 19:41:47 -07002311 uint32_t hasAudioSession_l(audio_session_t sessionId) const override REQUIRES(mutex()) {
Andy Hungc3d62f92019-03-14 13:38:51 -07002312 // Note: using mActiveTracks as no mTracks here.
2313 return ThreadBase::hasAudioSession_l(sessionId, mActiveTracks);
2314 }
Andy Hung440901d2023-06-29 21:19:25 -07002315 status_t setSyncEvent(const sp<audioflinger::SyncEvent>& event) final;
2316 bool isValidSyncEvent(const sp<audioflinger::SyncEvent>& event) const final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002317
Andy Hungab65b182023-09-06 19:41:47 -07002318 virtual void checkSilentMode_l() REQUIRES(mutex()) {} // cannot be const (RecordThread)
2319 virtual void processVolume_l() REQUIRES(mutex()) {}
Andy Hung8d672e02023-09-15 18:19:28 -07002320 void checkInvalidTracks_l() REQUIRES(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002321
Andy Hung440901d2023-06-29 21:19:25 -07002322 // Not in ThreadBase
Andy Hung3f49ebb2023-09-19 14:48:41 -07002323 virtual audio_stream_type_t streamType_l() const REQUIRES(mutex()) {
2324 return AUDIO_STREAM_DEFAULT;
2325 }
Andy Hungab65b182023-09-06 19:41:47 -07002326 virtual void invalidateTracks(audio_stream_type_t /* streamType */)
2327 EXCLUDES_ThreadBase_Mutex {}
2328 void invalidateTracks(std::set<audio_port_handle_t>& /* portIds */) override
2329 EXCLUDES_ThreadBase_Mutex {}
Eric Laurent6acd1d42017-01-04 14:23:29 -08002330
Eric Laurent331679c2018-04-16 17:03:16 -07002331 // Sets the UID records silence
Andy Hung7aa7d102023-07-07 15:58:48 -07002332 void setRecordSilenced(
Andy Hungab65b182023-09-06 19:41:47 -07002333 audio_port_handle_t /* portId */, bool /* silenced */) override
2334 EXCLUDES_ThreadBase_Mutex {}
Eric Laurent331679c2018-04-16 17:03:16 -07002335
Andy Hung440901d2023-06-29 21:19:25 -07002336 bool isStreamInitialized() const override { return false; }
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002337
Atneya Nairaa3afcb2024-10-08 16:36:19 -07002338 std::string getLocalLogHeader() const override;
2339
Andy Hungab65b182023-09-06 19:41:47 -07002340 void setClientSilencedState_l(audio_port_handle_t portId, bool silenced) REQUIRES(mutex()) {
jiabin09609032022-06-15 19:26:01 +00002341 mClientSilencedStates[portId] = silenced;
2342 }
2343
Andy Hungab65b182023-09-06 19:41:47 -07002344 size_t eraseClientSilencedState_l(audio_port_handle_t portId) REQUIRES(mutex()) {
jiabin09609032022-06-15 19:26:01 +00002345 return mClientSilencedStates.erase(portId);
2346 }
2347
Andy Hungab65b182023-09-06 19:41:47 -07002348 bool isClientSilenced_l(audio_port_handle_t portId) const REQUIRES(mutex()) {
jiabin09609032022-06-15 19:26:01 +00002349 const auto it = mClientSilencedStates.find(portId);
2350 return it != mClientSilencedStates.end() ? it->second : false;
2351 }
2352
Andy Hungab65b182023-09-06 19:41:47 -07002353 void setClientSilencedIfExists_l(audio_port_handle_t portId, bool silenced)
2354 REQUIRES(mutex()) {
jiabin09609032022-06-15 19:26:01 +00002355 const auto it = mClientSilencedStates.find(portId);
2356 if (it != mClientSilencedStates.end()) {
2357 it->second = silenced;
2358 }
2359 }
2360
Eric Laurent6acd1d42017-01-04 14:23:29 -08002361 protected:
Andy Hungab65b182023-09-06 19:41:47 -07002362 void dumpInternals_l(int fd, const Vector<String16>& args) override REQUIRES(mutex());
2363 void dumpTracks_l(int fd, const Vector<String16>& args) final REQUIRES(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002364
jiabinc52b1ff2019-10-31 17:20:42 -07002365 /**
Robert Wuaeb1d002024-10-30 23:19:44 +00002366 * @brief mDeviceIds current device port unique identifiers
jiabinc52b1ff2019-10-31 17:20:42 -07002367 */
Robert Wuaeb1d002024-10-30 23:19:44 +00002368 DeviceIdVector mDeviceIds GUARDED_BY(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -07002369
Andy Hung3f49ebb2023-09-19 14:48:41 -07002370 audio_attributes_t mAttr GUARDED_BY(mutex());
2371 audio_session_t mSessionId GUARDED_BY(mutex());
2372 audio_port_handle_t mPortId GUARDED_BY(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002373
Andy Hung3f49ebb2023-09-19 14:48:41 -07002374 wp<MmapStreamCallback> mCallback GUARDED_BY(mutex());
2375 sp<StreamHalInterface> mHalStream; // NO_THREAD_SAFETY_ANALYSIS
2376 sp<DeviceHalInterface> mHalDevice GUARDED_BY(mutex());
2377 AudioHwDevice* const mAudioHwDev GUARDED_BY(mutex());
2378 ActiveTracks<IAfMmapTrack> mActiveTracks GUARDED_BY(mutex());
2379 float mHalVolFloat GUARDED_BY(mutex());
2380 std::map<audio_port_handle_t, bool> mClientSilencedStates GUARDED_BY(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -07002381
Andy Hung3f49ebb2023-09-19 14:48:41 -07002382 int32_t mNoCallbackWarningCount GUARDED_BY(mutex());
2383 static constexpr int32_t kMaxNoCallbackWarnings = 5;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002384};
2385
Andy Hung7aa7d102023-07-07 15:58:48 -07002386class MmapPlaybackThread : public MmapThread, public IAfMmapPlaybackThread,
2387 public virtual VolumeInterface {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002388public:
Andy Hung583043b2023-07-17 17:05:00 -07002389 MmapPlaybackThread(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07002390 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002391
Andy Hung7aa7d102023-07-07 15:58:48 -07002392 sp<IAfMmapPlaybackThread> asIAfMmapPlaybackThread() final {
2393 return sp<IAfMmapPlaybackThread>::fromExisting(this);
2394 }
2395
Andy Hung440901d2023-06-29 21:19:25 -07002396 void configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08002397 audio_stream_type_t streamType,
2398 audio_session_t sessionId,
2399 const sp<MmapStreamCallback>& callback,
Robert Wuaeb1d002024-10-30 23:19:44 +00002400 const DeviceIdVector& deviceIds,
Andy Hung8d672e02023-09-15 18:19:28 -07002401 audio_port_handle_t portId) final EXCLUDES_ThreadBase_Mutex;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002402
Andy Hungab65b182023-09-06 19:41:47 -07002403 AudioStreamOut* clearOutput() final EXCLUDES_ThreadBase_Mutex;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002404
2405 // VolumeInterface
Andy Hung440901d2023-06-29 21:19:25 -07002406 void setMasterVolume(float value) final;
Andy Hungab65b182023-09-06 19:41:47 -07002407 // Needs implementation?
2408 void setMasterBalance(float /* value */) final EXCLUDES_ThreadBase_Mutex {}
Andy Hung8d672e02023-09-15 18:19:28 -07002409 void setMasterMute(bool muted) final EXCLUDES_ThreadBase_Mutex;
Vlad Popa1e865e62024-08-15 19:11:42 -07002410
2411 void setStreamVolume(audio_stream_type_t stream, float value, bool muted) final
2412 EXCLUDES_ThreadBase_Mutex;
Andy Hungab65b182023-09-06 19:41:47 -07002413 void setStreamMute(audio_stream_type_t stream, bool muted) final EXCLUDES_ThreadBase_Mutex;
2414 float streamVolume(audio_stream_type_t stream) const final EXCLUDES_ThreadBase_Mutex;
Vlad Popa1e865e62024-08-15 19:11:42 -07002415 status_t setPortsVolume(const std::vector<audio_port_handle_t>& portIds, float volume,
2416 bool muted) final EXCLUDES_ThreadBase_Mutex;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002417
Andy Hung8d672e02023-09-15 18:19:28 -07002418 void setMasterMute_l(bool muted) REQUIRES(mutex()) { mMasterMute = muted; }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002419
Andy Hungab65b182023-09-06 19:41:47 -07002420 void invalidateTracks(audio_stream_type_t streamType) final EXCLUDES_ThreadBase_Mutex;
2421 void invalidateTracks(std::set<audio_port_handle_t>& portIds) final EXCLUDES_ThreadBase_Mutex;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002422
Andy Hung3f49ebb2023-09-19 14:48:41 -07002423 audio_stream_type_t streamType_l() const final REQUIRES(mutex()) {
Andy Hung8d672e02023-09-15 18:19:28 -07002424 return mStreamType;
2425 }
Andy Hungab65b182023-09-06 19:41:47 -07002426 void checkSilentMode_l() final REQUIRES(mutex());
2427 void processVolume_l() final REQUIRES(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002428
Andy Hungab65b182023-09-06 19:41:47 -07002429 MetadataUpdate updateMetadata_l() final REQUIRES(mutex());
Kevin Rocard069c2712018-03-29 19:09:14 -07002430
Andy Hung440901d2023-06-29 21:19:25 -07002431 void toAudioPortConfig(struct audio_port_config* config) final;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07002432
Andy Hung440901d2023-06-29 21:19:25 -07002433 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) const final;
jiabinb7d8c5a2020-08-26 17:24:52 -07002434
Andy Hung440901d2023-06-29 21:19:25 -07002435 bool isStreamInitialized() const final {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002436 return !(mOutput == nullptr || mOutput->stream == nullptr);
2437 }
2438
Andy Hung440901d2023-06-29 21:19:25 -07002439 status_t reportData(const void* buffer, size_t frameCount) final;
jiabinfc791ee2023-02-15 19:43:40 +00002440
Andy Hung972bec12023-08-31 16:13:39 -07002441 void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) final
2442 REQUIRES(audio_utils::AudioFlinger_Mutex);
2443 void stopMelComputation_l() final
2444 REQUIRES(audio_utils::AudioFlinger_Mutex);
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002445
Eric Laurent6acd1d42017-01-04 14:23:29 -08002446protected:
Andy Hungab65b182023-09-06 19:41:47 -07002447 void dumpInternals_l(int fd, const Vector<String16>& args) final REQUIRES(mutex());
Andy Hung8d672e02023-09-15 18:19:28 -07002448 float streamVolume_l() const REQUIRES(mutex()) {
Eric Laurent1f9b5e62023-07-03 18:14:07 +02002449 return mStreamTypes[mStreamType].volume;
2450 }
Andy Hung8d672e02023-09-15 18:19:28 -07002451 bool streamMuted_l() const REQUIRES(mutex()) {
Eric Laurent1f9b5e62023-07-03 18:14:07 +02002452 return mStreamTypes[mStreamType].mute;
2453 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002454
Andy Hung8d672e02023-09-15 18:19:28 -07002455 stream_type_t mStreamTypes[AUDIO_STREAM_CNT] GUARDED_BY(mutex());
2456 audio_stream_type_t mStreamType GUARDED_BY(mutex());
2457 float mMasterVolume GUARDED_BY(mutex());
2458 bool mMasterMute GUARDED_BY(mutex());
2459 AudioStreamOut* mOutput; // NO_THREAD_SAFETY_ANALYSIS
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002460
Andy Hung8d672e02023-09-15 18:19:28 -07002461 mediautils::atomic_sp<audio_utils::MelProcessor> mMelProcessor; // locked internally
Eric Laurent6acd1d42017-01-04 14:23:29 -08002462};
2463
Andy Hung7aa7d102023-07-07 15:58:48 -07002464class MmapCaptureThread : public MmapThread, public IAfMmapCaptureThread
Eric Laurent6acd1d42017-01-04 14:23:29 -08002465{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002466public:
Andy Hung583043b2023-07-17 17:05:00 -07002467 MmapCaptureThread(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07002468 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002469
Andy Hung7aa7d102023-07-07 15:58:48 -07002470 sp<IAfMmapCaptureThread> asIAfMmapCaptureThread() final {
2471 return sp<IAfMmapCaptureThread>::fromExisting(this);
2472 }
2473
Andy Hungab65b182023-09-06 19:41:47 -07002474 AudioStreamIn* clearInput() final EXCLUDES_ThreadBase_Mutex;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002475
Andy Hungc5007f82023-08-29 14:26:09 -07002476 status_t exitStandby_l() REQUIRES(mutex()) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002477
Andy Hungab65b182023-09-06 19:41:47 -07002478 MetadataUpdate updateMetadata_l() final REQUIRES(mutex());
2479 void processVolume_l() final REQUIRES(mutex());
2480 void setRecordSilenced(audio_port_handle_t portId, bool silenced) final
2481 EXCLUDES_ThreadBase_Mutex;
Kevin Rocard069c2712018-03-29 19:09:14 -07002482
Andy Hung440901d2023-06-29 21:19:25 -07002483 void toAudioPortConfig(struct audio_port_config* config) final;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07002484
Andy Hung440901d2023-06-29 21:19:25 -07002485 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) const final;
jiabinb7d8c5a2020-08-26 17:24:52 -07002486
Andy Hung440901d2023-06-29 21:19:25 -07002487 bool isStreamInitialized() const final {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002488 return !(mInput == nullptr || mInput->stream == nullptr);
2489 }
2490
Eric Laurent6acd1d42017-01-04 14:23:29 -08002491protected:
2492
Andy Hung8d672e02023-09-15 18:19:28 -07002493 AudioStreamIn* mInput; // NO_THREAD_SAFETY_ANALYSIS
Eric Laurent6acd1d42017-01-04 14:23:29 -08002494};
jiabinc658e452022-10-21 20:52:21 +00002495
2496class BitPerfectThread : public MixerThread {
2497public:
Andy Hung583043b2023-07-17 17:05:00 -07002498 BitPerfectThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut *output,
jiabinc658e452022-10-21 20:52:21 +00002499 audio_io_handle_t id, bool systemReady);
2500
jiabin220eea12024-05-17 17:55:20 +00002501 void setTracksInternalMute(std::map<audio_port_handle_t, bool>* tracksInternalMuted)
2502 final EXCLUDES_ThreadBase_Mutex;
2503
jiabinc658e452022-10-21 20:52:21 +00002504protected:
Andy Hung8d672e02023-09-15 18:19:28 -07002505 mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove) final
2506 REQUIRES(mutex(), ThreadBase_ThreadLoop);
2507 void threadLoop_mix() final REQUIRES(ThreadBase_ThreadLoop);
jiabinc658e452022-10-21 20:52:21 +00002508
2509private:
jiabin220eea12024-05-17 17:55:20 +00002510 sp<IAfTrack> getTrackToStreamBitPerfectly_l() REQUIRES(mutex());
2511
Andy Hung8d672e02023-09-15 18:19:28 -07002512 // These variables are only accessed on the threadLoop; hence need no mutex.
2513 bool mIsBitPerfect GUARDED_BY(ThreadBase_ThreadLoop) = false;
2514 float mVolumeLeft GUARDED_BY(ThreadBase_ThreadLoop) = 0.f;
2515 float mVolumeRight GUARDED_BY(ThreadBase_ThreadLoop) = 0.f;
jiabinc658e452022-10-21 20:52:21 +00002516};
Andy Hunga5a7fc92023-06-23 19:27:19 -07002517
Andy Hungee58e4a2023-07-07 13:47:37 -07002518} // namespace android