blob: 5e1cd91e822172634275b0fc634c2557cf735b4d [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
Andy Hungee58e4a2023-07-07 13:47:37 -070018#pragma once
Eric Laurent81784c32012-11-19 14:55:58 -080019
Andy Hung25a80ac2023-07-19 12:47:35 -070020// ADD_BATTERY_DATA AUDIO_WATCHDOG FAST_THREAD_STATISTICS STATE_QUEUE_DUMP TEE_SINK
21#include "Configuration.h"
22#include "IAfThread.h"
23#include "IAfTrack.h"
24
25#include <android-base/macros.h> // DISALLOW_COPY_AND_ASSIGN
26#include <android/os/IPowerManager.h>
27#include <afutils/AudioWatchdog.h>
28#include <afutils/NBAIO_Tee.h>
29#include <audio_utils/Balance.h>
30#include <audio_utils/SimpleLog.h>
31#include <datapath/ThreadMetrics.h>
32#include <fastpath/FastCapture.h>
33#include <fastpath/FastMixer.h>
34#include <mediautils/Synchronization.h>
35#include <mediautils/ThreadSnapshot.h>
36#include <timing/MonotonicFrameCounter.h>
37#include <utils/Log.h>
38
Andy Hungee58e4a2023-07-07 13:47:37 -070039namespace android {
Andy Hung440901d2023-06-29 21:19:25 -070040
41class AsyncCallbackThread;
42
43class ThreadBase : public virtual IAfThreadBase, public Thread {
Eric Laurent81784c32012-11-19 14:55:58 -080044public:
Glenn Kasten97b7b752014-09-28 13:04:24 -070045 static const char *threadTypeToString(type_t type);
46
Andy Hung583043b2023-07-17 17:05:00 -070047 IAfThreadCallback* afThreadCallback() const final { return mAfThreadCallback.get(); }
Andy Hung87c693c2023-07-06 20:56:16 -070048
Andy Hung583043b2023-07-17 17:05:00 -070049 ThreadBase(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -070050 type_t type, bool systemReady, bool isOut);
Andy Hung440901d2023-06-29 21:19:25 -070051 ~ThreadBase() override;
Eric Laurent81784c32012-11-19 14:55:58 -080052
Andy Hung440901d2023-06-29 21:19:25 -070053 status_t readyToRun() final;
54 void clearPowerManager() final;
Eric Laurent81784c32012-11-19 14:55:58 -080055
56 // base for record and playback
57 enum {
58 CFG_EVENT_IO,
Eric Laurent10351942014-05-08 18:49:52 -070059 CFG_EVENT_PRIO,
60 CFG_EVENT_SET_PARAMETER,
Eric Laurent1c333e22014-05-20 10:48:17 -070061 CFG_EVENT_CREATE_AUDIO_PATCH,
62 CFG_EVENT_RELEASE_AUDIO_PATCH,
jiabinc52b1ff2019-10-31 17:20:42 -070063 CFG_EVENT_UPDATE_OUT_DEVICE,
Eric Laurentb3f315a2021-07-13 15:09:05 +020064 CFG_EVENT_RESIZE_BUFFER,
Eric Laurent68a40a82022-05-03 18:15:04 +020065 CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS,
66 CFG_EVENT_HAL_LATENCY_MODES_CHANGED,
Eric Laurent81784c32012-11-19 14:55:58 -080067 };
68
Eric Laurent10351942014-05-08 18:49:52 -070069 class ConfigEventData: public RefBase {
Eric Laurent81784c32012-11-19 14:55:58 -080070 public:
Eric Laurent10351942014-05-08 18:49:52 -070071 virtual ~ConfigEventData() {}
Eric Laurent81784c32012-11-19 14:55:58 -080072
73 virtual void dump(char *buffer, size_t size) = 0;
Eric Laurent10351942014-05-08 18:49:52 -070074 protected:
75 ConfigEventData() {}
Eric Laurent81784c32012-11-19 14:55:58 -080076 };
77
Eric Laurent10351942014-05-08 18:49:52 -070078 // Config event sequence by client if status needed (e.g binder thread calling setParameters()):
79 // 1. create SetParameterConfigEvent. This sets mWaitStatus in config event
Andy Hungc5007f82023-08-29 14:26:09 -070080 // 2. Lock mutex()
Eric Laurent10351942014-05-08 18:49:52 -070081 // 3. Call sendConfigEvent_l(): Append to mConfigEvents and mWaitWorkCV.signal
82 // 4. sendConfigEvent_l() reads status from event->mStatus;
83 // 5. sendConfigEvent_l() returns status
84 // 6. Unlock
85 //
86 // Parameter sequence by server: threadLoop calling processConfigEvents_l():
Andy Hungc5007f82023-08-29 14:26:09 -070087 // 1. Lock mutex()
Eric Laurent10351942014-05-08 18:49:52 -070088 // 2. If there is an entry in mConfigEvents proceed ...
89 // 3. Read first entry in mConfigEvents
90 // 4. Remove first entry from mConfigEvents
91 // 5. Process
92 // 6. Set event->mStatus
Andy Hungc5007f82023-08-29 14:26:09 -070093 // 7. event->mCondition.notify_one()
Eric Laurent10351942014-05-08 18:49:52 -070094 // 8. Unlock
Eric Laurent81784c32012-11-19 14:55:58 -080095
Eric Laurent10351942014-05-08 18:49:52 -070096 class ConfigEvent: public RefBase {
97 public:
Eric Laurentb3f315a2021-07-13 15:09:05 +020098 void dump(char *buffer, size_t size) {
99 snprintf(buffer, size, "Event type: %d\n", mType);
100 if (mData != nullptr) {
101 snprintf(buffer, size, "Data:\n");
102 mData->dump(buffer, size);
103 }
104 }
Eric Laurent10351942014-05-08 18:49:52 -0700105
Andy Hungc5007f82023-08-29 14:26:09 -0700106 audio_utils::mutex& mutex() const { return mMutex; }
Eric Laurent10351942014-05-08 18:49:52 -0700107 const int mType; // event type e.g. CFG_EVENT_IO
Andy Hungc5007f82023-08-29 14:26:09 -0700108 mutable audio_utils::mutex mMutex; // mutex associated with mCondition
109 audio_utils::condition_variable mCondition; // condition for status return
Eric Laurent10351942014-05-08 18:49:52 -0700110 status_t mStatus; // status communicated to sender
111 bool mWaitStatus; // true if sender is waiting for status
Eric Laurent72e3f392015-05-20 14:43:50 -0700112 bool mRequiresSystemReady; // true if must wait for system ready to enter event queue
Eric Laurent10351942014-05-08 18:49:52 -0700113 sp<ConfigEventData> mData; // event specific parameter data
114
115 protected:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700116 explicit ConfigEvent(int type, bool requiresSystemReady = false) :
Eric Laurent72e3f392015-05-20 14:43:50 -0700117 mType(type), mStatus(NO_ERROR), mWaitStatus(false),
118 mRequiresSystemReady(requiresSystemReady), mData(NULL) {}
Eric Laurent10351942014-05-08 18:49:52 -0700119 };
120
121 class IoConfigEventData : public ConfigEventData {
122 public:
Mikhail Naganov88536df2021-07-26 17:30:29 -0700123 IoConfigEventData(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700124 audio_port_handle_t portId) :
125 mEvent(event), mPid(pid), mPortId(portId) {}
Eric Laurent81784c32012-11-19 14:55:58 -0800126
127 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200128 snprintf(buffer, size, "- IO event: event %d\n", mEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800129 }
130
Mikhail Naganov88536df2021-07-26 17:30:29 -0700131 const audio_io_config_event_t mEvent;
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700132 const pid_t mPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -0700133 const audio_port_handle_t mPortId;
Eric Laurent81784c32012-11-19 14:55:58 -0800134 };
135
Eric Laurent10351942014-05-08 18:49:52 -0700136 class IoConfigEvent : public ConfigEvent {
Eric Laurent81784c32012-11-19 14:55:58 -0800137 public:
Mikhail Naganov88536df2021-07-26 17:30:29 -0700138 IoConfigEvent(audio_io_config_event_t event, pid_t pid, audio_port_handle_t portId) :
Eric Laurent10351942014-05-08 18:49:52 -0700139 ConfigEvent(CFG_EVENT_IO) {
Eric Laurent09f1ed22019-04-24 17:45:17 -0700140 mData = new IoConfigEventData(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700141 }
Eric Laurent10351942014-05-08 18:49:52 -0700142 };
Eric Laurent81784c32012-11-19 14:55:58 -0800143
Eric Laurent10351942014-05-08 18:49:52 -0700144 class PrioConfigEventData : public ConfigEventData {
145 public:
Mikhail Naganov83f04272017-02-07 10:45:09 -0800146 PrioConfigEventData(pid_t pid, pid_t tid, int32_t prio, bool forApp) :
147 mPid(pid), mTid(tid), mPrio(prio), mForApp(forApp) {}
Eric Laurent81784c32012-11-19 14:55:58 -0800148
149 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200150 snprintf(buffer, size, "- Prio event: pid %d, tid %d, prio %d, for app? %d\n",
Mikhail Naganov83f04272017-02-07 10:45:09 -0800151 mPid, mTid, mPrio, mForApp);
Eric Laurent81784c32012-11-19 14:55:58 -0800152 }
153
Eric Laurent81784c32012-11-19 14:55:58 -0800154 const pid_t mPid;
155 const pid_t mTid;
156 const int32_t mPrio;
Mikhail Naganov83f04272017-02-07 10:45:09 -0800157 const bool mForApp;
Eric Laurent81784c32012-11-19 14:55:58 -0800158 };
159
Eric Laurent10351942014-05-08 18:49:52 -0700160 class PrioConfigEvent : public ConfigEvent {
161 public:
Mikhail Naganov83f04272017-02-07 10:45:09 -0800162 PrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp) :
Eric Laurent72e3f392015-05-20 14:43:50 -0700163 ConfigEvent(CFG_EVENT_PRIO, true) {
Mikhail Naganov83f04272017-02-07 10:45:09 -0800164 mData = new PrioConfigEventData(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700165 }
Eric Laurent10351942014-05-08 18:49:52 -0700166 };
167
168 class SetParameterConfigEventData : public ConfigEventData {
169 public:
Andy Hung920f6572022-10-06 12:09:49 -0700170 explicit SetParameterConfigEventData(const String8& keyValuePairs) :
Eric Laurent10351942014-05-08 18:49:52 -0700171 mKeyValuePairs(keyValuePairs) {}
172
173 virtual void dump(char *buffer, size_t size) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000174 snprintf(buffer, size, "- KeyValue: %s\n", mKeyValuePairs.c_str());
Eric Laurent10351942014-05-08 18:49:52 -0700175 }
176
177 const String8 mKeyValuePairs;
178 };
179
180 class SetParameterConfigEvent : public ConfigEvent {
181 public:
Andy Hung920f6572022-10-06 12:09:49 -0700182 explicit SetParameterConfigEvent(const String8& keyValuePairs) :
Eric Laurent10351942014-05-08 18:49:52 -0700183 ConfigEvent(CFG_EVENT_SET_PARAMETER) {
184 mData = new SetParameterConfigEventData(keyValuePairs);
185 mWaitStatus = true;
186 }
Eric Laurent10351942014-05-08 18:49:52 -0700187 };
188
Eric Laurent1c333e22014-05-20 10:48:17 -0700189 class CreateAudioPatchConfigEventData : public ConfigEventData {
190 public:
191 CreateAudioPatchConfigEventData(const struct audio_patch patch,
192 audio_patch_handle_t handle) :
193 mPatch(patch), mHandle(handle) {}
194
195 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200196 snprintf(buffer, size, "- Patch handle: %u\n", mHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -0700197 }
198
199 const struct audio_patch mPatch;
200 audio_patch_handle_t mHandle;
201 };
202
203 class CreateAudioPatchConfigEvent : public ConfigEvent {
204 public:
205 CreateAudioPatchConfigEvent(const struct audio_patch patch,
206 audio_patch_handle_t handle) :
207 ConfigEvent(CFG_EVENT_CREATE_AUDIO_PATCH) {
208 mData = new CreateAudioPatchConfigEventData(patch, handle);
209 mWaitStatus = true;
210 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700211 };
212
213 class ReleaseAudioPatchConfigEventData : public ConfigEventData {
214 public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700215 explicit ReleaseAudioPatchConfigEventData(const audio_patch_handle_t handle) :
Eric Laurent1c333e22014-05-20 10:48:17 -0700216 mHandle(handle) {}
217
218 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200219 snprintf(buffer, size, "- Patch handle: %u\n", mHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -0700220 }
221
222 audio_patch_handle_t mHandle;
223 };
224
225 class ReleaseAudioPatchConfigEvent : public ConfigEvent {
226 public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700227 explicit ReleaseAudioPatchConfigEvent(const audio_patch_handle_t handle) :
Eric Laurent1c333e22014-05-20 10:48:17 -0700228 ConfigEvent(CFG_EVENT_RELEASE_AUDIO_PATCH) {
229 mData = new ReleaseAudioPatchConfigEventData(handle);
230 mWaitStatus = true;
231 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700232 };
Eric Laurent81784c32012-11-19 14:55:58 -0800233
jiabinc52b1ff2019-10-31 17:20:42 -0700234 class UpdateOutDevicesConfigEventData : public ConfigEventData {
235 public:
236 explicit UpdateOutDevicesConfigEventData(const DeviceDescriptorBaseVector& outDevices) :
237 mOutDevices(outDevices) {}
238
239 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200240 snprintf(buffer, size, "- Devices: %s", android::toString(mOutDevices).c_str());
jiabinc52b1ff2019-10-31 17:20:42 -0700241 }
242
243 DeviceDescriptorBaseVector mOutDevices;
244 };
245
246 class UpdateOutDevicesConfigEvent : public ConfigEvent {
247 public:
248 explicit UpdateOutDevicesConfigEvent(const DeviceDescriptorBaseVector& outDevices) :
249 ConfigEvent(CFG_EVENT_UPDATE_OUT_DEVICE) {
250 mData = new UpdateOutDevicesConfigEventData(outDevices);
251 }
jiabinc52b1ff2019-10-31 17:20:42 -0700252 };
253
Eric Laurentec376dc2021-04-08 20:41:22 +0200254 class ResizeBufferConfigEventData : public ConfigEventData {
255 public:
256 explicit ResizeBufferConfigEventData(int32_t maxSharedAudioHistoryMs) :
257 mMaxSharedAudioHistoryMs(maxSharedAudioHistoryMs) {}
258
259 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200260 snprintf(buffer, size, "- mMaxSharedAudioHistoryMs: %d", mMaxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +0200261 }
262
263 int32_t mMaxSharedAudioHistoryMs;
264 };
265
266 class ResizeBufferConfigEvent : public ConfigEvent {
267 public:
268 explicit ResizeBufferConfigEvent(int32_t maxSharedAudioHistoryMs) :
269 ConfigEvent(CFG_EVENT_RESIZE_BUFFER) {
270 mData = new ResizeBufferConfigEventData(maxSharedAudioHistoryMs);
271 }
Eric Laurentec376dc2021-04-08 20:41:22 +0200272 };
273
Eric Laurentb3f315a2021-07-13 15:09:05 +0200274 class CheckOutputStageEffectsEvent : public ConfigEvent {
275 public:
276 CheckOutputStageEffectsEvent() :
277 ConfigEvent(CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS) {
278 }
Eric Laurentb3f315a2021-07-13 15:09:05 +0200279 };
280
Eric Laurent68a40a82022-05-03 18:15:04 +0200281 class HalLatencyModesChangedEvent : public ConfigEvent {
282 public:
283 HalLatencyModesChangedEvent() :
284 ConfigEvent(CFG_EVENT_HAL_LATENCY_MODES_CHANGED) {
285 }
Eric Laurent68a40a82022-05-03 18:15:04 +0200286 };
287
Eric Laurentb3f315a2021-07-13 15:09:05 +0200288
Eric Laurent81784c32012-11-19 14:55:58 -0800289 class PMDeathRecipient : public IBinder::DeathRecipient {
290 public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700291 explicit PMDeathRecipient(const wp<ThreadBase>& thread) : mThread(thread) {}
Eric Laurent81784c32012-11-19 14:55:58 -0800292 virtual ~PMDeathRecipient() {}
293
294 // IBinder::DeathRecipient
295 virtual void binderDied(const wp<IBinder>& who);
296
297 private:
Mikhail Naganovbf493082017-04-17 17:37:12 -0700298 DISALLOW_COPY_AND_ASSIGN(PMDeathRecipient);
Eric Laurent81784c32012-11-19 14:55:58 -0800299
300 wp<ThreadBase> mThread;
301 };
302
Andy Hung440901d2023-06-29 21:19:25 -0700303 type_t type() const final { return mType; }
304 bool isDuplicating() const final { return (mType == DUPLICATING); }
305 audio_io_handle_t id() const final { return mId;}
Eric Laurent81784c32012-11-19 14:55:58 -0800306
Andy Hung440901d2023-06-29 21:19:25 -0700307 uint32_t sampleRate() const final { return mSampleRate; }
308 audio_channel_mask_t channelMask() const final { return mChannelMask; }
309 audio_channel_mask_t mixerChannelMask() const override { return mChannelMask; }
310 audio_format_t format() const final { return mHALFormat; }
311 uint32_t channelCount() const final { return mChannelCount; }
312 audio_channel_mask_t hapticChannelMask() const override { return AUDIO_CHANNEL_NONE; }
Andy Hung87c693c2023-07-06 20:56:16 -0700313 uint32_t hapticChannelCount() const override { return 0; }
Andy Hung440901d2023-06-29 21:19:25 -0700314 uint32_t latency_l() const override { return 0; }
315 void setVolumeForOutput_l(float /* left */, float /* right */) const override {}
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700316
317 // Return's the HAL's frame count i.e. fast mixer buffer size.
Andy Hung440901d2023-06-29 21:19:25 -0700318 size_t frameCountHAL() const final { return mFrameCount; }
319 size_t frameSize() const final { return mFrameSize; }
Eric Laurent81784c32012-11-19 14:55:58 -0800320
321 // Should be "virtual status_t requestExitAndWait()" and override same
322 // method in Thread, but Thread::requestExitAndWait() is not yet virtual.
Andy Hung440901d2023-06-29 21:19:25 -0700323 void exit() final;
324 status_t setParameters(const String8& keyValuePairs) final;
325
Andy Hungc5007f82023-08-29 14:26:09 -0700326 // sendConfigEvent_l() must be called with ThreadBase::mutex() held
Eric Laurent10351942014-05-08 18:49:52 -0700327 // Can temporarily release the lock if waiting for a reply from
328 // processConfigEvents_l().
Andy Hung440901d2023-06-29 21:19:25 -0700329 status_t sendConfigEvent_l(sp<ConfigEvent>& event);
330 void sendIoConfigEvent(audio_io_config_event_t event, pid_t pid = 0,
331 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final;
332 void sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid = 0,
333 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final;
334 void sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp) final;
335 void sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio, bool forApp) final;
336 status_t sendSetParameterConfigEvent_l(const String8& keyValuePair) final;
337 status_t sendCreateAudioPatchConfigEvent(const struct audio_patch* patch,
338 audio_patch_handle_t* handle) final;
339 status_t sendReleaseAudioPatchConfigEvent(audio_patch_handle_t handle) final;
340 status_t sendUpdateOutDeviceConfigEvent(
341 const DeviceDescriptorBaseVector& outDevices) final;
342 void sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs) final;
343 void sendCheckOutputStageEffectsEvent() final;
344 void sendCheckOutputStageEffectsEvent_l() final;
345 void sendHalLatencyModesChangedEvent_l() final;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200346
Andy Hung440901d2023-06-29 21:19:25 -0700347 void processConfigEvents_l() final;
348 void setCheckOutputStageEffects() override {}
349 void updateOutDevices(const DeviceDescriptorBaseVector& outDevices) override;
350 void toAudioPortConfig(struct audio_port_config* config) override;
351 void resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs) override;
Eric Laurent1c333e22014-05-20 10:48:17 -0700352
Andy Hung440901d2023-06-29 21:19:25 -0700353 // see note at declaration of mStandby, mOutDevice and mInDevice
354 bool inStandby() const override { return mStandby; }
355 const DeviceTypeSet outDeviceTypes() const final {
356 return getAudioDeviceTypes(mOutDeviceTypeAddrs);
357 }
358 audio_devices_t inDeviceType() const final { return mInDeviceTypeAddr.mType; }
359 DeviceTypeSet getDeviceTypes() const final {
360 return isOutput() ? outDeviceTypes() : DeviceTypeSet({inDeviceType()});
361 }
Eric Laurent81784c32012-11-19 14:55:58 -0800362
Andy Hung440901d2023-06-29 21:19:25 -0700363 const AudioDeviceTypeAddrVector& outDeviceTypeAddrs() const final {
364 return mOutDeviceTypeAddrs;
365 }
366 const AudioDeviceTypeAddr& inDeviceTypeAddr() const final {
367 return mInDeviceTypeAddr;
368 }
Andy Hung293558a2017-03-21 12:19:20 -0700369
Andy Hung440901d2023-06-29 21:19:25 -0700370 bool isOutput() const final { return mIsOut; }
jiabin8f278ee2019-11-11 12:16:27 -0800371
Andy Hung440901d2023-06-29 21:19:25 -0700372 bool isOffloadOrMmap() const final {
373 switch (mType) {
374 case OFFLOAD:
375 case MMAP_PLAYBACK:
376 case MMAP_CAPTURE:
377 return true;
378 default:
379 return false;
380 }
381 }
Eric Laurent81784c32012-11-19 14:55:58 -0800382
Andy Hung440901d2023-06-29 21:19:25 -0700383 sp<IAfEffectHandle> createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -0700384 const sp<Client>& client,
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700385 const sp<media::IEffectClient>& effectClient,
Eric Laurent81784c32012-11-19 14:55:58 -0800386 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -0800387 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800388 effect_descriptor_t *desc,
389 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -0800390 status_t *status /*non-NULL*/,
Eric Laurent2fe0acd2020-03-13 14:30:46 -0700391 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +0200392 bool probe,
Andy Hung440901d2023-06-29 21:19:25 -0700393 bool notifyFramesProcessed) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800394
395 // return values for hasAudioSession (bit field)
396 enum effect_state {
397 EFFECT_SESSION = 0x1, // the audio session corresponds to at least one
398 // effect
Eric Laurent4c415062016-06-17 16:14:16 -0700399 TRACK_SESSION = 0x2, // the audio session corresponds to at least one
Eric Laurent81784c32012-11-19 14:55:58 -0800400 // track
Eric Laurentb62d0362021-10-26 17:40:18 +0200401 FAST_SESSION = 0x4, // the audio session corresponds to at least one
Eric Laurent4c415062016-06-17 16:14:16 -0700402 // fast track
jiabinc658e452022-10-21 20:52:21 +0000403 SPATIALIZED_SESSION = 0x8, // the audio session corresponds to at least one
404 // spatialized track
405 BIT_PERFECT_SESSION = 0x10 // the audio session corresponds to at least one
406 // bit-perfect track
Eric Laurent81784c32012-11-19 14:55:58 -0800407 };
408
Andy Hung440901d2023-06-29 21:19:25 -0700409 // get effect chain corresponding to session Id.
410 sp<IAfEffectChain> getEffectChain(audio_session_t sessionId) const final;
411 // same as getEffectChain() but must be called with ThreadBase mutex locked
412 sp<IAfEffectChain> getEffectChain_l(audio_session_t sessionId) const final;
413 std::vector<int> getEffectIds_l(audio_session_t sessionId) const final;
414
Eric Laurent81784c32012-11-19 14:55:58 -0800415 // lock all effect chains Mutexes. Must be called before releasing the
416 // ThreadBase mutex before processing the mixer and effects. This guarantees the
417 // integrity of the chains during the process.
418 // Also sets the parameter 'effectChains' to current value of mEffectChains.
Andy Hung440901d2023-06-29 21:19:25 -0700419 void lockEffectChains_l(Vector<sp<IAfEffectChain>>& effectChains) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800420 // unlock effect chains after process
Andy Hung440901d2023-06-29 21:19:25 -0700421 void unlockEffectChains(const Vector<sp<IAfEffectChain>>& effectChains) final;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800422 // get a copy of mEffectChains vector
Andy Hung440901d2023-06-29 21:19:25 -0700423 Vector<sp<IAfEffectChain>> getEffectChains_l() const final { return mEffectChains; };
Eric Laurent81784c32012-11-19 14:55:58 -0800424 // set audio mode to all effect chains
Andy Hung440901d2023-06-29 21:19:25 -0700425 void setMode(audio_mode_t mode) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800426 // get effect module with corresponding ID on specified audio session
Andy Hung440901d2023-06-29 21:19:25 -0700427 sp<IAfEffectModule> getEffect(audio_session_t sessionId, int effectId) const final;
428 sp<IAfEffectModule> getEffect_l(audio_session_t sessionId, int effectId) const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800429 // add and effect module. Also creates the effect chain is none exists for
Eric Laurent6c796322019-04-09 14:13:17 -0700430 // the effects audio session. Only called in a context of moving an effect
431 // from one thread to another
Andy Hung440901d2023-06-29 21:19:25 -0700432 status_t addEffect_l(const sp<IAfEffectModule>& effect) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800433 // remove and effect module. Also removes the effect chain is this was the last
434 // effect
Andy Hung440901d2023-06-29 21:19:25 -0700435 void removeEffect_l(const sp<IAfEffectModule>& effect, bool release = false) final;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -0800436 // disconnect an effect handle from module and destroy module if last handle
Andy Hung440901d2023-06-29 21:19:25 -0700437 void disconnectEffectHandle(IAfEffectHandle* handle, bool unpinIfLast) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800438 // detach all tracks connected to an auxiliary effect
Andy Hung440901d2023-06-29 21:19:25 -0700439 void detachAuxEffect_l(int /* effectId */) override {}
Andy Hung99b1ba62023-07-14 11:00:08 -0700440 // TODO(b/291317898) - remove hasAudioSession_l below.
Andy Hung440901d2023-06-29 21:19:25 -0700441 uint32_t hasAudioSession_l(audio_session_t sessionId) const override = 0;
442 uint32_t hasAudioSession(audio_session_t sessionId) const final {
Andy Hungc5007f82023-08-29 14:26:09 -0700443 std::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -0700444 return hasAudioSession_l(sessionId);
445 }
446
Andy Hungc3d62f92019-03-14 13:38:51 -0700447 template <typename T>
448 uint32_t hasAudioSession_l(audio_session_t sessionId, const T& tracks) const {
449 uint32_t result = 0;
450 if (getEffectChain_l(sessionId) != 0) {
451 result = EFFECT_SESSION;
452 }
453 for (size_t i = 0; i < tracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -0700454 const sp<IAfTrackBase>& track = tracks[i];
Andy Hungc3d62f92019-03-14 13:38:51 -0700455 if (sessionId == track->sessionId()
456 && !track->isInvalid() // not yet removed from tracks.
457 && !track->isTerminated()) {
458 result |= TRACK_SESSION;
459 if (track->isFastTrack()) {
460 result |= FAST_SESSION; // caution, only represents first track.
461 }
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200462 if (track->isSpatialized()) {
Eric Laurentb62d0362021-10-26 17:40:18 +0200463 result |= SPATIALIZED_SESSION; // caution, only first track.
464 }
jiabinc658e452022-10-21 20:52:21 +0000465 if (track->isBitPerfect()) {
466 result |= BIT_PERFECT_SESSION;
467 }
Andy Hungc3d62f92019-03-14 13:38:51 -0700468 break;
469 }
470 }
471 return result;
472 }
473
Eric Laurent81784c32012-11-19 14:55:58 -0800474 // the value returned by default implementation is not important as the
475 // strategy is only meaningful for PlaybackThread which implements this method
Andy Hung440901d2023-06-29 21:19:25 -0700476 product_strategy_t getStrategyForSession_l(
477 audio_session_t /* sessionId */) const override {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800478 return static_cast<product_strategy_t>(0);
479 }
Eric Laurent81784c32012-11-19 14:55:58 -0800480
Eric Laurent81784c32012-11-19 14:55:58 -0800481 // check if some effects must be suspended/restored when an effect is enabled
482 // or disabled
Andy Hung440901d2023-06-29 21:19:25 -0700483 void checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -0800484 audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -0700485 bool threadLocked) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800486
Eric Laurent81784c32012-11-19 14:55:58 -0800487
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700488 // Return a reference to a per-thread heap which can be used to allocate IMemory
489 // objects that will be read-only to client processes, read/write to mediaserver,
490 // and shared by all client processes of the thread.
491 // The heap is per-thread rather than common across all threads, because
492 // clients can't be trusted not to modify the offset of the IMemory they receive.
493 // If a thread does not have such a heap, this method returns 0.
Andy Hung440901d2023-06-29 21:19:25 -0700494 sp<MemoryDealer> readOnlyHeap() const override { return nullptr; }
Eric Laurent81784c32012-11-19 14:55:58 -0800495
Andy Hung440901d2023-06-29 21:19:25 -0700496 sp<IMemory> pipeMemory() const override { return nullptr; }
Glenn Kasten6181ffd2014-05-13 10:41:52 -0700497
Andy Hung440901d2023-06-29 21:19:25 -0700498 void systemReady() final;
Eric Laurent72e3f392015-05-20 14:43:50 -0700499
Andy Hung440901d2023-06-29 21:19:25 -0700500 void broadcast_l() final;
Eric Laurent4c415062016-06-17 16:14:16 -0700501
Andy Hung440901d2023-06-29 21:19:25 -0700502 bool isTimestampCorrectionEnabled() const override { return false; }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800503
Andy Hung440901d2023-06-29 21:19:25 -0700504 bool isMsdDevice() const final { return mIsMsdDevice; }
Andy Hungc8fddf32018-08-08 18:32:37 -0700505
Andy Hung440901d2023-06-29 21:19:25 -0700506 void dump(int fd, const Vector<String16>& args) override;
Andy Hungdc099c22018-09-18 13:46:39 -0700507
Andy Hungd0979812019-02-21 15:51:44 -0800508 // deliver stats to mediametrics.
Andy Hung440901d2023-06-29 21:19:25 -0700509 void sendStatistics(bool force) final;
Andy Hungd0979812019-02-21 15:51:44 -0800510
Andy Hungc5007f82023-08-29 14:26:09 -0700511 audio_utils::mutex& mutex() const final {
512 return mMutex;
Andy Hung440901d2023-06-29 21:19:25 -0700513 }
Andy Hungc5007f82023-08-29 14:26:09 -0700514 mutable audio_utils::mutex mMutex;
Eric Laurent81784c32012-11-19 14:55:58 -0800515
Andy Hung440901d2023-06-29 21:19:25 -0700516 void onEffectEnable(const sp<IAfEffectModule>& effect) final;
517 void onEffectDisable() final;
Eric Laurent6b446ce2019-12-13 10:56:31 -0800518
Andy Hungc5007f82023-08-29 14:26:09 -0700519 // invalidateTracksForAudioSession_l must be called with holding mutex().
Andy Hung440901d2023-06-29 21:19:25 -0700520 void invalidateTracksForAudioSession_l(audio_session_t /* sessionId */) const override {}
jiabineb3bda02020-06-30 14:07:03 -0700521 // Invalidate all the tracks with the given audio session.
Andy Hung440901d2023-06-29 21:19:25 -0700522 void invalidateTracksForAudioSession(audio_session_t sessionId) const final {
Andy Hungc5007f82023-08-29 14:26:09 -0700523 std::lock_guard _l(mutex());
jiabineb3bda02020-06-30 14:07:03 -0700524 invalidateTracksForAudioSession_l(sessionId);
525 }
526
527 template <typename T>
528 void invalidateTracksForAudioSession_l(audio_session_t sessionId,
529 const T& tracks) const {
530 for (size_t i = 0; i < tracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -0700531 const sp<IAfTrackBase>& track = tracks[i];
jiabineb3bda02020-06-30 14:07:03 -0700532 if (sessionId == track->sessionId()) {
533 track->invalidate();
534 }
535 }
536 }
537
Andy Hung440901d2023-06-29 21:19:25 -0700538 void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) override;
539 void stopMelComputation_l() override;
Vlad Popa6fbbfbf2023-02-22 15:05:43 +0100540
Eric Laurent81784c32012-11-19 14:55:58 -0800541protected:
542
543 // entry describing an effect being suspended in mSuspendedSessions keyed vector
544 class SuspendedSessionDesc : public RefBase {
545 public:
546 SuspendedSessionDesc() : mRefCount(0) {}
547
548 int mRefCount; // number of active suspend requests
549 effect_uuid_t mType; // effect type UUID
550 };
551
Andy Hungdae27702016-10-31 14:01:16 -0700552 void acquireWakeLock();
553 virtual void acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800554 void releaseWakeLock();
555 void releaseWakeLock_l();
Andy Hungd01b0f12016-11-07 16:10:30 -0800556 void updateWakeLockUids_l(const SortedVector<uid_t> &uids);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800557 void getPowerManager_l();
Eric Laurentd8365c52017-07-16 15:27:05 -0700558 // suspend or restore effects of the specified type (or all if type is NULL)
559 // on a given session. The number of suspend requests is counted and restore
560 // occurs when all suspend requests are cancelled.
Eric Laurent81784c32012-11-19 14:55:58 -0800561 void setEffectSuspended_l(const effect_uuid_t *type,
562 bool suspend,
Andy Hung87c693c2023-07-06 20:56:16 -0700563 audio_session_t sessionId) final;
Eric Laurentd8365c52017-07-16 15:27:05 -0700564 // updated mSuspendedSessions when an effect is suspended or restored
Eric Laurent81784c32012-11-19 14:55:58 -0800565 void updateSuspendedSessions_l(const effect_uuid_t *type,
566 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -0800567 audio_session_t sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800568 // check if some effects must be suspended when an effect chain is added
Andy Hung116bc262023-06-20 18:56:17 -0700569 void checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain);
Eric Laurent81784c32012-11-19 14:55:58 -0800570
Kevin Rocard069c2712018-03-29 19:09:14 -0700571 // sends the metadata of the active tracks to the HAL
Vlad Popa7e81cea2023-01-19 16:34:16 +0100572 struct MetadataUpdate {
573 std::vector<playback_track_metadata_v7_t> playbackMetadataUpdate;
574 std::vector<record_track_metadata_v7_t> recordMetadataUpdate;
575 };
576 virtual MetadataUpdate updateMetadata_l() = 0;
Kevin Rocard069c2712018-03-29 19:09:14 -0700577
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100578 String16 getWakeLockTag();
579
Eric Laurent81784c32012-11-19 14:55:58 -0800580 virtual void preExit() { }
Andy Hung2ddee192015-12-18 17:34:44 -0800581 virtual void setMasterMono_l(bool mono __unused) { }
582 virtual bool requireMonoBlend() { return false; }
Eric Laurent81784c32012-11-19 14:55:58 -0800583
Andy Hung1c86ebe2018-05-29 20:29:08 -0700584 // called within the threadLoop to obtain timestamp from the HAL.
585 virtual status_t threadloop_getHalTimestamp_l(
586 ExtendedTimestamp *timestamp __unused) const {
587 return INVALID_OPERATION;
588 }
Andy Hung116bc262023-06-20 18:56:17 -0700589public:
Andy Hung99b1ba62023-07-14 11:00:08 -0700590// TODO(b/291317898) organize with publics
Eric Laurentd66d7a12021-07-13 13:35:32 +0200591 product_strategy_t getStrategyForStream(audio_stream_type_t stream) const;
Andy Hung116bc262023-06-20 18:56:17 -0700592protected:
Eric Laurentd66d7a12021-07-13 13:35:32 +0200593
Eric Laurentb0463942022-12-20 16:31:10 +0100594 virtual void onHalLatencyModesChanged_l() {}
595
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700596 virtual void dumpInternals_l(int fd __unused, const Vector<String16>& args __unused)
597 { }
598 virtual void dumpTracks_l(int fd __unused, const Vector<String16>& args __unused) { }
599
Eric Laurent81784c32012-11-19 14:55:58 -0800600 const type_t mType;
601
602 // Used by parameters, config events, addTrack_l, exit
Andy Hungc5007f82023-08-29 14:26:09 -0700603 audio_utils::condition_variable mWaitWorkCV;
Eric Laurent81784c32012-11-19 14:55:58 -0800604
Andy Hung583043b2023-07-17 17:05:00 -0700605 const sp<IAfThreadCallback> mAfThreadCallback;
Andy Hungcf10d742020-04-28 15:38:24 -0700606 ThreadMetrics mThreadMetrics;
607 const bool mIsOut;
Glenn Kasten9b58f632013-07-16 11:37:48 -0700608
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800609 // updated by PlaybackThread::readOutputParameters_l() or
610 // RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800611 uint32_t mSampleRate;
612 size_t mFrameCount; // output HAL, direct output, record
Eric Laurent81784c32012-11-19 14:55:58 -0800613 audio_channel_mask_t mChannelMask;
Glenn Kastenf6ed4232013-07-16 11:16:27 -0700614 uint32_t mChannelCount;
Eric Laurent81784c32012-11-19 14:55:58 -0800615 size_t mFrameSize;
Glenn Kasten97b7b752014-09-28 13:04:24 -0700616 // not HAL frame size, this is for output sink (to pipe to fast mixer)
Andy Hung463be252014-07-10 16:56:07 -0700617 audio_format_t mFormat; // Source format for Recording and
618 // Sink format for Playback.
619 // Sink format may be different than
620 // HAL format if Fastmixer is used.
621 audio_format_t mHALFormat;
Glenn Kasten70949c42013-08-06 07:40:12 -0700622 size_t mBufferSize; // HAL buffer size for read() or write()
jiabinc52b1ff2019-10-31 17:20:42 -0700623 AudioDeviceTypeAddrVector mOutDeviceTypeAddrs; // output device types and addresses
624 AudioDeviceTypeAddr mInDeviceTypeAddr; // input device type and address
Eric Laurent10351942014-05-08 18:49:52 -0700625 Vector< sp<ConfigEvent> > mConfigEvents;
Eric Laurent72e3f392015-05-20 14:43:50 -0700626 Vector< sp<ConfigEvent> > mPendingConfigEvents; // events awaiting system ready
Eric Laurent81784c32012-11-19 14:55:58 -0800627
628 // These fields are written and read by thread itself without lock or barrier,
jiabinc52b1ff2019-10-31 17:20:42 -0700629 // and read by other threads without lock or barrier via standby(), outDeviceTypes()
630 // and inDeviceType().
Eric Laurent81784c32012-11-19 14:55:58 -0800631 // Because of the absence of a lock or barrier, any other thread that reads
632 // these fields must use the information in isolation, or be prepared to deal
633 // with possibility that it might be inconsistent with other information.
Glenn Kasten4944acb2013-08-19 08:39:20 -0700634 bool mStandby; // Whether thread is currently in standby.
jiabinc52b1ff2019-10-31 17:20:42 -0700635
Eric Laurent296fb132015-05-01 11:38:42 -0700636 struct audio_patch mPatch;
jiabinc52b1ff2019-10-31 17:20:42 -0700637
Glenn Kastenf59497b2015-01-26 16:35:47 -0800638 audio_source_t mAudioSource;
Eric Laurent81784c32012-11-19 14:55:58 -0800639
640 const audio_io_handle_t mId;
Andy Hung116bc262023-06-20 18:56:17 -0700641 Vector<sp<IAfEffectChain>> mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -0800642
Glenn Kastend7dca052015-03-05 16:05:54 -0800643 static const int kThreadNameLength = 16; // prctl(PR_SET_NAME) limit
644 char mThreadName[kThreadNameLength]; // guaranteed NUL-terminated
Chris Ye6597d732020-02-28 22:38:25 -0800645 sp<os::IPowerManager> mPowerManager;
Eric Laurent81784c32012-11-19 14:55:58 -0800646 sp<IBinder> mWakeLockToken;
647 const sp<PMDeathRecipient> mDeathRecipient;
Glenn Kastend848eb42016-03-08 13:42:11 -0800648 // list of suspended effects per session and per type. The first (outer) vector is
649 // keyed by session ID, the second (inner) by type UUID timeLow field
Eric Laurentd8365c52017-07-16 15:27:05 -0700650 // Updated by updateSuspendedSessions_l() only.
Glenn Kastend848eb42016-03-08 13:42:11 -0800651 KeyedVector< audio_session_t, KeyedVector< int, sp<SuspendedSessionDesc> > >
Eric Laurent81784c32012-11-19 14:55:58 -0800652 mSuspendedSessions;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -0700653 // TODO: add comment and adjust size as needed
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800654 static const size_t kLogSize = 4 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -0800655 sp<NBLog::Writer> mNBLogWriter;
Eric Laurent72e3f392015-05-20 14:43:50 -0700656 bool mSystemReady;
Andy Hung818e7a32016-02-16 18:08:07 -0800657 ExtendedTimestamp mTimestamp;
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700658 TimestampVerifier< // For timestamp statistics.
659 int64_t /* frame count */, int64_t /* time ns */> mTimestampVerifier;
Dean Wheatley12473e92021-03-18 23:00:55 +1100660 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush
661 // TODO: add confirmation checks:
662 // 1) DIRECT threads and linear PCM format really resets to 0?
663 // 2) Is frame count really valid if not linear pcm?
664 // 3) Are all 64 bits of position returned, not just lowest 32 bits?
jiabinc52b1ff2019-10-31 17:20:42 -0700665 // Timestamp corrected device should be a single device.
666 audio_devices_t mTimestampCorrectedDevice = AUDIO_DEVICE_NONE;
Andy Hung446f4df2019-02-21 12:26:41 -0800667
668 // ThreadLoop statistics per iteration.
669 int64_t mLastIoBeginNs = -1;
670 int64_t mLastIoEndNs = -1;
671
Andy Hung44d648b2022-04-08 17:33:40 -0700672 // ThreadSnapshot is thread-safe (internally locked)
673 mediautils::ThreadSnapshot mThreadSnapshot;
674
Andy Hung446f4df2019-02-21 12:26:41 -0800675 // This should be read under ThreadBase lock (if not on the threadLoop thread).
676 audio_utils::Statistics<double> mIoJitterMs{0.995 /* alpha */};
677 audio_utils::Statistics<double> mProcessTimeMs{0.995 /* alpha */};
Andy Hunge6c37112019-02-26 17:38:10 -0800678 audio_utils::Statistics<double> mLatencyMs{0.995 /* alpha */};
Robert Wu06db0a32021-08-10 19:05:34 +0000679 audio_utils::Statistics<double> mMonopipePipeDepthStats{0.999 /* alpha */};
Andy Hung446f4df2019-02-21 12:26:41 -0800680
Andy Hungd0979812019-02-21 15:51:44 -0800681 // Save the last count when we delivered statistics to mediametrics.
682 int64_t mLastRecordedTimestampVerifierN = 0;
683 int64_t mLastRecordedTimeNs = 0; // BOOTTIME to include suspend.
684
Andy Hungc8fddf32018-08-08 18:32:37 -0700685 bool mIsMsdDevice = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800686 // A condition that must be evaluated by the thread loop has changed and
687 // we must not wait for async write callback in the thread loop before evaluating it
688 bool mSignalPending;
Andy Hungdae27702016-10-31 14:01:16 -0700689
Andy Hung8946a282018-04-19 20:04:56 -0700690#ifdef TEE_SINK
691 NBAIO_Tee mTee;
692#endif
Andy Hungdae27702016-10-31 14:01:16 -0700693 // ActiveTracks is a sorted vector of track type T representing the
694 // active tracks of threadLoop() to be considered by the locked prepare portion.
695 // ActiveTracks should be accessed with the ThreadBase lock held.
696 //
697 // During processing and I/O, the threadLoop does not hold the lock;
698 // hence it does not directly use ActiveTracks. Care should be taken
699 // to hold local strong references or defer removal of tracks
700 // if the threadLoop may still be accessing those tracks due to mix, etc.
701 //
702 // This class updates power information appropriately.
703 //
704
705 template <typename T>
706 class ActiveTracks {
707 public:
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700708 explicit ActiveTracks(SimpleLog *localLog = nullptr)
Andy Hungdae27702016-10-31 14:01:16 -0700709 : mActiveTracksGeneration(0)
710 , mLastActiveTracksGeneration(0)
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700711 , mLocalLog(localLog)
Andy Hungdae27702016-10-31 14:01:16 -0700712 { }
713
714 ~ActiveTracks() {
715 ALOGW_IF(!mActiveTracks.isEmpty(),
716 "ActiveTracks should be empty in destructor");
717 }
718 // returns the last track added (even though it may have been
719 // subsequently removed from ActiveTracks).
720 //
721 // Used for DirectOutputThread to ensure a flush is called when transitioning
722 // to a new track (even though it may be on the same session).
723 // Used for OffloadThread to ensure that volume and mixer state is
724 // taken from the latest track added.
725 //
726 // The latest track is saved with a weak pointer to prevent keeping an
727 // otherwise useless track alive. Thus the function will return nullptr
728 // if the latest track has subsequently been removed and destroyed.
729 sp<T> getLatest() {
730 return mLatestActiveTrack.promote();
731 }
732
733 // SortedVector methods
734 ssize_t add(const sp<T> &track);
735 ssize_t remove(const sp<T> &track);
736 size_t size() const {
737 return mActiveTracks.size();
738 }
Eric Tan39ec8d62018-07-24 09:49:29 -0700739 bool isEmpty() const {
740 return mActiveTracks.isEmpty();
741 }
Andy Hung87c693c2023-07-06 20:56:16 -0700742 ssize_t indexOf(const sp<T>& item) const {
Andy Hungdae27702016-10-31 14:01:16 -0700743 return mActiveTracks.indexOf(item);
744 }
745 sp<T> operator[](size_t index) const {
746 return mActiveTracks[index];
747 }
748 typename SortedVector<sp<T>>::iterator begin() {
749 return mActiveTracks.begin();
750 }
751 typename SortedVector<sp<T>>::iterator end() {
752 return mActiveTracks.end();
753 }
754
755 // Due to Binder recursion optimization, clear() and updatePowerState()
756 // cannot be called from a Binder thread because they may call back into
757 // the original calling process (system server) for BatteryNotifier
758 // (which requires a Java environment that may not be present).
759 // Hence, call clear() and updatePowerState() only from the
760 // ThreadBase thread.
761 void clear();
762 // periodically called in the threadLoop() to update power state uids.
Andy Hung920f6572022-10-06 12:09:49 -0700763 void updatePowerState(const sp<ThreadBase>& thread, bool force = false);
Andy Hungdae27702016-10-31 14:01:16 -0700764
Kevin Rocardc86a7f72018-04-03 09:00:09 -0700765 /** @return true if one or move active tracks was added or removed since the
Jasmine Chaeaa10e42021-05-11 10:11:14 +0800766 * last time this function was called or the vector was created.
767 * true if volume of one of active tracks was changed.
768 */
Kevin Rocard069c2712018-03-29 19:09:14 -0700769 bool readAndClearHasChanged();
770
Eric Laurentdda206a2022-07-08 17:28:35 +0200771 /** Force updating track metadata to audio HAL stream next time
772 * readAndClearHasChanged() is called.
773 */
774 void setHasChanged() { mHasChanged = true; }
775
Andy Hungdae27702016-10-31 14:01:16 -0700776 private:
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700777 void logTrack(const char *funcName, const sp<T> &track) const;
778
Andy Hungd01b0f12016-11-07 16:10:30 -0800779 SortedVector<uid_t> getWakeLockUids() {
780 SortedVector<uid_t> wakeLockUids;
Andy Hungdae27702016-10-31 14:01:16 -0700781 for (const sp<T> &track : mActiveTracks) {
782 wakeLockUids.add(track->uid());
783 }
784 return wakeLockUids; // moved by underlying SharedBuffer
785 }
786
Andy Hungdae27702016-10-31 14:01:16 -0700787 SortedVector<sp<T>> mActiveTracks;
788 int mActiveTracksGeneration;
789 int mLastActiveTracksGeneration;
790 wp<T> mLatestActiveTrack; // latest track added to ActiveTracks
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700791 SimpleLog * const mLocalLog;
Kevin Rocardc86a7f72018-04-03 09:00:09 -0700792 // If the vector has changed since last call to readAndClearHasChanged
Kevin Rocard069c2712018-03-29 19:09:14 -0700793 bool mHasChanged = false;
Andy Hungdae27702016-10-31 14:01:16 -0700794 };
Andy Hung293558a2017-03-21 12:19:20 -0700795
796 SimpleLog mLocalLog;
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700797
798private:
799 void dumpBase_l(int fd, const Vector<String16>& args);
800 void dumpEffectChains_l(int fd, const Vector<String16>& args);
Eric Laurent81784c32012-11-19 14:55:58 -0800801};
802
803// --- PlaybackThread ---
Andy Hung440901d2023-06-29 21:19:25 -0700804class PlaybackThread : public ThreadBase, public virtual IAfPlaybackThread,
805 public StreamOutHalInterfaceCallback,
Andy Hung87c693c2023-07-06 20:56:16 -0700806 public virtual VolumeInterface, public StreamOutHalInterfaceEventCallback {
Eric Laurent81784c32012-11-19 14:55:58 -0800807public:
Andy Hung87c693c2023-07-06 20:56:16 -0700808 sp<IAfPlaybackThread> asIAfPlaybackThread() final {
809 return sp<IAfPlaybackThread>::fromExisting(this);
810 }
Eric Laurent81784c32012-11-19 14:55:58 -0800811
Eric Laurente93cc032016-05-05 10:15:10 -0700812 // retry count before removing active track in case of underrun on offloaded thread:
813 // we need to make sure that AudioTrack client has enough time to send large buffers
814 //FIXME may be more appropriate if expressed in time units. Need to revise how underrun is
815 // handled for offloaded tracks
816 static const int8_t kMaxTrackRetriesOffload = 20;
817 static const int8_t kMaxTrackStartupRetriesOffload = 100;
Andy Hung8ed196a2018-01-05 13:21:11 -0800818 static constexpr uint32_t kMaxTracksPerUid = 40;
Andy Hung1bc088a2018-02-09 15:57:31 -0800819 static constexpr size_t kMaxTracks = 256;
Eric Laurente93cc032016-05-05 10:15:10 -0700820
rago1bb90822017-05-02 18:31:48 -0700821 // Maximum delay (in nanoseconds) for upcoming buffers in suspend mode, otherwise
822 // if delay is greater, the estimated time for timeLoopNextNs is reset.
823 // This allows for catch-up to be done for small delays, while resetting the estimate
824 // for initial conditions or large delays.
825 static const nsecs_t kMaxNextBufferDelayNs = 100000000;
826
Andy Hung583043b2023-07-17 17:05:00 -0700827 PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +0200828 audio_io_handle_t id, type_t type, bool systemReady,
829 audio_config_base_t *mixerConfig = nullptr);
Andy Hung440901d2023-06-29 21:19:25 -0700830 ~PlaybackThread() override;
Eric Laurent81784c32012-11-19 14:55:58 -0800831
Eric Laurent81784c32012-11-19 14:55:58 -0800832 // Thread virtuals
Andy Hung440901d2023-06-29 21:19:25 -0700833 bool threadLoop() final;
Eric Laurent81784c32012-11-19 14:55:58 -0800834
835 // RefBase
Andy Hung440901d2023-06-29 21:19:25 -0700836 void onFirstRef() override;
Eric Laurent81784c32012-11-19 14:55:58 -0800837
Andy Hung440901d2023-06-29 21:19:25 -0700838 status_t checkEffectCompatibility_l(
839 const effect_descriptor_t* desc, audio_session_t sessionId) final;
Eric Laurent4c415062016-06-17 16:14:16 -0700840
Andy Hung87c693c2023-07-06 20:56:16 -0700841 void addOutputTrack_l(const sp<IAfTrack>& track) final {
842 mTracks.add(track);
843 }
844
Eric Laurent81784c32012-11-19 14:55:58 -0800845protected:
846 // Code snippets that were lifted up out of threadLoop()
847 virtual void threadLoop_mix() = 0;
848 virtual void threadLoop_sleepTime() = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800849 virtual ssize_t threadLoop_write();
850 virtual void threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -0800851 virtual void threadLoop_standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800852 virtual void threadLoop_exit();
Andy Hung8d31fd22023-06-26 19:20:57 -0700853 virtual void threadLoop_removeTracks(const Vector<sp<IAfTrack>>& tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -0800854
855 // prepareTracks_l reads and writes mActiveTracks, and returns
856 // the pending set of tracks to remove via Vector 'tracksToRemove'. The caller
857 // is responsible for clearing or destroying this Vector later on, when it
858 // is safe to do so. That will drop the final ref count and destroy the tracks.
Andy Hung8d31fd22023-06-26 19:20:57 -0700859 virtual mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove) = 0;
860 void removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove);
Eric Laurenteab90452019-06-24 15:17:46 -0700861 status_t handleVoipVolume_l(float *volume);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800862
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700863 // StreamOutHalInterfaceCallback implementation
864 virtual void onWriteReady();
865 virtual void onDrainReady();
866 virtual void onError();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800867
Andy Hungee58e4a2023-07-07 13:47:37 -0700868public: // AsyncCallbackThread
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700869 void resetWriteBlocked(uint32_t sequence);
870 void resetDraining(uint32_t sequence);
Andy Hungee58e4a2023-07-07 13:47:37 -0700871protected:
Eric Laurentbfb1b832013-01-07 09:53:42 -0800872
873 virtual bool waitingAsyncCallback();
874 virtual bool waitingAsyncCallback_l();
875 virtual bool shouldStandby_l();
Haynes Mathew George4c6a4332014-01-15 12:31:39 -0800876 virtual void onAddNewTrack_l();
Andy Hungee58e4a2023-07-07 13:47:37 -0700877public: // AsyncCallbackThread
Haynes Mathew George4527b9e2016-07-07 19:54:17 -0700878 void onAsyncError(); // error reported by AsyncCallbackThread
Andy Hungee58e4a2023-07-07 13:47:37 -0700879protected:
jiabinf6eb4c32020-02-25 14:06:25 -0800880 // StreamHalInterfaceCodecFormatCallback implementation
881 void onCodecFormatChanged(
Andy Hung440901d2023-06-29 21:19:25 -0700882 const std::basic_string<uint8_t>& metadataBs) final;
jiabinf6eb4c32020-02-25 14:06:25 -0800883
Eric Laurent81784c32012-11-19 14:55:58 -0800884 // ThreadBase virtuals
885 virtual void preExit();
886
Eric Laurent64667972016-03-30 18:19:46 -0700887 virtual bool keepWakeLock() const { return true; }
Andy Hungdae27702016-10-31 14:01:16 -0700888 virtual void acquireWakeLock_l() {
889 ThreadBase::acquireWakeLock_l();
890 mActiveTracks.updatePowerState(this, true /* force */);
891 }
Eric Laurent64667972016-03-30 18:19:46 -0700892
Eric Laurentb3f315a2021-07-13 15:09:05 +0200893 virtual void checkOutputStageEffects() {}
Eric Laurent68a40a82022-05-03 18:15:04 +0200894 virtual void setHalLatencyMode_l() {}
895
Eric Laurentb3f315a2021-07-13 15:09:05 +0200896
Andy Hung440901d2023-06-29 21:19:25 -0700897 void dumpInternals_l(int fd, const Vector<String16>& args) override;
898 void dumpTracks_l(int fd, const Vector<String16>& args) final;
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700899
Eric Laurent81784c32012-11-19 14:55:58 -0800900public:
901
Andy Hung440901d2023-06-29 21:19:25 -0700902 status_t initCheck() const final { return mOutput == nullptr ? NO_INIT : NO_ERROR; }
Eric Laurent81784c32012-11-19 14:55:58 -0800903
904 // return estimated latency in milliseconds, as reported by HAL
Andy Hung440901d2023-06-29 21:19:25 -0700905 uint32_t latency() const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800906 // same, but lock must already be held
Andy Hung440901d2023-06-29 21:19:25 -0700907 uint32_t latency_l() const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800908
Eric Laurent6acd1d42017-01-04 14:23:29 -0800909 // VolumeInterface
Andy Hung440901d2023-06-29 21:19:25 -0700910 void setMasterVolume(float value) final;
911 void setMasterBalance(float balance) override;
912 void setMasterMute(bool muted) final;
913 void setStreamVolume(audio_stream_type_t stream, float value) final;
914 void setStreamMute(audio_stream_type_t stream, bool muted) final;
915 float streamVolume(audio_stream_type_t stream) const final;
916 void setVolumeForOutput_l(float left, float right) const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800917
Andy Hung440901d2023-06-29 21:19:25 -0700918 sp<IAfTrack> createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -0700919 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -0800920 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700921 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -0800922 uint32_t *sampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -0800923 audio_format_t format,
924 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -0800925 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -0800926 size_t *pNotificationFrameCount,
927 uint32_t notificationsPerBuffer,
928 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -0800929 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -0800930 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -0700931 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700932 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +0000933 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -0800934 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800935 status_t *status /*non-NULL*/,
jiabinf6eb4c32020-02-25 14:06:25 -0800936 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200937 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +0000938 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +0000939 bool isBitPerfect,
940 audio_output_flags_t* afTrackFlags) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800941
Andy Hung87c693c2023-07-06 20:56:16 -0700942 bool isTrackActive(const sp<IAfTrack>& track) const final {
943 return mActiveTracks.indexOf(track) >= 0;
944 }
945
946 AudioStreamOut* getOutput_l() const final { return mOutput; }
Andy Hung440901d2023-06-29 21:19:25 -0700947 AudioStreamOut* getOutput() const final;
948 AudioStreamOut* clearOutput() final;
949 sp<StreamHalInterface> stream() const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800950
951 // a very large number of suspend() will eventually wraparound, but unlikely
Andy Hung440901d2023-06-29 21:19:25 -0700952 void suspend() final { (void) android_atomic_inc(&mSuspended); }
953 void restore() final
Eric Laurent81784c32012-11-19 14:55:58 -0800954 {
955 // if restore() is done without suspend(), get back into
956 // range so that the next suspend() will operate correctly
957 if (android_atomic_dec(&mSuspended) <= 0) {
958 android_atomic_release_store(0, &mSuspended);
959 }
960 }
Andy Hung440901d2023-06-29 21:19:25 -0700961 bool isSuspended() const final
Eric Laurent81784c32012-11-19 14:55:58 -0800962 { return android_atomic_acquire_load(&mSuspended) > 0; }
963
Andy Hung440901d2023-06-29 21:19:25 -0700964 String8 getParameters(const String8& keys);
965 void ioConfigChanged(audio_io_config_event_t event, pid_t pid = 0,
966 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final;
967 status_t getRenderPosition(uint32_t* halFrames, uint32_t* dspFrames) const final;
Andy Hung010a1a12014-03-13 13:57:33 -0700968 // Consider also removing and passing an explicit mMainBuffer initialization
Andy Hung8d31fd22023-06-26 19:20:57 -0700969 // parameter to AF::IAfTrack::Track().
Andy Hung440901d2023-06-29 21:19:25 -0700970 float* sinkBuffer() const final {
Andy Hung319587b2023-05-23 14:01:03 -0700971 return reinterpret_cast<float *>(mSinkBuffer); };
Eric Laurent81784c32012-11-19 14:55:58 -0800972
Andy Hung440901d2023-06-29 21:19:25 -0700973 void detachAuxEffect_l(int effectId) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800974
Andy Hung440901d2023-06-29 21:19:25 -0700975 status_t attachAuxEffect(const sp<IAfTrack>& track, int EffectId) final;
976 status_t attachAuxEffect_l(const sp<IAfTrack>& track, int EffectId) final;
977
978 status_t addEffectChain_l(const sp<IAfEffectChain>& chain) final;
979 size_t removeEffectChain_l(const sp<IAfEffectChain>& chain) final;
980 uint32_t hasAudioSession_l(audio_session_t sessionId) const final {
Andy Hungc3d62f92019-03-14 13:38:51 -0700981 return ThreadBase::hasAudioSession_l(sessionId, mTracks);
982 }
Andy Hung440901d2023-06-29 21:19:25 -0700983 product_strategy_t getStrategyForSession_l(audio_session_t sessionId) const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800984
985
Andy Hung440901d2023-06-29 21:19:25 -0700986 status_t setSyncEvent(const sp<audioflinger::SyncEvent>& event) final;
987 bool isValidSyncEvent(const sp<audioflinger::SyncEvent>& event) const final;
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700988
989 // called with AudioFlinger lock held
Andy Hung440901d2023-06-29 21:19:25 -0700990 bool invalidateTracks_l(audio_stream_type_t streamType) final;
991 bool invalidateTracks_l(std::set<audio_port_handle_t>& portIds) final;
992 void invalidateTracks(audio_stream_type_t streamType) override;
jiabinc44b3462022-12-08 12:52:31 -0800993 // Invalidate tracks by a set of port ids. The port id will be removed from
994 // the given set if the corresponding track is found and invalidated.
Andy Hung440901d2023-06-29 21:19:25 -0700995 void invalidateTracks(std::set<audio_port_handle_t>& portIds) override;
Eric Laurent81784c32012-11-19 14:55:58 -0800996
Andy Hung87c693c2023-07-06 20:56:16 -0700997 size_t frameCount() const final { return mNormalFrameCount; }
Glenn Kasten9b58f632013-07-16 11:37:48 -0700998
Andy Hung440901d2023-06-29 21:19:25 -0700999 audio_channel_mask_t mixerChannelMask() const final {
Eric Laurentf1f22e72021-07-13 14:04:14 +02001000 return mMixerChannelMask;
1001 }
1002
Andy Hung440901d2023-06-29 21:19:25 -07001003 status_t getTimestamp_l(AudioTimestamp& timestamp) final;
Eric Laurent83b88082014-06-20 18:31:16 -07001004
Andy Hung440901d2023-06-29 21:19:25 -07001005 void addPatchTrack(const sp<IAfPatchTrack>& track) final;
1006 void deletePatchTrack(const sp<IAfPatchTrack>& track) final;
Eric Laurent83b88082014-06-20 18:31:16 -07001007
Andy Hung440901d2023-06-29 21:19:25 -07001008 void toAudioPortConfig(struct audio_port_config* config) final;
Eric Laurentaccc1472013-09-20 09:36:34 -07001009
Andy Hung10cbff12017-02-21 17:30:14 -08001010 // Return the asynchronous signal wait time.
Andy Hung440901d2023-06-29 21:19:25 -07001011 int64_t computeWaitTimeNs_l() const override { return INT64_MAX; }
Andy Hung1bc088a2018-02-09 15:57:31 -08001012 // returns true if the track is allowed to be added to the thread.
Andy Hung440901d2023-06-29 21:19:25 -07001013 bool isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08001014 audio_channel_mask_t channelMask __unused,
1015 audio_format_t format __unused,
1016 audio_session_t sessionId __unused,
Andy Hung440901d2023-06-29 21:19:25 -07001017 uid_t uid) const override {
Andy Hung1bc088a2018-02-09 15:57:31 -08001018 return trackCountForUid_l(uid) < PlaybackThread::kMaxTracksPerUid
1019 && mTracks.size() < PlaybackThread::kMaxTracks;
1020 }
1021
Andy Hung440901d2023-06-29 21:19:25 -07001022 bool isTimestampCorrectionEnabled() const final {
jiabinc52b1ff2019-10-31 17:20:42 -07001023 return audio_is_output_devices(mTimestampCorrectedDevice)
1024 && outDeviceTypes().count(mTimestampCorrectedDevice) != 0;
Andy Hungc8fddf32018-08-08 18:32:37 -07001025 }
jiabinc52b1ff2019-10-31 17:20:42 -07001026
Andy Hung440901d2023-06-29 21:19:25 -07001027 bool isStreamInitialized() const final {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001028 return !(mOutput == nullptr || mOutput->stream == nullptr);
1029 }
1030
Andy Hung440901d2023-06-29 21:19:25 -07001031 audio_channel_mask_t hapticChannelMask() const final {
jiabineb3bda02020-06-30 14:07:03 -07001032 return mHapticChannelMask;
1033 }
Andy Hung87c693c2023-07-06 20:56:16 -07001034
1035 uint32_t hapticChannelCount() const final {
1036 return mHapticChannelCount;
1037 }
1038
Andy Hung440901d2023-06-29 21:19:25 -07001039 bool supportsHapticPlayback() const final {
jiabineb3bda02020-06-30 14:07:03 -07001040 return (mHapticChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE;
1041 }
1042
Andy Hung440901d2023-06-29 21:19:25 -07001043 void setDownStreamPatch(const struct audio_patch* patch) final {
Andy Hungc5007f82023-08-29 14:26:09 -07001044 std::lock_guard _l(mutex());
Eric Laurent74c38dc2020-12-23 18:19:44 +01001045 mDownStreamPatch = *patch;
1046 }
1047
Andy Hung440901d2023-06-29 21:19:25 -07001048 IAfTrack* getTrackById_l(audio_port_handle_t trackId) final;
jiabinf042b9b2021-05-07 23:46:28 +00001049
Andy Hung440901d2023-06-29 21:19:25 -07001050 bool hasMixer() const final {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001051 return mType == MIXER || mType == DUPLICATING || mType == SPATIALIZER;
Eric Laurentb3f315a2021-07-13 15:09:05 +02001052 }
Eric Laurent68a40a82022-05-03 18:15:04 +02001053
Andy Hung440901d2023-06-29 21:19:25 -07001054 status_t setRequestedLatencyMode(
1055 audio_latency_mode_t /* mode */) override { return INVALID_OPERATION; }
Eric Laurent68a40a82022-05-03 18:15:04 +02001056
Andy Hung440901d2023-06-29 21:19:25 -07001057 status_t getSupportedLatencyModes(
1058 std::vector<audio_latency_mode_t>* /* modes */) override {
Eric Laurent68a40a82022-05-03 18:15:04 +02001059 return INVALID_OPERATION;
1060 }
1061
Andy Hung440901d2023-06-29 21:19:25 -07001062 status_t setBluetoothVariableLatencyEnabled(bool /* enabled */) override{
Eric Laurentb0463942022-12-20 16:31:10 +01001063 return INVALID_OPERATION;
1064 }
Eric Laurent52057642022-12-16 11:45:07 +01001065
Andy Hung440901d2023-06-29 21:19:25 -07001066 void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) override;
1067 void stopMelComputation_l() override;
Vlad Popab042ee62022-10-20 18:05:00 +02001068
Andy Hung440901d2023-06-29 21:19:25 -07001069 void setStandby() final {
Andy Hungc5007f82023-08-29 14:26:09 -07001070 std::lock_guard _l(mutex());
Eric Laurent19952e12023-04-20 10:08:29 +02001071 setStandby_l();
1072 }
1073
Andy Hung440901d2023-06-29 21:19:25 -07001074 void setStandby_l() final {
Eric Laurent19952e12023-04-20 10:08:29 +02001075 mStandby = true;
1076 mHalStarted = false;
1077 mKernelPositionOnStandby =
1078 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
1079 }
1080
Andy Hung440901d2023-06-29 21:19:25 -07001081 bool waitForHalStart() final {
Andy Hungc5007f82023-08-29 14:26:09 -07001082 audio_utils::unique_lock _l(mutex());
Eric Laurent19952e12023-04-20 10:08:29 +02001083 static const nsecs_t kWaitHalTimeoutNs = seconds(2);
1084 nsecs_t endWaitTimetNs = systemTime() + kWaitHalTimeoutNs;
1085 while (!mHalStarted) {
1086 nsecs_t timeNs = systemTime();
1087 if (timeNs >= endWaitTimetNs) {
1088 break;
1089 }
1090 nsecs_t waitTimeLeftNs = endWaitTimetNs - timeNs;
Andy Hungc5007f82023-08-29 14:26:09 -07001091 mWaitHalStartCV.wait_for(_l, std::chrono::nanoseconds(waitTimeLeftNs));
Eric Laurent19952e12023-04-20 10:08:29 +02001092 }
1093 return mHalStarted;
1094 }
Eric Laurent81784c32012-11-19 14:55:58 -08001095protected:
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001096 // updated by readOutputParameters_l()
Glenn Kasten9b58f632013-07-16 11:37:48 -07001097 size_t mNormalFrameCount; // normal mixer and effects
1098
Andy Hung08fb1742015-05-31 23:22:10 -07001099 bool mThreadThrottle; // throttle the thread processing
Andy Hung40eb1a12015-06-18 13:42:02 -07001100 uint32_t mThreadThrottleTimeMs; // throttle time for MIXER threads
1101 uint32_t mThreadThrottleEndMs; // notify once per throttling
Andy Hung08fb1742015-05-31 23:22:10 -07001102 uint32_t mHalfBufferMs; // half the buffer size in milliseconds
1103
Andy Hung010a1a12014-03-13 13:57:33 -07001104 void* mSinkBuffer; // frame size aligned sink buffer
Eric Laurent81784c32012-11-19 14:55:58 -08001105
Andy Hung98ef9782014-03-04 14:46:50 -08001106 // TODO:
1107 // Rearrange the buffer info into a struct/class with
1108 // clear, copy, construction, destruction methods.
1109 //
1110 // mSinkBuffer also has associated with it:
1111 //
1112 // mSinkBufferSize: Sink Buffer Size
1113 // mFormat: Sink Buffer Format
1114
Andy Hung69aed5f2014-02-25 17:24:40 -08001115 // Mixer Buffer (mMixerBuffer*)
1116 //
1117 // In the case of floating point or multichannel data, which is not in the
1118 // sink format, it is required to accumulate in a higher precision or greater channel count
1119 // buffer before downmixing or data conversion to the sink buffer.
1120
1121 // Set to "true" to enable the Mixer Buffer otherwise mixer output goes to sink buffer.
1122 bool mMixerBufferEnabled;
1123
1124 // Storage, 32 byte aligned (may make this alignment a requirement later).
1125 // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
1126 void* mMixerBuffer;
1127
1128 // Size of mMixerBuffer in bytes: mNormalFrameCount * #channels * sampsize.
1129 size_t mMixerBufferSize;
1130
1131 // The audio format of mMixerBuffer. Set to AUDIO_FORMAT_PCM_(FLOAT|16_BIT) only.
1132 audio_format_t mMixerBufferFormat;
1133
1134 // An internal flag set to true by MixerThread::prepareTracks_l()
1135 // when mMixerBuffer contains valid data after mixing.
1136 bool mMixerBufferValid;
1137
Andy Hung98ef9782014-03-04 14:46:50 -08001138 // Effects Buffer (mEffectsBuffer*)
1139 //
1140 // In the case of effects data, which is not in the sink format,
1141 // it is required to accumulate in a different buffer before data conversion
1142 // to the sink buffer.
1143
1144 // Set to "true" to enable the Effects Buffer otherwise effects output goes to sink buffer.
1145 bool mEffectBufferEnabled;
1146
1147 // Storage, 32 byte aligned (may make this alignment a requirement later).
1148 // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
1149 void* mEffectBuffer;
1150
1151 // Size of mEffectsBuffer in bytes: mNormalFrameCount * #channels * sampsize.
1152 size_t mEffectBufferSize;
1153
1154 // The audio format of mEffectsBuffer. Set to AUDIO_FORMAT_PCM_16_BIT only.
1155 audio_format_t mEffectBufferFormat;
1156
1157 // An internal flag set to true by MixerThread::prepareTracks_l()
1158 // when mEffectsBuffer contains valid data after mixing.
1159 //
1160 // When this is set, all mixer data is routed into the effects buffer
1161 // for any processing (including output processing).
1162 bool mEffectBufferValid;
1163
jiabinc658e452022-10-21 20:52:21 +00001164 // Set to "true" to enable when data has already copied to sink
1165 bool mHasDataCopiedToSinkBuffer = false;
1166
Eric Laurentb62d0362021-10-26 17:40:18 +02001167 // Frame size aligned buffer used as input and output to all post processing effects
1168 // except the Spatializer in a SPATIALIZER thread. Non spatialized tracks are mixed into
1169 // this buffer so that post processing effects can be applied.
1170 void* mPostSpatializerBuffer = nullptr;
1171
1172 // Size of mPostSpatializerBuffer in bytes
1173 size_t mPostSpatializerBufferSize;
Eric Laurent39095982021-08-24 18:29:27 +02001174
1175
Eric Laurent81784c32012-11-19 14:55:58 -08001176 // suspend count, > 0 means suspended. While suspended, the thread continues to pull from
1177 // tracks and mix, but doesn't write to HAL. A2DP and SCO HAL implementations can't handle
1178 // concurrent use of both of them, so Audio Policy Service suspends one of the threads to
1179 // workaround that restriction.
1180 // 'volatile' means accessed via atomic operations and no lock.
1181 volatile int32_t mSuspended;
1182
Andy Hung818e7a32016-02-16 18:08:07 -08001183 int64_t mBytesWritten;
yucliu6cfb5932022-07-20 17:40:39 -07001184 std::atomic<int64_t> mFramesWritten; // not reset on standby
Dean Wheatley12473e92021-03-18 23:00:55 +11001185 int64_t mLastFramesWritten = -1; // track changes in timestamp
1186 // server frames written.
Andy Hung238fa3d2016-07-28 10:53:22 -07001187 int64_t mSuspendedFrames; // not reset on standby
jiabin245cdd92018-12-07 17:55:15 -08001188
1189 // mHapticChannelMask and mHapticChannelCount will only be valid when the thread support
1190 // haptic playback.
1191 audio_channel_mask_t mHapticChannelMask = AUDIO_CHANNEL_NONE;
1192 uint32_t mHapticChannelCount = 0;
Eric Laurentf1f22e72021-07-13 14:04:14 +02001193
1194 audio_channel_mask_t mMixerChannelMask = AUDIO_CHANNEL_NONE;
1195
Eric Laurent81784c32012-11-19 14:55:58 -08001196 // mMasterMute is in both PlaybackThread and in AudioFlinger. When a
1197 // PlaybackThread needs to find out if master-muted, it checks it's local
1198 // copy rather than the one in AudioFlinger. This optimization saves a lock.
1199 bool mMasterMute;
1200 void setMasterMute_l(bool muted) { mMasterMute = muted; }
Dean Wheatley12473e92021-03-18 23:00:55 +11001201
1202 auto discontinuityForStandbyOrFlush() const { // call on threadLoop or with lock.
1203 return ((mType == DIRECT && !audio_is_linear_pcm(mFormat))
1204 || mType == OFFLOAD)
1205 ? mTimestampVerifier.DISCONTINUITY_MODE_ZERO
1206 : mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS;
1207 }
1208
Andy Hung8d31fd22023-06-26 19:20:57 -07001209 ActiveTracks<IAfTrack> mActiveTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08001210
Eric Laurent81784c32012-11-19 14:55:58 -08001211 // Time to sleep between cycles when:
1212 virtual uint32_t activeSleepTimeUs() const; // mixer state MIXER_TRACKS_ENABLED
1213 virtual uint32_t idleSleepTimeUs() const = 0; // mixer state MIXER_IDLE
1214 virtual uint32_t suspendSleepTimeUs() const = 0; // audio policy manager suspended us
1215 // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write()
1216 // No sleep in standby mode; waits on a condition
1217
1218 // Code snippets that are temporarily lifted up out of threadLoop() until the merge
Andy Hung440901d2023-06-29 21:19:25 -07001219 virtual void checkSilentMode_l() final; // consider unification with MMapThread
Eric Laurent81784c32012-11-19 14:55:58 -08001220
1221 // Non-trivial for DUPLICATING only
1222 virtual void saveOutputTracks() { }
1223 virtual void clearOutputTracks() { }
1224
1225 // Cache various calculated values, at threadLoop() entry and after a parameter change
1226 virtual void cacheParameters_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02001227 void setCheckOutputStageEffects() override {
1228 mCheckOutputStageEffects.store(true);
1229 }
Eric Laurent81784c32012-11-19 14:55:58 -08001230
1231 virtual uint32_t correctLatency_l(uint32_t latency) const;
1232
Eric Laurent1c333e22014-05-20 10:48:17 -07001233 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
1234 audio_patch_handle_t *handle);
1235 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle);
1236
Andy Hung87c693c2023-07-06 20:56:16 -07001237 bool usesHwAvSync() const final { return mType == DIRECT && mOutput != nullptr
Phil Burk6fc2a7c2015-04-30 16:08:10 -07001238 && mHwSupportsPause
1239 && (mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC); }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08001240
Andy Hung1bc088a2018-02-09 15:57:31 -08001241 uint32_t trackCountForUid_l(uid_t uid) const;
Eric Laurentad7dd962016-09-22 12:38:37 -07001242
jiabineb3bda02020-06-30 14:07:03 -07001243 void invalidateTracksForAudioSession_l(
Andy Hung440901d2023-06-29 21:19:25 -07001244 audio_session_t sessionId) const override {
jiabineb3bda02020-06-30 14:07:03 -07001245 ThreadBase::invalidateTracksForAudioSession_l(sessionId, mTracks);
1246 }
1247
Mikhail Naganovbf493082017-04-17 17:37:12 -07001248 DISALLOW_COPY_AND_ASSIGN(PlaybackThread);
Eric Laurent81784c32012-11-19 14:55:58 -08001249
Andy Hung87c693c2023-07-06 20:56:16 -07001250 status_t addTrack_l(const sp<IAfTrack>& track) final;
1251 bool destroyTrack_l(const sp<IAfTrack>& track) final;
1252
Andy Hung8d31fd22023-06-26 19:20:57 -07001253 void removeTrack_l(const sp<IAfTrack>& track);
Eric Laurent81784c32012-11-19 14:55:58 -08001254
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001255 void readOutputParameters_l();
Vlad Popa7e81cea2023-01-19 16:34:16 +01001256 MetadataUpdate updateMetadata_l() final;
Kevin Rocardc86a7f72018-04-03 09:00:09 -07001257 virtual void sendMetadataToBackend_l(const StreamOutHalInterface::SourceMetadata& metadata);
Eric Laurent81784c32012-11-19 14:55:58 -08001258
Dean Wheatley12473e92021-03-18 23:00:55 +11001259 void collectTimestamps_l();
1260
Andy Hungc0691382018-09-12 18:01:57 -07001261 // The Tracks class manages tracks added and removed from the Thread.
Andy Hung1bc088a2018-02-09 15:57:31 -08001262 template <typename T>
1263 class Tracks {
1264 public:
Andy Hung920f6572022-10-06 12:09:49 -07001265 explicit Tracks(bool saveDeletedTrackIds) :
Andy Hungc0691382018-09-12 18:01:57 -07001266 mSaveDeletedTrackIds(saveDeletedTrackIds) { }
Andy Hung1bc088a2018-02-09 15:57:31 -08001267
1268 // SortedVector methods
Andy Hungc0691382018-09-12 18:01:57 -07001269 ssize_t add(const sp<T> &track) {
1270 const ssize_t index = mTracks.add(track);
1271 LOG_ALWAYS_FATAL_IF(index < 0, "cannot add track");
1272 return index;
1273 }
Andy Hung1bc088a2018-02-09 15:57:31 -08001274 ssize_t remove(const sp<T> &track);
1275 size_t size() const {
1276 return mTracks.size();
1277 }
1278 bool isEmpty() const {
1279 return mTracks.isEmpty();
1280 }
1281 ssize_t indexOf(const sp<T> &item) {
1282 return mTracks.indexOf(item);
1283 }
1284 sp<T> operator[](size_t index) const {
1285 return mTracks[index];
1286 }
1287 typename SortedVector<sp<T>>::iterator begin() {
1288 return mTracks.begin();
1289 }
1290 typename SortedVector<sp<T>>::iterator end() {
1291 return mTracks.end();
1292 }
1293
Andy Hung920f6572022-10-06 12:09:49 -07001294 size_t processDeletedTrackIds(const std::function<void(int)>& f) {
Andy Hungc0691382018-09-12 18:01:57 -07001295 for (const int trackId : mDeletedTrackIds) {
1296 f(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08001297 }
Andy Hungc0691382018-09-12 18:01:57 -07001298 return mDeletedTrackIds.size();
Andy Hung1bc088a2018-02-09 15:57:31 -08001299 }
1300
Andy Hungc0691382018-09-12 18:01:57 -07001301 void clearDeletedTrackIds() { mDeletedTrackIds.clear(); }
Andy Hung1bc088a2018-02-09 15:57:31 -08001302
1303 private:
Andy Hungc0691382018-09-12 18:01:57 -07001304 // Tracks pending deletion for MIXER type threads
1305 const bool mSaveDeletedTrackIds; // true to enable tracking
1306 std::set<int> mDeletedTrackIds;
Andy Hung1bc088a2018-02-09 15:57:31 -08001307
1308 SortedVector<sp<T>> mTracks; // wrapped SortedVector.
1309 };
1310
Andy Hung8d31fd22023-06-26 19:20:57 -07001311 Tracks<IAfTrack> mTracks;
Andy Hung1bc088a2018-02-09 15:57:31 -08001312
Eric Laurent223fd5c2014-11-11 13:43:36 -08001313 stream_type_t mStreamTypes[AUDIO_STREAM_CNT];
Andy Hungee58e4a2023-07-07 13:47:37 -07001314
Eric Laurent81784c32012-11-19 14:55:58 -08001315 AudioStreamOut *mOutput;
1316
1317 float mMasterVolume;
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001318 std::atomic<float> mMasterBalance{};
1319 audio_utils::Balance mBalance;
Eric Laurent81784c32012-11-19 14:55:58 -08001320 int mNumWrites;
1321 int mNumDelayedWrites;
1322 bool mInWrite;
1323
1324 // FIXME rename these former local variables of threadLoop to standard "m" names
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001325 nsecs_t mStandbyTimeNs;
Andy Hung25c2dac2014-02-27 14:56:00 -08001326 size_t mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001327
1328 // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l()
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001329 uint32_t mActiveSleepTimeUs;
1330 uint32_t mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08001331
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001332 uint32_t mSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08001333
1334 // mixer status returned by prepareTracks_l()
1335 mixer_state mMixerStatus; // current cycle
1336 // previous cycle when in prepareTracks_l()
1337 mixer_state mMixerStatusIgnoringFastTracks;
1338 // FIXME or a separate ready state per track
1339
1340 // FIXME move these declarations into the specific sub-class that needs them
1341 // MIXER only
1342 uint32_t sleepTimeShift;
1343
1344 // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001345 nsecs_t mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08001346
1347 // MIXER only
1348 nsecs_t maxPeriod;
1349
1350 // DUPLICATING only
1351 uint32_t writeFrames;
1352
Eric Laurentbfb1b832013-01-07 09:53:42 -08001353 size_t mBytesRemaining;
1354 size_t mCurrentWriteLength;
1355 bool mUseAsyncWrite;
Eric Laurent3b4529e2013-09-05 18:09:19 -07001356 // mWriteAckSequence contains current write sequence on bits 31-1. The write sequence is
1357 // incremented each time a write(), a flush() or a standby() occurs.
1358 // Bit 0 is set when a write blocks and indicates a callback is expected.
1359 // Bit 0 is reset by the async callback thread calling resetWriteBlocked(). Out of sequence
1360 // callbacks are ignored.
1361 uint32_t mWriteAckSequence;
1362 // mDrainSequence contains current drain sequence on bits 31-1. The drain sequence is
1363 // incremented each time a drain is requested or a flush() or standby() occurs.
1364 // Bit 0 is set when the drain() command is called at the HAL and indicates a callback is
1365 // expected.
1366 // Bit 0 is reset by the async callback thread calling resetDraining(). Out of sequence
1367 // callbacks are ignored.
1368 uint32_t mDrainSequence;
Andy Hungee58e4a2023-07-07 13:47:37 -07001369
Eric Laurentbfb1b832013-01-07 09:53:42 -08001370 sp<AsyncCallbackThread> mCallbackThread;
1371
Andy Hungc5007f82023-08-29 14:26:09 -07001372 audio_utils::mutex& audioTrackCbMutex() const { return mAudioTrackCbMutex; }
1373 mutable audio_utils::mutex mAudioTrackCbMutex;
jiabinf6eb4c32020-02-25 14:06:25 -08001374 // Record of IAudioTrackCallback
Andy Hung8d31fd22023-06-26 19:20:57 -07001375 std::map<sp<IAfTrack>, sp<media::IAudioTrackCallback>> mAudioTrackCallbacks;
jiabinf6eb4c32020-02-25 14:06:25 -08001376
Eric Laurent81784c32012-11-19 14:55:58 -08001377 // The HAL output sink is treated as non-blocking, but current implementation is blocking
1378 sp<NBAIO_Sink> mOutputSink;
1379 // If a fast mixer is present, the blocking pipe sink, otherwise clear
1380 sp<NBAIO_Sink> mPipeSink;
1381 // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink
1382 sp<NBAIO_Sink> mNormalSink;
Andy Hungee58e4a2023-07-07 13:47:37 -07001383
Eric Laurent81784c32012-11-19 14:55:58 -08001384 uint32_t mScreenState; // cached copy of gScreenState
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07001385 // TODO: add comment and adjust size as needed
Glenn Kasteneef598c2017-04-03 14:41:13 -07001386 static const size_t kFastMixerLogSize = 8 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -08001387 sp<NBLog::Writer> mFastMixerNBLogWriter;
Andy Hung2148bf02016-11-28 19:01:02 -08001388
Dean Wheatley30d28422018-11-06 10:27:40 +11001389 // Downstream patch latency, available if mDownstreamLatencyStatMs.getN() > 0.
1390 audio_utils::Statistics<double> mDownstreamLatencyStatMs{0.999};
Andy Hung2148bf02016-11-28 19:01:02 -08001391
Eric Laurent19952e12023-04-20 10:08:29 +02001392 // output stream start detection based on render position returned by the kernel
1393 // condition signalled when the output stream has started
Andy Hungc5007f82023-08-29 14:26:09 -07001394 audio_utils::condition_variable mWaitHalStartCV;
Eric Laurent19952e12023-04-20 10:08:29 +02001395 // true when the output stream render position has moved, reset to false in standby
1396 bool mHalStarted = false;
1397 // last kernel render position saved when entering standby
1398 int64_t mKernelPositionOnStandby = 0;
1399
Eric Laurent81784c32012-11-19 14:55:58 -08001400public:
Andy Hung440901d2023-06-29 21:19:25 -07001401 FastTrackUnderruns getFastTrackUnderruns(size_t /* fastIndex */) const override
1402 { return {}; }
1403 const std::atomic<int64_t>& framesWritten() const final { return mFramesWritten; }
Eric Laurent81784c32012-11-19 14:55:58 -08001404
1405protected:
1406 // accessed by both binder threads and within threadLoop(), lock on mutex needed
Andy Hung87c693c2023-07-06 20:56:16 -07001407 uint32_t& fastTrackAvailMask_l() final { return mFastTrackAvailMask; }
1408 uint32_t mFastTrackAvailMask; // bit i set if fast track [i] is available
Eric Laurentd1f69b02014-12-15 14:33:13 -08001409 bool mHwSupportsPause;
1410 bool mHwPaused;
1411 bool mFlushPending;
Eric Laurent7c29ec92017-09-20 17:54:22 -07001412 // volumes last sent to audio HAL with stream->setVolume()
1413 float mLeftVolFloat;
1414 float mRightVolFloat;
Eric Laurent74c38dc2020-12-23 18:19:44 +01001415
1416 // audio patch used by the downstream software patch.
1417 // Only used if ThreadBase::mIsMsdDevice is true.
1418 struct audio_patch mDownStreamPatch;
Eric Laurentb3f315a2021-07-13 15:09:05 +02001419
1420 std::atomic_bool mCheckOutputStageEffects{};
ziyangch8f194f12021-12-01 13:48:04 -08001421
ziyangch8f194f12021-12-01 13:48:04 -08001422
Brian Lindahl65e90012022-07-27 18:01:07 +02001423 // Provides periodic checking for timestamp advancement for underrun detection.
1424 class IsTimestampAdvancing {
1425 public:
1426 // The timestamp will not be checked any faster than the specified time.
Andy Hung920f6572022-10-06 12:09:49 -07001427 explicit IsTimestampAdvancing(nsecs_t minimumTimeBetweenChecksNs)
Brian Lindahl65e90012022-07-27 18:01:07 +02001428 : mMinimumTimeBetweenChecksNs(minimumTimeBetweenChecksNs)
1429 {
1430 clear();
1431 }
1432 // Check if the presentation position has advanced in the last periodic time.
1433 bool check(AudioStreamOut * output);
1434 // Clear the internal state when the playback state changes for the output
1435 // stream.
1436 void clear();
1437 private:
1438 // The minimum time between timestamp checks.
1439 const nsecs_t mMinimumTimeBetweenChecksNs;
1440 // Add differential check on the timestamps to see if there is a change in the
1441 // timestamp frame position between the last call to check.
1442 uint64_t mPreviousPosition;
1443 // The time at which the last check occurred, to ensure we don't check too
1444 // frequently, giving the Audio HAL enough time to update its timestamps.
1445 nsecs_t mPreviousNs;
1446 // The valued is latched so we don't check timestamps too frequently.
1447 bool mLatchedValue;
1448 };
1449 IsTimestampAdvancing mIsTimestampAdvancing;
ziyangch8f194f12021-12-01 13:48:04 -08001450
Brian Lindahl65e90012022-07-27 18:01:07 +02001451 virtual void flushHw_l() {
1452 mIsTimestampAdvancing.clear();
1453 }
Eric Laurent81784c32012-11-19 14:55:58 -08001454};
1455
Eric Laurentb0463942022-12-20 16:31:10 +01001456class MixerThread : public PlaybackThread,
1457 public StreamOutHalInterfaceLatencyModeCallback {
Eric Laurent81784c32012-11-19 14:55:58 -08001458public:
Andy Hung583043b2023-07-17 17:05:00 -07001459 MixerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08001460 AudioStreamOut* output,
1461 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001462 bool systemReady,
Eric Laurentf1f22e72021-07-13 14:04:14 +02001463 type_t type = MIXER,
1464 audio_config_base_t *mixerConfig = nullptr);
Andy Hung440901d2023-06-29 21:19:25 -07001465 ~MixerThread() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001466
Eric Laurentb0463942022-12-20 16:31:10 +01001467 // RefBase
Andy Hung440901d2023-06-29 21:19:25 -07001468 void onFirstRef() override;
Eric Laurentb0463942022-12-20 16:31:10 +01001469
1470 // StreamOutHalInterfaceLatencyModeCallback
1471 void onRecommendedLatencyModeChanged(
Andy Hung440901d2023-06-29 21:19:25 -07001472 std::vector<audio_latency_mode_t> modes) final;
Eric Laurentb0463942022-12-20 16:31:10 +01001473
Eric Laurent81784c32012-11-19 14:55:58 -08001474 // Thread virtuals
1475
Andy Hung440901d2023-06-29 21:19:25 -07001476 bool checkForNewParameter_l(const String8& keyValuePair, status_t& status) final;
Eric Laurent81784c32012-11-19 14:55:58 -08001477
Andy Hung440901d2023-06-29 21:19:25 -07001478 bool isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08001479 audio_channel_mask_t channelMask, audio_format_t format,
Andy Hung440901d2023-06-29 21:19:25 -07001480 audio_session_t sessionId, uid_t uid) const final;
Eric Laurent81784c32012-11-19 14:55:58 -08001481protected:
Andy Hung440901d2023-06-29 21:19:25 -07001482 mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove) override;
1483 uint32_t idleSleepTimeUs() const final;
1484 uint32_t suspendSleepTimeUs() const final;
1485 void cacheParameters_l() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001486
Andy Hung440901d2023-06-29 21:19:25 -07001487 void acquireWakeLock_l() final {
Andy Hungdae27702016-10-31 14:01:16 -07001488 PlaybackThread::acquireWakeLock_l();
Andy Hung818e7a32016-02-16 18:08:07 -08001489 if (hasFastMixer()) {
1490 mFastMixer->setBoottimeOffset(
1491 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME]);
1492 }
1493 }
1494
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001495 void dumpInternals_l(int fd, const Vector<String16>& args) override;
1496
Eric Laurent81784c32012-11-19 14:55:58 -08001497 // threadLoop snippets
Andy Hung440901d2023-06-29 21:19:25 -07001498 ssize_t threadLoop_write() override;
1499 void threadLoop_standby() override;
1500 void threadLoop_mix() override;
1501 void threadLoop_sleepTime() override;
1502 uint32_t correctLatency_l(uint32_t latency) const final;
Eric Laurent81784c32012-11-19 14:55:58 -08001503
Andy Hung440901d2023-06-29 21:19:25 -07001504 status_t createAudioPatch_l(
1505 const struct audio_patch* patch, audio_patch_handle_t* handle) final;
1506 status_t releaseAudioPatch_l(const audio_patch_handle_t handle) final;
Eric Laurent054d9d32015-04-24 08:48:48 -07001507
Eric Laurent81784c32012-11-19 14:55:58 -08001508 AudioMixer* mAudioMixer; // normal mixer
Eric Laurentb0463942022-12-20 16:31:10 +01001509
1510 // Support low latency mode by default as unless explicitly indicated by the audio HAL
1511 // we assume the audio path is compatible with the head tracking latency requirements
1512 std::vector<audio_latency_mode_t> mSupportedLatencyModes = {AUDIO_LATENCY_MODE_LOW};
1513 // default to invalid value to force first update to the audio HAL
1514 audio_latency_mode_t mSetLatencyMode =
1515 (audio_latency_mode_t)AUDIO_LATENCY_MODE_INVALID;
1516
1517 // Bluetooth Variable latency control logic is enabled or disabled for this thread
1518 std::atomic_bool mBluetoothLatencyModesEnabled;
1519
Eric Laurent81784c32012-11-19 14:55:58 -08001520private:
1521 // one-time initialization, no locks required
Glenn Kasten4d23ca32014-05-13 10:39:51 -07001522 sp<FastMixer> mFastMixer; // non-0 if there is also a fast mixer
Eric Laurent81784c32012-11-19 14:55:58 -08001523 sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread
1524
1525 // contents are not guaranteed to be consistent, no locks required
1526 FastMixerDumpState mFastMixerDumpState;
1527#ifdef STATE_QUEUE_DUMP
1528 StateQueueObserverDump mStateQueueObserverDump;
1529 StateQueueMutatorDump mStateQueueMutatorDump;
1530#endif
1531 AudioWatchdogDump mAudioWatchdogDump;
1532
1533 // accessible only within the threadLoop(), no locks required
1534 // mFastMixer->sq() // for mutating and pushing state
1535 int32_t mFastMixerFutex; // for cold idle
1536
Andy Hung2ddee192015-12-18 17:34:44 -08001537 std::atomic_bool mMasterMono;
Eric Laurent81784c32012-11-19 14:55:58 -08001538public:
Glenn Kasten4d23ca32014-05-13 10:39:51 -07001539 virtual bool hasFastMixer() const { return mFastMixer != 0; }
Eric Laurent81784c32012-11-19 14:55:58 -08001540 virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const {
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001541 ALOG_ASSERT(fastIndex < FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08001542 return mFastMixerDumpState.mTracks[fastIndex].mUnderruns;
1543 }
Eric Laurent83b88082014-06-20 18:31:16 -07001544
Andy Hung1c86ebe2018-05-29 20:29:08 -07001545 status_t threadloop_getHalTimestamp_l(
1546 ExtendedTimestamp *timestamp) const override {
1547 if (mNormalSink.get() != nullptr) {
1548 return mNormalSink->getTimestamp(*timestamp);
1549 }
1550 return INVALID_OPERATION;
1551 }
1552
Eric Laurentb0463942022-12-20 16:31:10 +01001553 status_t getSupportedLatencyModes(
1554 std::vector<audio_latency_mode_t>* modes) override;
1555
1556 status_t setBluetoothVariableLatencyEnabled(bool enabled) override;
1557
Andy Hung2ddee192015-12-18 17:34:44 -08001558protected:
1559 virtual void setMasterMono_l(bool mono) {
1560 mMasterMono.store(mono);
1561 if (mFastMixer != nullptr) { /* hasFastMixer() */
1562 mFastMixer->setMasterMono(mMasterMono);
1563 }
1564 }
1565 // the FastMixer performs mono blend if it exists.
Glenn Kasten03c48d52016-01-27 17:25:17 -08001566 // Blending with limiter is not idempotent,
1567 // and blending without limiter is idempotent but inefficient to do twice.
Andy Hung2ddee192015-12-18 17:34:44 -08001568 virtual bool requireMonoBlend() { return mMasterMono.load() && !hasFastMixer(); }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001569
1570 void setMasterBalance(float balance) override {
1571 mMasterBalance.store(balance);
1572 if (hasFastMixer()) {
1573 mFastMixer->setMasterBalance(balance);
1574 }
1575 }
Eric Laurentb0463942022-12-20 16:31:10 +01001576
1577 void updateHalSupportedLatencyModes_l();
1578 void onHalLatencyModesChanged_l() override;
1579 void setHalLatencyMode_l() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001580};
1581
Andy Hung87c693c2023-07-06 20:56:16 -07001582class DirectOutputThread : public PlaybackThread, public virtual IAfDirectOutputThread {
Eric Laurent81784c32012-11-19 14:55:58 -08001583public:
1584
Andy Hung87c693c2023-07-06 20:56:16 -07001585 sp<IAfDirectOutputThread> asIAfDirectOutputThread() final {
1586 return sp<IAfDirectOutputThread>::fromExisting(this);
1587 }
1588
Andy Hung583043b2023-07-17 17:05:00 -07001589 DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Gareth Fennb18c1a32022-10-05 13:42:36 -07001590 audio_io_handle_t id, bool systemReady,
1591 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07001592 : DirectOutputThread(afThreadCallback, output, id, DIRECT, systemReady, offloadInfo) { }
Andy Hung48f59ed2019-01-28 15:06:59 -08001593
Eric Laurent81784c32012-11-19 14:55:58 -08001594 virtual ~DirectOutputThread();
1595
Andy Hung87c693c2023-07-06 20:56:16 -07001596 status_t selectPresentation(int presentationId, int programId) final;
Mikhail Naganovac917ac2018-11-28 14:03:52 -08001597
Eric Laurent81784c32012-11-19 14:55:58 -08001598 // Thread virtuals
1599
Eric Laurent10351942014-05-08 18:49:52 -07001600 virtual bool checkForNewParameter_l(const String8& keyValuePair,
1601 status_t& status);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001602
ziyangch8f194f12021-12-01 13:48:04 -08001603 void flushHw_l() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001604
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001605 void setMasterBalance(float balance) override;
1606
Eric Laurent81784c32012-11-19 14:55:58 -08001607protected:
Eric Laurent81784c32012-11-19 14:55:58 -08001608 virtual uint32_t activeSleepTimeUs() const;
1609 virtual uint32_t idleSleepTimeUs() const;
1610 virtual uint32_t suspendSleepTimeUs() const;
1611 virtual void cacheParameters_l();
1612
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001613 void dumpInternals_l(int fd, const Vector<String16>& args) override;
1614
Eric Laurent81784c32012-11-19 14:55:58 -08001615 // threadLoop snippets
Andy Hung8d31fd22023-06-26 19:20:57 -07001616 virtual mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08001617 virtual void threadLoop_mix();
1618 virtual void threadLoop_sleepTime();
Eric Laurentd1f69b02014-12-15 14:33:13 -08001619 virtual void threadLoop_exit();
1620 virtual bool shouldStandby_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001621
Phil Burk43b4dcc2015-06-09 16:53:44 -07001622 virtual void onAddNewTrack_l();
1623
Gareth Fennb18c1a32022-10-05 13:42:36 -07001624 const audio_offload_info_t mOffloadInfo;
Andy Hung398ffa22022-12-13 19:19:53 -08001625
1626 audioflinger::MonotonicFrameCounter mMonotonicFrameCounter; // for VolumeShaper
Andy Hung48f59ed2019-01-28 15:06:59 -08001627 bool mVolumeShaperActive = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001628
Andy Hung583043b2023-07-17 17:05:00 -07001629 DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Gareth Fennb18c1a32022-10-05 13:42:36 -07001630 audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
1631 const audio_offload_info_t& offloadInfo);
Andy Hung8d31fd22023-06-26 19:20:57 -07001632 void processVolume_l(IAfTrack *track, bool lastTrack);
Gareth Fennb18c1a32022-10-05 13:42:36 -07001633 bool isTunerStream() const { return (mOffloadInfo.content_id > 0); }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001634
Eric Laurent81784c32012-11-19 14:55:58 -08001635 // prepareTracks_l() tells threadLoop_mix() the name of the single active track
Andy Hung8d31fd22023-06-26 19:20:57 -07001636 sp<IAfTrack> mActiveTrack;
Phil Burk43b4dcc2015-06-09 16:53:44 -07001637
Andy Hung8d31fd22023-06-26 19:20:57 -07001638 wp<IAfTrack> mPreviousTrack; // used to detect track switch
Phil Burk43b4dcc2015-06-09 16:53:44 -07001639
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001640 // This must be initialized for initial condition of mMasterBalance = 0 (disabled).
1641 float mMasterBalanceLeft = 1.f;
1642 float mMasterBalanceRight = 1.f;
1643
Eric Laurent81784c32012-11-19 14:55:58 -08001644public:
1645 virtual bool hasFastMixer() const { return false; }
Andy Hung10cbff12017-02-21 17:30:14 -08001646
1647 virtual int64_t computeWaitTimeNs_l() const override;
Andy Hungf3234512018-07-03 14:51:47 -07001648
1649 status_t threadloop_getHalTimestamp_l(ExtendedTimestamp *timestamp) const override {
1650 // For DIRECT and OFFLOAD threads, query the output sink directly.
1651 if (mOutput != nullptr) {
1652 uint64_t uposition64;
1653 struct timespec time;
1654 if (mOutput->getPresentationPosition(
1655 &uposition64, &time) == OK) {
1656 timestamp->mPosition[ExtendedTimestamp::LOCATION_KERNEL]
1657 = (int64_t)uposition64;
1658 timestamp->mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
1659 = audio_utils_ns_from_timespec(&time);
1660 return NO_ERROR;
1661 }
1662 }
1663 return INVALID_OPERATION;
1664 }
Eric Laurent81784c32012-11-19 14:55:58 -08001665};
1666
Eric Laurentbfb1b832013-01-07 09:53:42 -08001667class OffloadThread : public DirectOutputThread {
1668public:
1669
Andy Hung583043b2023-07-17 17:05:00 -07001670 OffloadThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Gareth Fennb18c1a32022-10-05 13:42:36 -07001671 audio_io_handle_t id, bool systemReady,
1672 const audio_offload_info_t& offloadInfo);
Eric Laurent6a51d7e2013-10-17 18:59:26 -07001673 virtual ~OffloadThread() {};
ziyangch8f194f12021-12-01 13:48:04 -08001674 void flushHw_l() override;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001675
1676protected:
1677 // threadLoop snippets
Andy Hung8d31fd22023-06-26 19:20:57 -07001678 virtual mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001679 virtual void threadLoop_exit();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001680
1681 virtual bool waitingAsyncCallback();
1682 virtual bool waitingAsyncCallback_l();
Haynes Mathew George05317d22016-05-03 16:34:26 -07001683 virtual void invalidateTracks(audio_stream_type_t streamType);
jiabinc44b3462022-12-08 12:52:31 -08001684 void invalidateTracks(std::set<audio_port_handle_t>& portIds) override;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001685
Eric Laurentde0613d2016-07-22 18:19:11 -07001686 virtual bool keepWakeLock() const { return (mKeepWakeLock || (mDrainSequence & 1)); }
Eric Laurent64667972016-03-30 18:19:46 -07001687
Eric Laurentbfb1b832013-01-07 09:53:42 -08001688private:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001689 size_t mPausedWriteLength; // length in bytes of write interrupted by pause
1690 size_t mPausedBytesRemaining; // bytes still waiting in mixbuffer after resume
Eric Laurent64667972016-03-30 18:19:46 -07001691 bool mKeepWakeLock; // keep wake lock while waiting for write callback
Eric Laurentbfb1b832013-01-07 09:53:42 -08001692};
1693
1694class AsyncCallbackThread : public Thread {
1695public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001696 explicit AsyncCallbackThread(const wp<PlaybackThread>& playbackThread);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001697
Eric Laurentbfb1b832013-01-07 09:53:42 -08001698 // Thread virtuals
1699 virtual bool threadLoop();
1700
1701 // RefBase
1702 virtual void onFirstRef();
1703
1704 void exit();
Eric Laurent3b4529e2013-09-05 18:09:19 -07001705 void setWriteBlocked(uint32_t sequence);
1706 void resetWriteBlocked();
1707 void setDraining(uint32_t sequence);
1708 void resetDraining();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07001709 void setAsyncError();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001710
1711private:
Eric Laurent4de95592013-09-26 15:28:21 -07001712 const wp<PlaybackThread> mPlaybackThread;
Eric Laurent3b4529e2013-09-05 18:09:19 -07001713 // mWriteAckSequence corresponds to the last write sequence passed by the offload thread via
1714 // setWriteBlocked(). The sequence is shifted one bit to the left and the lsb is used
1715 // to indicate that the callback has been received via resetWriteBlocked()
Eric Laurent4de95592013-09-26 15:28:21 -07001716 uint32_t mWriteAckSequence;
Eric Laurent3b4529e2013-09-05 18:09:19 -07001717 // mDrainSequence corresponds to the last drain sequence passed by the offload thread via
1718 // setDraining(). The sequence is shifted one bit to the left and the lsb is used
1719 // to indicate that the callback has been received via resetDraining()
Eric Laurent4de95592013-09-26 15:28:21 -07001720 uint32_t mDrainSequence;
Andy Hungc5007f82023-08-29 14:26:09 -07001721 audio_utils::condition_variable mWaitWorkCV;
1722 mutable audio_utils::mutex mMutex;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07001723 bool mAsyncError;
Andy Hungc5007f82023-08-29 14:26:09 -07001724
1725 audio_utils::mutex& mutex() const { return mMutex; }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001726};
1727
Andy Hung87c693c2023-07-06 20:56:16 -07001728class DuplicatingThread : public MixerThread, public IAfDuplicatingThread {
Eric Laurent81784c32012-11-19 14:55:58 -08001729public:
Andy Hung583043b2023-07-17 17:05:00 -07001730 DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
1731 IAfPlaybackThread* mainThread,
Eric Laurent72e3f392015-05-20 14:43:50 -07001732 audio_io_handle_t id, bool systemReady);
Andy Hung87c693c2023-07-06 20:56:16 -07001733 ~DuplicatingThread() override;
1734
1735 sp<IAfDuplicatingThread> asIAfDuplicatingThread() final {
1736 return sp<IAfDuplicatingThread>::fromExisting(this);
1737 }
Eric Laurent81784c32012-11-19 14:55:58 -08001738
1739 // Thread virtuals
Andy Hung87c693c2023-07-06 20:56:16 -07001740 void addOutputTrack(IAfPlaybackThread* thread) final;
1741 void removeOutputTrack(IAfPlaybackThread* thread) final;
1742 uint32_t waitTimeMs() const final { return mWaitTimeMs; }
Kevin Rocard069c2712018-03-29 19:09:14 -07001743
Kevin Rocardc86a7f72018-04-03 09:00:09 -07001744 void sendMetadataToBackend_l(
1745 const StreamOutHalInterface::SourceMetadata& metadata) override;
Eric Laurent81784c32012-11-19 14:55:58 -08001746protected:
1747 virtual uint32_t activeSleepTimeUs() const;
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001748 void dumpInternals_l(int fd, const Vector<String16>& args) override;
Eric Laurent81784c32012-11-19 14:55:58 -08001749
1750private:
Andy Hung920f6572022-10-06 12:09:49 -07001751 bool outputsReady();
Eric Laurent81784c32012-11-19 14:55:58 -08001752protected:
1753 // threadLoop snippets
1754 virtual void threadLoop_mix();
1755 virtual void threadLoop_sleepTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001756 virtual ssize_t threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08001757 virtual void threadLoop_standby();
1758 virtual void cacheParameters_l();
1759
1760private:
1761 // called from threadLoop, addOutputTrack, removeOutputTrack
1762 virtual void updateWaitTime_l();
1763protected:
1764 virtual void saveOutputTracks();
1765 virtual void clearOutputTracks();
1766private:
1767
1768 uint32_t mWaitTimeMs;
Andy Hung8d31fd22023-06-26 19:20:57 -07001769 SortedVector <sp<IAfOutputTrack>> outputTracks;
1770 SortedVector <sp<IAfOutputTrack>> mOutputTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08001771public:
1772 virtual bool hasFastMixer() const { return false; }
Andy Hung1c86ebe2018-05-29 20:29:08 -07001773 status_t threadloop_getHalTimestamp_l(
1774 ExtendedTimestamp *timestamp) const override {
1775 if (mOutputTracks.size() > 0) {
1776 // forward the first OutputTrack's kernel information for timestamp.
1777 const ExtendedTimestamp trackTimestamp =
1778 mOutputTracks[0]->getClientProxyTimestamp();
1779 if (trackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] > 0) {
1780 timestamp->mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
1781 trackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
1782 timestamp->mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
1783 trackTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
1784 return OK; // discard server timestamp - that's ignored.
1785 }
1786 }
1787 return INVALID_OPERATION;
1788 }
Eric Laurent81784c32012-11-19 14:55:58 -08001789};
1790
Eric Laurentb0463942022-12-20 16:31:10 +01001791class SpatializerThread : public MixerThread {
Eric Laurentb3f315a2021-07-13 15:09:05 +02001792public:
Andy Hung583043b2023-07-17 17:05:00 -07001793 SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02001794 AudioStreamOut* output,
1795 audio_io_handle_t id,
1796 bool systemReady,
1797 audio_config_base_t *mixerConfig);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001798
Andy Hung440901d2023-06-29 21:19:25 -07001799 bool hasFastMixer() const final { return false; }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001800
Eric Laurent68a40a82022-05-03 18:15:04 +02001801 // RefBase
Andy Hung440901d2023-06-29 21:19:25 -07001802 void onFirstRef() final;
Eric Laurent68a40a82022-05-03 18:15:04 +02001803
Andy Hung440901d2023-06-29 21:19:25 -07001804 status_t setRequestedLatencyMode(audio_latency_mode_t mode) final;
Eric Laurent68a40a82022-05-03 18:15:04 +02001805
Eric Laurentb3f315a2021-07-13 15:09:05 +02001806protected:
Andy Hung440901d2023-06-29 21:19:25 -07001807 void checkOutputStageEffects() final;
1808 void setHalLatencyMode_l() final;
Eric Laurentb3f315a2021-07-13 15:09:05 +02001809
1810private:
Eric Laurent68a40a82022-05-03 18:15:04 +02001811 // Do not request a specific mode by default
1812 audio_latency_mode_t mRequestedLatencyMode = AUDIO_LATENCY_MODE_FREE;
1813
Andy Hung116bc262023-06-20 18:56:17 -07001814 sp<IAfEffectHandle> mFinalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02001815};
1816
Eric Laurent81784c32012-11-19 14:55:58 -08001817// record thread
Andy Hung87c693c2023-07-06 20:56:16 -07001818class RecordThread : public IAfRecordThread, public ThreadBase
Eric Laurent81784c32012-11-19 14:55:58 -08001819{
Andy Hung8d31fd22023-06-26 19:20:57 -07001820 friend class ResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08001821public:
Andy Hung87c693c2023-07-06 20:56:16 -07001822 sp<IAfRecordThread> asIAfRecordThread() final {
1823 return sp<IAfRecordThread>::fromExisting(this);
1824 }
Eric Laurent81784c32012-11-19 14:55:58 -08001825
Andy Hung583043b2023-07-17 17:05:00 -07001826 RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08001827 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08001828 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001829 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08001830 );
Andy Hung440901d2023-06-29 21:19:25 -07001831 ~RecordThread() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001832
1833 // no addTrack_l ?
Andy Hung87c693c2023-07-06 20:56:16 -07001834 void destroyTrack_l(const sp<IAfRecordTrack>& track) final;
1835 void removeTrack_l(const sp<IAfRecordTrack>& track) final;
Eric Laurent81784c32012-11-19 14:55:58 -08001836
Eric Laurent81784c32012-11-19 14:55:58 -08001837 // Thread virtuals
Andy Hung440901d2023-06-29 21:19:25 -07001838 bool threadLoop() final;
1839 void preExit() final;
Eric Laurent81784c32012-11-19 14:55:58 -08001840
1841 // RefBase
Andy Hung440901d2023-06-29 21:19:25 -07001842 void onFirstRef() final;
Eric Laurent81784c32012-11-19 14:55:58 -08001843
Andy Hung440901d2023-06-29 21:19:25 -07001844 status_t initCheck() const final { return mInput == nullptr ? NO_INIT : NO_ERROR; }
Glenn Kastene198c362013-08-13 09:13:36 -07001845
Andy Hung440901d2023-06-29 21:19:25 -07001846 sp<MemoryDealer> readOnlyHeap() const final { return mReadOnlyHeap; }
Glenn Kastenb880f5e2014-05-07 08:43:45 -07001847
Andy Hung440901d2023-06-29 21:19:25 -07001848 sp<IMemory> pipeMemory() const final { return mPipeMemory; }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001849
Andy Hung87c693c2023-07-06 20:56:16 -07001850 sp<IAfRecordTrack> createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001851 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001852 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001853 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001854 audio_format_t format,
1855 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001856 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08001857 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001858 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07001859 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00001860 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07001861 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001862 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001863 status_t *status /*non-NULL*/,
Eric Laurentec376dc2021-04-08 20:41:22 +02001864 audio_port_handle_t portId,
Andy Hung87c693c2023-07-06 20:56:16 -07001865 int32_t maxSharedAudioHistoryMs) final;
Eric Laurent81784c32012-11-19 14:55:58 -08001866
Andy Hung8d31fd22023-06-26 19:20:57 -07001867 status_t start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08001868 AudioSystem::sync_event_t event,
Andy Hung87c693c2023-07-06 20:56:16 -07001869 audio_session_t triggerSession) final;
Eric Laurent81784c32012-11-19 14:55:58 -08001870
1871 // ask the thread to stop the specified track, and
1872 // return true if the caller should then do it's part of the stopping process
Andy Hung87c693c2023-07-06 20:56:16 -07001873 bool stop(IAfRecordTrack* recordTrack) final;
1874 AudioStreamIn* getInput() const final { return mInput; }
1875 AudioStreamIn* clearInput() final;
Eric Laurent81784c32012-11-19 14:55:58 -08001876
Andy Hung99b1ba62023-07-14 11:00:08 -07001877 // TODO(b/291317898) Unify with IAfThreadBase
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001878 virtual sp<StreamHalInterface> stream() const;
Eric Laurent81784c32012-11-19 14:55:58 -08001879
Eric Laurent81784c32012-11-19 14:55:58 -08001880
Eric Laurent10351942014-05-08 18:49:52 -07001881 virtual bool checkForNewParameter_l(const String8& keyValuePair,
1882 status_t& status);
1883 virtual void cacheParameters_l() {}
Eric Laurent81784c32012-11-19 14:55:58 -08001884 virtual String8 getParameters(const String8& keys);
Andy Hung87c693c2023-07-06 20:56:16 -07001885 void ioConfigChanged(audio_io_config_event_t event, pid_t pid = 0,
1886 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final;
Eric Laurent1c333e22014-05-20 10:48:17 -07001887 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
1888 audio_patch_handle_t *handle);
1889 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle);
jiabinc52b1ff2019-10-31 17:20:42 -07001890 void updateOutDevices(const DeviceDescriptorBaseVector& outDevices) override;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02001891 void resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs) override;
Eric Laurent83b88082014-06-20 18:31:16 -07001892
Andy Hung87c693c2023-07-06 20:56:16 -07001893 void addPatchTrack(const sp<IAfPatchRecord>& record) final;
1894 void deletePatchTrack(const sp<IAfPatchRecord>& record) final;
Eric Laurent83b88082014-06-20 18:31:16 -07001895
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001896 void readInputParameters_l();
Andy Hung87c693c2023-07-06 20:56:16 -07001897 uint32_t getInputFramesLost() const final;
Eric Laurent81784c32012-11-19 14:55:58 -08001898
Andy Hung116bc262023-06-20 18:56:17 -07001899 virtual status_t addEffectChain_l(const sp<IAfEffectChain>& chain);
1900 virtual size_t removeEffectChain_l(const sp<IAfEffectChain>& chain);
Andy Hungc3d62f92019-03-14 13:38:51 -07001901 uint32_t hasAudioSession_l(audio_session_t sessionId) const override {
1902 return ThreadBase::hasAudioSession_l(sessionId, mTracks);
1903 }
Eric Laurent81784c32012-11-19 14:55:58 -08001904
1905 // Return the set of unique session IDs across all tracks.
1906 // The keys are the session IDs, and the associated values are meaningless.
1907 // FIXME replace by Set [and implement Bag/Multiset for other uses].
Glenn Kastend848eb42016-03-08 13:42:11 -08001908 KeyedVector<audio_session_t, bool> sessionIds() const;
Eric Laurent81784c32012-11-19 14:55:58 -08001909
Andy Hung068e08e2023-05-15 19:02:55 -07001910 status_t setSyncEvent(const sp<audioflinger::SyncEvent>& event) override;
1911 bool isValidSyncEvent(const sp<audioflinger::SyncEvent>& event) const override;
Eric Laurent81784c32012-11-19 14:55:58 -08001912
Andy Hung068e08e2023-05-15 19:02:55 -07001913 static void syncStartEventCallback(const wp<audioflinger::SyncEvent>& event);
Eric Laurent81784c32012-11-19 14:55:58 -08001914
Glenn Kasten9b58f632013-07-16 11:37:48 -07001915 virtual size_t frameCount() const { return mFrameCount; }
Andy Hung87c693c2023-07-06 20:56:16 -07001916 bool hasFastCapture() const final { return mFastCapture != 0; }
Mikhail Naganovdc769682018-05-04 15:34:08 -07001917 virtual void toAudioPortConfig(struct audio_port_config *config);
Glenn Kasten9b58f632013-07-16 11:37:48 -07001918
Eric Laurent4c415062016-06-17 16:14:16 -07001919 virtual status_t checkEffectCompatibility_l(const effect_descriptor_t *desc,
1920 audio_session_t sessionId);
1921
Andy Hungdae27702016-10-31 14:01:16 -07001922 virtual void acquireWakeLock_l() {
1923 ThreadBase::acquireWakeLock_l();
1924 mActiveTracks.updatePowerState(this, true /* force */);
1925 }
1926
Andy Hung87c693c2023-07-06 20:56:16 -07001927 void checkBtNrec() final;
Eric Laurentd8365c52017-07-16 15:27:05 -07001928
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001929 // Sets the UID records silence
Andy Hung87c693c2023-07-06 20:56:16 -07001930 void setRecordSilenced(audio_port_handle_t portId, bool silenced) final;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001931
Andy Hung87c693c2023-07-06 20:56:16 -07001932 status_t getActiveMicrophones(
1933 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const final;
1934 status_t setPreferredMicrophoneDirection(audio_microphone_direction_t direction) final;
1935 status_t setPreferredMicrophoneFieldDimension(float zoom) final;
Paul McLean03a6e6a2018-12-04 10:54:13 -07001936
Vlad Popa7e81cea2023-01-19 16:34:16 +01001937 MetadataUpdate updateMetadata_l() override;
Kevin Rocard069c2712018-03-29 19:09:14 -07001938
Andy Hung87c693c2023-07-06 20:56:16 -07001939 bool fastTrackAvailable() const final { return mFastTrackAvail; }
1940 void setFastTrackAvailable(bool available) final { mFastTrackAvail = available; }
jiabin01c8f562018-07-19 17:47:28 -07001941
Andy Hungc8fddf32018-08-08 18:32:37 -07001942 bool isTimestampCorrectionEnabled() const override {
1943 // checks popcount for exactly one device.
Atneya Nair497fff12022-01-18 16:23:04 -05001944 // Is currently disabled. Before enabling,
1945 // verify compressed record timestamps.
jiabinc52b1ff2019-10-31 17:20:42 -07001946 return audio_is_input_device(mTimestampCorrectedDevice)
1947 && inDeviceType() == mTimestampCorrectedDevice;
Andy Hungc8fddf32018-08-08 18:32:37 -07001948 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001949
Andy Hung87c693c2023-07-06 20:56:16 -07001950 status_t shareAudioHistory(const std::string& sharedAudioPackageName,
Eric Laurentec376dc2021-04-08 20:41:22 +02001951 audio_session_t sharedSessionId = AUDIO_SESSION_NONE,
Andy Hung87c693c2023-07-06 20:56:16 -07001952 int64_t sharedAudioStartMs = -1) final;
Eric Laurentec376dc2021-04-08 20:41:22 +02001953 status_t shareAudioHistory_l(const std::string& sharedAudioPackageName,
1954 audio_session_t sharedSessionId = AUDIO_SESSION_NONE,
1955 int64_t sharedAudioStartMs = -1);
Andy Hung87c693c2023-07-06 20:56:16 -07001956 void resetAudioHistory_l() final;
Eric Laurentec376dc2021-04-08 20:41:22 +02001957
Andy Hung440901d2023-06-29 21:19:25 -07001958 bool isStreamInitialized() const final {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001959 return !(mInput == nullptr || mInput->stream == nullptr);
1960 }
1961
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001962protected:
1963 void dumpInternals_l(int fd, const Vector<String16>& args) override;
1964 void dumpTracks_l(int fd, const Vector<String16>& args) override;
1965
Eric Laurent81784c32012-11-19 14:55:58 -08001966private:
Eric Laurent81784c32012-11-19 14:55:58 -08001967 // Enter standby if not already in standby, and set mStandby flag
Glenn Kasten93e471f2013-08-19 08:40:07 -07001968 void standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08001969
1970 // Call the HAL standby method unconditionally, and don't change mStandby flag
Glenn Kastene198c362013-08-13 09:13:36 -07001971 void inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08001972
Eric Laurentd8365c52017-07-16 15:27:05 -07001973 void checkBtNrec_l();
1974
Eric Laurentec376dc2021-04-08 20:41:22 +02001975 int32_t getOldestFront_l();
1976 void updateFronts_l(int32_t offset);
1977
Eric Laurent81784c32012-11-19 14:55:58 -08001978 AudioStreamIn *mInput;
Mikhail Naganov2534b382019-09-25 13:05:02 -07001979 Source *mSource;
Andy Hung8d31fd22023-06-26 19:20:57 -07001980 SortedVector <sp<IAfRecordTrack>> mTracks;
Glenn Kasten2b806402013-11-20 16:37:38 -08001981 // mActiveTracks has dual roles: it indicates the current active track(s), and
Andy Hungc5007f82023-08-29 14:26:09 -07001982 // is used together with mStartStopCV to indicate start()/stop() progress
Andy Hung8d31fd22023-06-26 19:20:57 -07001983 ActiveTracks<IAfRecordTrack> mActiveTracks;
Andy Hungdae27702016-10-31 14:01:16 -07001984
Andy Hungc5007f82023-08-29 14:26:09 -07001985 audio_utils::condition_variable mStartStopCV;
Glenn Kasten9b58f632013-07-16 11:37:48 -07001986
Glenn Kasten85948432013-08-19 12:09:05 -07001987 // resampler converts input at HAL Hz to output at AudioRecord client Hz
Glenn Kasten1b291842016-07-18 14:55:21 -07001988 void *mRsmpInBuffer; // size = mRsmpInFramesOA
Glenn Kasten85948432013-08-19 12:09:05 -07001989 size_t mRsmpInFrames; // size of resampler input in frames
1990 size_t mRsmpInFramesP2;// size rounded up to a power-of-2
Glenn Kasten1b291842016-07-18 14:55:21 -07001991 size_t mRsmpInFramesOA;// mRsmpInFramesP2 + over-allocation
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001992
1993 // rolling index that is never cleared
Glenn Kasten85948432013-08-19 12:09:05 -07001994 int32_t mRsmpInRear; // last filled frame + 1
Glenn Kasten85948432013-08-19 12:09:05 -07001995
Eric Laurent81784c32012-11-19 14:55:58 -08001996 // For dumpsys
Glenn Kastenb880f5e2014-05-07 08:43:45 -07001997 const sp<MemoryDealer> mReadOnlyHeap;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001998
1999 // one-time initialization, no locks required
Glenn Kastenb187de12014-12-30 08:18:15 -08002000 sp<FastCapture> mFastCapture; // non-0 if there is also
2001 // a fast capture
Eric Laurent72e3f392015-05-20 14:43:50 -07002002
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07002003 // FIXME audio watchdog thread
2004
2005 // contents are not guaranteed to be consistent, no locks required
2006 FastCaptureDumpState mFastCaptureDumpState;
2007#ifdef STATE_QUEUE_DUMP
2008 // FIXME StateQueue observer and mutator dump fields
2009#endif
2010 // FIXME audio watchdog dump
2011
2012 // accessible only within the threadLoop(), no locks required
2013 // mFastCapture->sq() // for mutating and pushing state
2014 int32_t mFastCaptureFutex; // for cold idle
2015
2016 // The HAL input source is treated as non-blocking,
2017 // but current implementation is blocking
2018 sp<NBAIO_Source> mInputSource;
2019 // The source for the normal capture thread to read from: mInputSource or mPipeSource
2020 sp<NBAIO_Source> mNormalSource;
2021 // If a fast capture is present, the non-blocking pipe sink written to by fast capture,
2022 // otherwise clear
2023 sp<NBAIO_Sink> mPipeSink;
2024 // If a fast capture is present, the non-blocking pipe source read by normal thread,
2025 // otherwise clear
2026 sp<NBAIO_Source> mPipeSource;
2027 // Depth of pipe from fast capture to normal thread and fast clients, always power of 2
2028 size_t mPipeFramesP2;
2029 // If a fast capture is present, the Pipe as IMemory, otherwise clear
2030 sp<IMemory> mPipeMemory;
2031
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002032 // TODO: add comment and adjust size as needed
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07002033 static const size_t kFastCaptureLogSize = 4 * 1024;
2034 sp<NBLog::Writer> mFastCaptureNBLogWriter;
2035
2036 bool mFastTrackAvail; // true if fast track available
Eric Laurentd8365c52017-07-16 15:27:05 -07002037 // common state to all record threads
2038 std::atomic_bool mBtNrecSuspended;
Andy Hung6427e442018-08-09 12:51:02 -07002039
2040 int64_t mFramesRead = 0; // continuous running counter.
jiabinc52b1ff2019-10-31 17:20:42 -07002041
2042 DeviceDescriptorBaseVector mOutDevices;
Eric Laurentec376dc2021-04-08 20:41:22 +02002043
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02002044 int32_t mMaxSharedAudioHistoryMs = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02002045 std::string mSharedAudioPackageName = {};
Eric Laurent2407ce32021-04-26 14:56:03 +02002046 int32_t mSharedAudioStartFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02002047 audio_session_t mSharedAudioSessionId = AUDIO_SESSION_NONE;
Eric Laurent81784c32012-11-19 14:55:58 -08002048};
Eric Laurent6acd1d42017-01-04 14:23:29 -08002049
Andy Hung7aa7d102023-07-07 15:58:48 -07002050class MmapThread : public ThreadBase, public virtual IAfMmapThread
Eric Laurent6acd1d42017-01-04 14:23:29 -08002051{
2052 public:
Andy Hung583043b2023-07-17 17:05:00 -07002053 MmapThread(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -07002054 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady,
Andy Hungcf10d742020-04-28 15:38:24 -07002055 bool isOut);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002056
Andy Hung7aa7d102023-07-07 15:58:48 -07002057 void configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08002058 audio_stream_type_t streamType,
2059 audio_session_t sessionId,
2060 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07002061 audio_port_handle_t deviceId,
Andy Hung7aa7d102023-07-07 15:58:48 -07002062 audio_port_handle_t portId) override;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002063
Andy Hung7aa7d102023-07-07 15:58:48 -07002064 void disconnect() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002065
Andy Hung440901d2023-06-29 21:19:25 -07002066 // MmapStreamInterface for adapter.
Andy Hung7aa7d102023-07-07 15:58:48 -07002067 status_t createMmapBuffer(int32_t minSizeFrames, struct audio_mmap_buffer_info* info) final;
2068 status_t getMmapPosition(struct audio_mmap_position* position) const override;
2069 status_t start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07002070 const audio_attributes_t *attr,
Andy Hung7aa7d102023-07-07 15:58:48 -07002071 audio_port_handle_t* handle) final;
2072 status_t stop(audio_port_handle_t handle) final;
2073 status_t standby() final;
2074 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) const = 0;
2075 status_t reportData(const void* buffer, size_t frameCount) override;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002076
2077 // RefBase
Andy Hung440901d2023-06-29 21:19:25 -07002078 void onFirstRef() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002079
2080 // Thread virtuals
Andy Hung440901d2023-06-29 21:19:25 -07002081 bool threadLoop() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002082
Andy Hung440901d2023-06-29 21:19:25 -07002083 // Not in ThreadBase
2084 virtual void threadLoop_exit() final;
2085 virtual void threadLoop_standby() final;
2086 virtual bool shouldStandby_l() final { return false; }
Andy Hungc5007f82023-08-29 14:26:09 -07002087 virtual status_t exitStandby_l() REQUIRES(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002088
Andy Hung440901d2023-06-29 21:19:25 -07002089 status_t initCheck() const final { return mHalStream == nullptr ? NO_INIT : NO_ERROR; }
2090 size_t frameCount() const final { return mFrameCount; }
2091 bool checkForNewParameter_l(const String8& keyValuePair, status_t& status) final;
2092 String8 getParameters(const String8& keys) final;
2093 void ioConfigChanged(audio_io_config_event_t event, pid_t pid = 0,
2094 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002095 void readHalParameters_l();
Andy Hung440901d2023-06-29 21:19:25 -07002096 void cacheParameters_l() final {}
2097 status_t createAudioPatch_l(
2098 const struct audio_patch* patch, audio_patch_handle_t* handle) final;
2099 status_t releaseAudioPatch_l(const audio_patch_handle_t handle) final;
2100 void toAudioPortConfig(struct audio_port_config* config) override;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002101
Andy Hung440901d2023-06-29 21:19:25 -07002102 sp<StreamHalInterface> stream() const final { return mHalStream; }
2103 status_t addEffectChain_l(const sp<IAfEffectChain>& chain) final;
2104 size_t removeEffectChain_l(const sp<IAfEffectChain>& chain) final;
2105 status_t checkEffectCompatibility_l(
2106 const effect_descriptor_t *desc, audio_session_t sessionId) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002107
Andy Hung440901d2023-06-29 21:19:25 -07002108 uint32_t hasAudioSession_l(audio_session_t sessionId) const override {
Andy Hungc3d62f92019-03-14 13:38:51 -07002109 // Note: using mActiveTracks as no mTracks here.
2110 return ThreadBase::hasAudioSession_l(sessionId, mActiveTracks);
2111 }
Andy Hung440901d2023-06-29 21:19:25 -07002112 status_t setSyncEvent(const sp<audioflinger::SyncEvent>& event) final;
2113 bool isValidSyncEvent(const sp<audioflinger::SyncEvent>& event) const final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002114
Andy Hung440901d2023-06-29 21:19:25 -07002115 virtual void checkSilentMode_l() {} // cannot be const (RecordThread)
2116 virtual void processVolume_l() {}
Eric Laurent6acd1d42017-01-04 14:23:29 -08002117 void checkInvalidTracks_l();
2118
Andy Hung440901d2023-06-29 21:19:25 -07002119 // Not in ThreadBase
2120 virtual audio_stream_type_t streamType() const { return AUDIO_STREAM_DEFAULT; }
2121 virtual void invalidateTracks(audio_stream_type_t /* streamType */) {}
Andy Hung7aa7d102023-07-07 15:58:48 -07002122 void invalidateTracks(std::set<audio_port_handle_t>& /* portIds */) override {}
Eric Laurent6acd1d42017-01-04 14:23:29 -08002123
Eric Laurent331679c2018-04-16 17:03:16 -07002124 // Sets the UID records silence
Andy Hung7aa7d102023-07-07 15:58:48 -07002125 void setRecordSilenced(
2126 audio_port_handle_t /* portId */, bool /* silenced */) override {}
Eric Laurent331679c2018-04-16 17:03:16 -07002127
Andy Hung440901d2023-06-29 21:19:25 -07002128 bool isStreamInitialized() const override { return false; }
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002129
jiabin09609032022-06-15 19:26:01 +00002130 void setClientSilencedState_l(audio_port_handle_t portId, bool silenced) {
2131 mClientSilencedStates[portId] = silenced;
2132 }
2133
2134 size_t eraseClientSilencedState_l(audio_port_handle_t portId) {
2135 return mClientSilencedStates.erase(portId);
2136 }
2137
2138 bool isClientSilenced_l(audio_port_handle_t portId) const {
2139 const auto it = mClientSilencedStates.find(portId);
2140 return it != mClientSilencedStates.end() ? it->second : false;
2141 }
2142
2143 void setClientSilencedIfExists_l(audio_port_handle_t portId, bool silenced) {
2144 const auto it = mClientSilencedStates.find(portId);
2145 if (it != mClientSilencedStates.end()) {
2146 it->second = silenced;
2147 }
2148 }
2149
Eric Laurent6acd1d42017-01-04 14:23:29 -08002150 protected:
Andy Hung440901d2023-06-29 21:19:25 -07002151 void dumpInternals_l(int fd, const Vector<String16>& args) override;
2152 void dumpTracks_l(int fd, const Vector<String16>& args) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002153
jiabinc52b1ff2019-10-31 17:20:42 -07002154 /**
2155 * @brief mDeviceId current device port unique identifier
2156 */
2157 audio_port_handle_t mDeviceId = AUDIO_PORT_HANDLE_NONE;
2158
Eric Laurent6acd1d42017-01-04 14:23:29 -08002159 audio_attributes_t mAttr;
2160 audio_session_t mSessionId;
2161 audio_port_handle_t mPortId;
2162
Phil Burk7f6b40d2017-02-09 13:18:38 -08002163 wp<MmapStreamCallback> mCallback;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002164 sp<StreamHalInterface> mHalStream;
2165 sp<DeviceHalInterface> mHalDevice;
2166 AudioHwDevice* const mAudioHwDev;
Andy Hung8d31fd22023-06-26 19:20:57 -07002167 ActiveTracks<IAfMmapTrack> mActiveTracks;
Eric Laurent67f97292018-04-20 18:05:41 -07002168 float mHalVolFloat;
jiabin09609032022-06-15 19:26:01 +00002169 std::map<audio_port_handle_t, bool> mClientSilencedStates;
Eric Laurent331679c2018-04-16 17:03:16 -07002170
2171 int32_t mNoCallbackWarningCount;
2172 static constexpr int32_t kMaxNoCallbackWarnings = 5;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002173};
2174
Andy Hung7aa7d102023-07-07 15:58:48 -07002175class MmapPlaybackThread : public MmapThread, public IAfMmapPlaybackThread,
2176 public virtual VolumeInterface {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002177public:
Andy Hung583043b2023-07-17 17:05:00 -07002178 MmapPlaybackThread(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07002179 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002180
Andy Hung7aa7d102023-07-07 15:58:48 -07002181 sp<IAfMmapPlaybackThread> asIAfMmapPlaybackThread() final {
2182 return sp<IAfMmapPlaybackThread>::fromExisting(this);
2183 }
2184
Andy Hung440901d2023-06-29 21:19:25 -07002185 void configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08002186 audio_stream_type_t streamType,
2187 audio_session_t sessionId,
2188 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07002189 audio_port_handle_t deviceId,
Andy Hung440901d2023-06-29 21:19:25 -07002190 audio_port_handle_t portId) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002191
Andy Hung7aa7d102023-07-07 15:58:48 -07002192 AudioStreamOut* clearOutput() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002193
2194 // VolumeInterface
Andy Hung440901d2023-06-29 21:19:25 -07002195 void setMasterVolume(float value) final;
2196 void setMasterBalance(float /* value */) final {} // Needs implementation?
2197 void setMasterMute(bool muted) final;
2198 void setStreamVolume(audio_stream_type_t stream, float value) final;
2199 void setStreamMute(audio_stream_type_t stream, bool muted) final;
2200 float streamVolume(audio_stream_type_t stream) const final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002201
2202 void setMasterMute_l(bool muted) { mMasterMute = muted; }
2203
Andy Hung440901d2023-06-29 21:19:25 -07002204 void invalidateTracks(audio_stream_type_t streamType) final;
2205 void invalidateTracks(std::set<audio_port_handle_t>& portIds) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002206
Andy Hung440901d2023-06-29 21:19:25 -07002207 audio_stream_type_t streamType() const final { return mStreamType; }
2208 void checkSilentMode_l() final;
2209 void processVolume_l() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002210
Andy Hung440901d2023-06-29 21:19:25 -07002211 MetadataUpdate updateMetadata_l() final;
Kevin Rocard069c2712018-03-29 19:09:14 -07002212
Andy Hung440901d2023-06-29 21:19:25 -07002213 void toAudioPortConfig(struct audio_port_config* config) final;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07002214
Andy Hung440901d2023-06-29 21:19:25 -07002215 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) const final;
jiabinb7d8c5a2020-08-26 17:24:52 -07002216
Andy Hung440901d2023-06-29 21:19:25 -07002217 bool isStreamInitialized() const final {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002218 return !(mOutput == nullptr || mOutput->stream == nullptr);
2219 }
2220
Andy Hung440901d2023-06-29 21:19:25 -07002221 status_t reportData(const void* buffer, size_t frameCount) final;
jiabinfc791ee2023-02-15 19:43:40 +00002222
Andy Hung440901d2023-06-29 21:19:25 -07002223 void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) final;
2224 void stopMelComputation_l() final;
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002225
Eric Laurent6acd1d42017-01-04 14:23:29 -08002226protected:
Andy Hung440901d2023-06-29 21:19:25 -07002227 void dumpInternals_l(int fd, const Vector<String16>& args) final;
Eric Laurent1f9b5e62023-07-03 18:14:07 +02002228 float streamVolume_l() const {
2229 return mStreamTypes[mStreamType].volume;
2230 }
2231 bool streamMuted_l() const {
2232 return mStreamTypes[mStreamType].mute;
2233 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002234
Eric Laurent1f9b5e62023-07-03 18:14:07 +02002235 stream_type_t mStreamTypes[AUDIO_STREAM_CNT];
Eric Laurent6acd1d42017-01-04 14:23:29 -08002236 audio_stream_type_t mStreamType;
2237 float mMasterVolume;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002238 bool mMasterMute;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002239 AudioStreamOut* mOutput;
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002240
2241 mediautils::atomic_sp<audio_utils::MelProcessor> mMelProcessor;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002242};
2243
Andy Hung7aa7d102023-07-07 15:58:48 -07002244class MmapCaptureThread : public MmapThread, public IAfMmapCaptureThread
Eric Laurent6acd1d42017-01-04 14:23:29 -08002245{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002246public:
Andy Hung583043b2023-07-17 17:05:00 -07002247 MmapCaptureThread(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07002248 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002249
Andy Hung7aa7d102023-07-07 15:58:48 -07002250 sp<IAfMmapCaptureThread> asIAfMmapCaptureThread() final {
2251 return sp<IAfMmapCaptureThread>::fromExisting(this);
2252 }
2253
2254 AudioStreamIn* clearInput() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002255
Andy Hungc5007f82023-08-29 14:26:09 -07002256 status_t exitStandby_l() REQUIRES(mutex()) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002257
Andy Hung440901d2023-06-29 21:19:25 -07002258 MetadataUpdate updateMetadata_l() final;
2259 void processVolume_l() final;
2260 void setRecordSilenced(audio_port_handle_t portId, bool silenced) final;
Kevin Rocard069c2712018-03-29 19:09:14 -07002261
Andy Hung440901d2023-06-29 21:19:25 -07002262 void toAudioPortConfig(struct audio_port_config* config) final;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07002263
Andy Hung440901d2023-06-29 21:19:25 -07002264 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) const final;
jiabinb7d8c5a2020-08-26 17:24:52 -07002265
Andy Hung440901d2023-06-29 21:19:25 -07002266 bool isStreamInitialized() const final {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002267 return !(mInput == nullptr || mInput->stream == nullptr);
2268 }
2269
Eric Laurent6acd1d42017-01-04 14:23:29 -08002270protected:
2271
2272 AudioStreamIn* mInput;
2273};
jiabinc658e452022-10-21 20:52:21 +00002274
2275class BitPerfectThread : public MixerThread {
2276public:
Andy Hung583043b2023-07-17 17:05:00 -07002277 BitPerfectThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut *output,
jiabinc658e452022-10-21 20:52:21 +00002278 audio_io_handle_t id, bool systemReady);
2279
2280protected:
Andy Hung440901d2023-06-29 21:19:25 -07002281 mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove) final;
2282 void threadLoop_mix() final;
jiabinc658e452022-10-21 20:52:21 +00002283
2284private:
2285 bool mIsBitPerfect;
jiabin76d94692022-12-15 21:51:21 +00002286 float mVolumeLeft = 0.f;
2287 float mVolumeRight = 0.f;
jiabinc658e452022-10-21 20:52:21 +00002288};
Andy Hunga5a7fc92023-06-23 19:27:19 -07002289
Andy Hungee58e4a2023-07-07 13:47:37 -07002290} // namespace android