blob: c6c585b64b46dc9e1bcfca5fd9c88e11320a0be4 [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 Hung4b17e882023-07-07 13:47:37 -070018#pragma once
Eric Laurent81784c32012-11-19 14:55:58 -080019
Andy Hung409572b2023-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 Hung4b17e882023-07-07 13:47:37 -070039namespace android {
Andy Hung3e4c8742023-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 Hung7535ed92023-07-17 17:05:00 -070047 IAfThreadCallback* afThreadCallback() const final { return mAfThreadCallback.get(); }
Andy Hung0c1e11e2023-07-06 20:56:16 -070048
Andy Hung7535ed92023-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 Hung3e4c8742023-06-29 21:19:25 -070051 ~ThreadBase() override;
Eric Laurent81784c32012-11-19 14:55:58 -080052
Andy Hung3e4c8742023-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
80 // 2. Lock mLock
81 // 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():
87 // 1. Lock mLock
88 // 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
93 // 7. event->mCond.signal
94 // 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
106 const int mType; // event type e.g. CFG_EVENT_IO
107 Mutex mLock; // mutex associated with mCond
108 Condition mCond; // condition for status return
109 status_t mStatus; // status communicated to sender
110 bool mWaitStatus; // true if sender is waiting for status
Eric Laurent72e3f392015-05-20 14:43:50 -0700111 bool mRequiresSystemReady; // true if must wait for system ready to enter event queue
Eric Laurent10351942014-05-08 18:49:52 -0700112 sp<ConfigEventData> mData; // event specific parameter data
113
114 protected:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700115 explicit ConfigEvent(int type, bool requiresSystemReady = false) :
Eric Laurent72e3f392015-05-20 14:43:50 -0700116 mType(type), mStatus(NO_ERROR), mWaitStatus(false),
117 mRequiresSystemReady(requiresSystemReady), mData(NULL) {}
Eric Laurent10351942014-05-08 18:49:52 -0700118 };
119
120 class IoConfigEventData : public ConfigEventData {
121 public:
Mikhail Naganov88536df2021-07-26 17:30:29 -0700122 IoConfigEventData(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700123 audio_port_handle_t portId) :
124 mEvent(event), mPid(pid), mPortId(portId) {}
Eric Laurent81784c32012-11-19 14:55:58 -0800125
126 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200127 snprintf(buffer, size, "- IO event: event %d\n", mEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800128 }
129
Mikhail Naganov88536df2021-07-26 17:30:29 -0700130 const audio_io_config_event_t mEvent;
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700131 const pid_t mPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -0700132 const audio_port_handle_t mPortId;
Eric Laurent81784c32012-11-19 14:55:58 -0800133 };
134
Eric Laurent10351942014-05-08 18:49:52 -0700135 class IoConfigEvent : public ConfigEvent {
Eric Laurent81784c32012-11-19 14:55:58 -0800136 public:
Mikhail Naganov88536df2021-07-26 17:30:29 -0700137 IoConfigEvent(audio_io_config_event_t event, pid_t pid, audio_port_handle_t portId) :
Eric Laurent10351942014-05-08 18:49:52 -0700138 ConfigEvent(CFG_EVENT_IO) {
Eric Laurent09f1ed22019-04-24 17:45:17 -0700139 mData = new IoConfigEventData(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700140 }
Eric Laurent10351942014-05-08 18:49:52 -0700141 };
Eric Laurent81784c32012-11-19 14:55:58 -0800142
Eric Laurent10351942014-05-08 18:49:52 -0700143 class PrioConfigEventData : public ConfigEventData {
144 public:
Mikhail Naganov83f04272017-02-07 10:45:09 -0800145 PrioConfigEventData(pid_t pid, pid_t tid, int32_t prio, bool forApp) :
146 mPid(pid), mTid(tid), mPrio(prio), mForApp(forApp) {}
Eric Laurent81784c32012-11-19 14:55:58 -0800147
148 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200149 snprintf(buffer, size, "- Prio event: pid %d, tid %d, prio %d, for app? %d\n",
Mikhail Naganov83f04272017-02-07 10:45:09 -0800150 mPid, mTid, mPrio, mForApp);
Eric Laurent81784c32012-11-19 14:55:58 -0800151 }
152
Eric Laurent81784c32012-11-19 14:55:58 -0800153 const pid_t mPid;
154 const pid_t mTid;
155 const int32_t mPrio;
Mikhail Naganov83f04272017-02-07 10:45:09 -0800156 const bool mForApp;
Eric Laurent81784c32012-11-19 14:55:58 -0800157 };
158
Eric Laurent10351942014-05-08 18:49:52 -0700159 class PrioConfigEvent : public ConfigEvent {
160 public:
Mikhail Naganov83f04272017-02-07 10:45:09 -0800161 PrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp) :
Eric Laurent72e3f392015-05-20 14:43:50 -0700162 ConfigEvent(CFG_EVENT_PRIO, true) {
Mikhail Naganov83f04272017-02-07 10:45:09 -0800163 mData = new PrioConfigEventData(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700164 }
Eric Laurent10351942014-05-08 18:49:52 -0700165 };
166
167 class SetParameterConfigEventData : public ConfigEventData {
168 public:
Andy Hung920f6572022-10-06 12:09:49 -0700169 explicit SetParameterConfigEventData(const String8& keyValuePairs) :
Eric Laurent10351942014-05-08 18:49:52 -0700170 mKeyValuePairs(keyValuePairs) {}
171
172 virtual void dump(char *buffer, size_t size) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +0000173 snprintf(buffer, size, "- KeyValue: %s\n", mKeyValuePairs.c_str());
Eric Laurent10351942014-05-08 18:49:52 -0700174 }
175
176 const String8 mKeyValuePairs;
177 };
178
179 class SetParameterConfigEvent : public ConfigEvent {
180 public:
Andy Hung920f6572022-10-06 12:09:49 -0700181 explicit SetParameterConfigEvent(const String8& keyValuePairs) :
Eric Laurent10351942014-05-08 18:49:52 -0700182 ConfigEvent(CFG_EVENT_SET_PARAMETER) {
183 mData = new SetParameterConfigEventData(keyValuePairs);
184 mWaitStatus = true;
185 }
Eric Laurent10351942014-05-08 18:49:52 -0700186 };
187
Eric Laurent1c333e22014-05-20 10:48:17 -0700188 class CreateAudioPatchConfigEventData : public ConfigEventData {
189 public:
190 CreateAudioPatchConfigEventData(const struct audio_patch patch,
191 audio_patch_handle_t handle) :
192 mPatch(patch), mHandle(handle) {}
193
194 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200195 snprintf(buffer, size, "- Patch handle: %u\n", mHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -0700196 }
197
198 const struct audio_patch mPatch;
199 audio_patch_handle_t mHandle;
200 };
201
202 class CreateAudioPatchConfigEvent : public ConfigEvent {
203 public:
204 CreateAudioPatchConfigEvent(const struct audio_patch patch,
205 audio_patch_handle_t handle) :
206 ConfigEvent(CFG_EVENT_CREATE_AUDIO_PATCH) {
207 mData = new CreateAudioPatchConfigEventData(patch, handle);
208 mWaitStatus = true;
209 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700210 };
211
212 class ReleaseAudioPatchConfigEventData : public ConfigEventData {
213 public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700214 explicit ReleaseAudioPatchConfigEventData(const audio_patch_handle_t handle) :
Eric Laurent1c333e22014-05-20 10:48:17 -0700215 mHandle(handle) {}
216
217 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200218 snprintf(buffer, size, "- Patch handle: %u\n", mHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -0700219 }
220
221 audio_patch_handle_t mHandle;
222 };
223
224 class ReleaseAudioPatchConfigEvent : public ConfigEvent {
225 public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700226 explicit ReleaseAudioPatchConfigEvent(const audio_patch_handle_t handle) :
Eric Laurent1c333e22014-05-20 10:48:17 -0700227 ConfigEvent(CFG_EVENT_RELEASE_AUDIO_PATCH) {
228 mData = new ReleaseAudioPatchConfigEventData(handle);
229 mWaitStatus = true;
230 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700231 };
Eric Laurent81784c32012-11-19 14:55:58 -0800232
jiabinc52b1ff2019-10-31 17:20:42 -0700233 class UpdateOutDevicesConfigEventData : public ConfigEventData {
234 public:
235 explicit UpdateOutDevicesConfigEventData(const DeviceDescriptorBaseVector& outDevices) :
236 mOutDevices(outDevices) {}
237
238 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200239 snprintf(buffer, size, "- Devices: %s", android::toString(mOutDevices).c_str());
jiabinc52b1ff2019-10-31 17:20:42 -0700240 }
241
242 DeviceDescriptorBaseVector mOutDevices;
243 };
244
245 class UpdateOutDevicesConfigEvent : public ConfigEvent {
246 public:
247 explicit UpdateOutDevicesConfigEvent(const DeviceDescriptorBaseVector& outDevices) :
248 ConfigEvent(CFG_EVENT_UPDATE_OUT_DEVICE) {
249 mData = new UpdateOutDevicesConfigEventData(outDevices);
250 }
jiabinc52b1ff2019-10-31 17:20:42 -0700251 };
252
Eric Laurentec376dc2021-04-08 20:41:22 +0200253 class ResizeBufferConfigEventData : public ConfigEventData {
254 public:
255 explicit ResizeBufferConfigEventData(int32_t maxSharedAudioHistoryMs) :
256 mMaxSharedAudioHistoryMs(maxSharedAudioHistoryMs) {}
257
258 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200259 snprintf(buffer, size, "- mMaxSharedAudioHistoryMs: %d", mMaxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +0200260 }
261
262 int32_t mMaxSharedAudioHistoryMs;
263 };
264
265 class ResizeBufferConfigEvent : public ConfigEvent {
266 public:
267 explicit ResizeBufferConfigEvent(int32_t maxSharedAudioHistoryMs) :
268 ConfigEvent(CFG_EVENT_RESIZE_BUFFER) {
269 mData = new ResizeBufferConfigEventData(maxSharedAudioHistoryMs);
270 }
Eric Laurentec376dc2021-04-08 20:41:22 +0200271 };
272
Eric Laurentb3f315a2021-07-13 15:09:05 +0200273 class CheckOutputStageEffectsEvent : public ConfigEvent {
274 public:
275 CheckOutputStageEffectsEvent() :
276 ConfigEvent(CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS) {
277 }
Eric Laurentb3f315a2021-07-13 15:09:05 +0200278 };
279
Eric Laurent68a40a82022-05-03 18:15:04 +0200280 class HalLatencyModesChangedEvent : public ConfigEvent {
281 public:
282 HalLatencyModesChangedEvent() :
283 ConfigEvent(CFG_EVENT_HAL_LATENCY_MODES_CHANGED) {
284 }
Eric Laurent68a40a82022-05-03 18:15:04 +0200285 };
286
Eric Laurentb3f315a2021-07-13 15:09:05 +0200287
Eric Laurent81784c32012-11-19 14:55:58 -0800288 class PMDeathRecipient : public IBinder::DeathRecipient {
289 public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700290 explicit PMDeathRecipient(const wp<ThreadBase>& thread) : mThread(thread) {}
Eric Laurent81784c32012-11-19 14:55:58 -0800291 virtual ~PMDeathRecipient() {}
292
293 // IBinder::DeathRecipient
294 virtual void binderDied(const wp<IBinder>& who);
295
296 private:
Mikhail Naganovbf493082017-04-17 17:37:12 -0700297 DISALLOW_COPY_AND_ASSIGN(PMDeathRecipient);
Eric Laurent81784c32012-11-19 14:55:58 -0800298
299 wp<ThreadBase> mThread;
300 };
301
Andy Hung3e4c8742023-06-29 21:19:25 -0700302 type_t type() const final { return mType; }
303 bool isDuplicating() const final { return (mType == DUPLICATING); }
304 audio_io_handle_t id() const final { return mId;}
Eric Laurent81784c32012-11-19 14:55:58 -0800305
Andy Hung3e4c8742023-06-29 21:19:25 -0700306 uint32_t sampleRate() const final { return mSampleRate; }
307 audio_channel_mask_t channelMask() const final { return mChannelMask; }
308 audio_channel_mask_t mixerChannelMask() const override { return mChannelMask; }
309 audio_format_t format() const final { return mHALFormat; }
310 uint32_t channelCount() const final { return mChannelCount; }
311 audio_channel_mask_t hapticChannelMask() const override { return AUDIO_CHANNEL_NONE; }
Andy Hung0c1e11e2023-07-06 20:56:16 -0700312 uint32_t hapticChannelCount() const override { return 0; }
Andy Hung3e4c8742023-06-29 21:19:25 -0700313 uint32_t latency_l() const override { return 0; }
314 void setVolumeForOutput_l(float /* left */, float /* right */) const override {}
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700315
316 // Return's the HAL's frame count i.e. fast mixer buffer size.
Andy Hung3e4c8742023-06-29 21:19:25 -0700317 size_t frameCountHAL() const final { return mFrameCount; }
318 size_t frameSize() const final { return mFrameSize; }
Eric Laurent81784c32012-11-19 14:55:58 -0800319
320 // Should be "virtual status_t requestExitAndWait()" and override same
321 // method in Thread, but Thread::requestExitAndWait() is not yet virtual.
Andy Hung3e4c8742023-06-29 21:19:25 -0700322 void exit() final;
323 status_t setParameters(const String8& keyValuePairs) final;
324
Eric Laurent10351942014-05-08 18:49:52 -0700325 // sendConfigEvent_l() must be called with ThreadBase::mLock held
326 // Can temporarily release the lock if waiting for a reply from
327 // processConfigEvents_l().
Andy Hung3e4c8742023-06-29 21:19:25 -0700328 status_t sendConfigEvent_l(sp<ConfigEvent>& event);
329 void sendIoConfigEvent(audio_io_config_event_t event, pid_t pid = 0,
330 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final;
331 void sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid = 0,
332 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final;
333 void sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp) final;
334 void sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio, bool forApp) final;
335 status_t sendSetParameterConfigEvent_l(const String8& keyValuePair) final;
336 status_t sendCreateAudioPatchConfigEvent(const struct audio_patch* patch,
337 audio_patch_handle_t* handle) final;
338 status_t sendReleaseAudioPatchConfigEvent(audio_patch_handle_t handle) final;
339 status_t sendUpdateOutDeviceConfigEvent(
340 const DeviceDescriptorBaseVector& outDevices) final;
341 void sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs) final;
342 void sendCheckOutputStageEffectsEvent() final;
343 void sendCheckOutputStageEffectsEvent_l() final;
344 void sendHalLatencyModesChangedEvent_l() final;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200345
Andy Hung3e4c8742023-06-29 21:19:25 -0700346 void processConfigEvents_l() final;
347 void setCheckOutputStageEffects() override {}
348 void updateOutDevices(const DeviceDescriptorBaseVector& outDevices) override;
349 void toAudioPortConfig(struct audio_port_config* config) override;
350 void resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs) override;
Eric Laurent1c333e22014-05-20 10:48:17 -0700351
Andy Hung3e4c8742023-06-29 21:19:25 -0700352 // see note at declaration of mStandby, mOutDevice and mInDevice
353 bool inStandby() const override { return mStandby; }
354 const DeviceTypeSet outDeviceTypes() const final {
355 return getAudioDeviceTypes(mOutDeviceTypeAddrs);
356 }
357 audio_devices_t inDeviceType() const final { return mInDeviceTypeAddr.mType; }
358 DeviceTypeSet getDeviceTypes() const final {
359 return isOutput() ? outDeviceTypes() : DeviceTypeSet({inDeviceType()});
360 }
Eric Laurent81784c32012-11-19 14:55:58 -0800361
Andy Hung3e4c8742023-06-29 21:19:25 -0700362 const AudioDeviceTypeAddrVector& outDeviceTypeAddrs() const final {
363 return mOutDeviceTypeAddrs;
364 }
365 const AudioDeviceTypeAddr& inDeviceTypeAddr() const final {
366 return mInDeviceTypeAddr;
367 }
Andy Hung293558a2017-03-21 12:19:20 -0700368
Andy Hung3e4c8742023-06-29 21:19:25 -0700369 bool isOutput() const final { return mIsOut; }
jiabin8f278ee2019-11-11 12:16:27 -0800370
Andy Hung3e4c8742023-06-29 21:19:25 -0700371 bool isOffloadOrMmap() const final {
372 switch (mType) {
373 case OFFLOAD:
374 case MMAP_PLAYBACK:
375 case MMAP_CAPTURE:
376 return true;
377 default:
378 return false;
379 }
380 }
Eric Laurent81784c32012-11-19 14:55:58 -0800381
Andy Hung3e4c8742023-06-29 21:19:25 -0700382 sp<IAfEffectHandle> createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -0700383 const sp<Client>& client,
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700384 const sp<media::IEffectClient>& effectClient,
Eric Laurent81784c32012-11-19 14:55:58 -0800385 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -0800386 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800387 effect_descriptor_t *desc,
388 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -0800389 status_t *status /*non-NULL*/,
Eric Laurent2fe0acd2020-03-13 14:30:46 -0700390 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +0200391 bool probe,
Andy Hung3e4c8742023-06-29 21:19:25 -0700392 bool notifyFramesProcessed) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800393
394 // return values for hasAudioSession (bit field)
395 enum effect_state {
396 EFFECT_SESSION = 0x1, // the audio session corresponds to at least one
397 // effect
Eric Laurent4c415062016-06-17 16:14:16 -0700398 TRACK_SESSION = 0x2, // the audio session corresponds to at least one
Eric Laurent81784c32012-11-19 14:55:58 -0800399 // track
Eric Laurentb62d0362021-10-26 17:40:18 +0200400 FAST_SESSION = 0x4, // the audio session corresponds to at least one
Eric Laurent4c415062016-06-17 16:14:16 -0700401 // fast track
jiabinc658e452022-10-21 20:52:21 +0000402 SPATIALIZED_SESSION = 0x8, // the audio session corresponds to at least one
403 // spatialized track
404 BIT_PERFECT_SESSION = 0x10 // the audio session corresponds to at least one
405 // bit-perfect track
Eric Laurent81784c32012-11-19 14:55:58 -0800406 };
407
Andy Hung3e4c8742023-06-29 21:19:25 -0700408 // get effect chain corresponding to session Id.
409 sp<IAfEffectChain> getEffectChain(audio_session_t sessionId) const final;
410 // same as getEffectChain() but must be called with ThreadBase mutex locked
411 sp<IAfEffectChain> getEffectChain_l(audio_session_t sessionId) const final;
412 std::vector<int> getEffectIds_l(audio_session_t sessionId) const final;
413
Eric Laurent81784c32012-11-19 14:55:58 -0800414 // lock all effect chains Mutexes. Must be called before releasing the
415 // ThreadBase mutex before processing the mixer and effects. This guarantees the
416 // integrity of the chains during the process.
417 // Also sets the parameter 'effectChains' to current value of mEffectChains.
Andy Hung3e4c8742023-06-29 21:19:25 -0700418 void lockEffectChains_l(Vector<sp<IAfEffectChain>>& effectChains) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800419 // unlock effect chains after process
Andy Hung3e4c8742023-06-29 21:19:25 -0700420 void unlockEffectChains(const Vector<sp<IAfEffectChain>>& effectChains) final;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800421 // get a copy of mEffectChains vector
Andy Hung3e4c8742023-06-29 21:19:25 -0700422 Vector<sp<IAfEffectChain>> getEffectChains_l() const final { return mEffectChains; };
Eric Laurent81784c32012-11-19 14:55:58 -0800423 // set audio mode to all effect chains
Andy Hung3e4c8742023-06-29 21:19:25 -0700424 void setMode(audio_mode_t mode) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800425 // get effect module with corresponding ID on specified audio session
Andy Hung3e4c8742023-06-29 21:19:25 -0700426 sp<IAfEffectModule> getEffect(audio_session_t sessionId, int effectId) const final;
427 sp<IAfEffectModule> getEffect_l(audio_session_t sessionId, int effectId) const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800428 // add and effect module. Also creates the effect chain is none exists for
Eric Laurent6c796322019-04-09 14:13:17 -0700429 // the effects audio session. Only called in a context of moving an effect
430 // from one thread to another
Andy Hung3e4c8742023-06-29 21:19:25 -0700431 status_t addEffect_l(const sp<IAfEffectModule>& effect) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800432 // remove and effect module. Also removes the effect chain is this was the last
433 // effect
Andy Hung3e4c8742023-06-29 21:19:25 -0700434 void removeEffect_l(const sp<IAfEffectModule>& effect, bool release = false) final;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -0800435 // disconnect an effect handle from module and destroy module if last handle
Andy Hung3e4c8742023-06-29 21:19:25 -0700436 void disconnectEffectHandle(IAfEffectHandle* handle, bool unpinIfLast) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800437 // detach all tracks connected to an auxiliary effect
Andy Hung3e4c8742023-06-29 21:19:25 -0700438 void detachAuxEffect_l(int /* effectId */) override {}
Andy Hungeb6b5f82023-07-14 11:00:08 -0700439 // TODO(b/291317898) - remove hasAudioSession_l below.
Andy Hung3e4c8742023-06-29 21:19:25 -0700440 uint32_t hasAudioSession_l(audio_session_t sessionId) const override = 0;
441 uint32_t hasAudioSession(audio_session_t sessionId) const final {
Eric Laurent4c415062016-06-17 16:14:16 -0700442 Mutex::Autolock _l(mLock);
443 return hasAudioSession_l(sessionId);
444 }
445
Andy Hungc3d62f92019-03-14 13:38:51 -0700446 template <typename T>
447 uint32_t hasAudioSession_l(audio_session_t sessionId, const T& tracks) const {
448 uint32_t result = 0;
449 if (getEffectChain_l(sessionId) != 0) {
450 result = EFFECT_SESSION;
451 }
452 for (size_t i = 0; i < tracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -0700453 const sp<IAfTrackBase>& track = tracks[i];
Andy Hungc3d62f92019-03-14 13:38:51 -0700454 if (sessionId == track->sessionId()
455 && !track->isInvalid() // not yet removed from tracks.
456 && !track->isTerminated()) {
457 result |= TRACK_SESSION;
458 if (track->isFastTrack()) {
459 result |= FAST_SESSION; // caution, only represents first track.
460 }
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200461 if (track->isSpatialized()) {
Eric Laurentb62d0362021-10-26 17:40:18 +0200462 result |= SPATIALIZED_SESSION; // caution, only first track.
463 }
jiabinc658e452022-10-21 20:52:21 +0000464 if (track->isBitPerfect()) {
465 result |= BIT_PERFECT_SESSION;
466 }
Andy Hungc3d62f92019-03-14 13:38:51 -0700467 break;
468 }
469 }
470 return result;
471 }
472
Eric Laurent81784c32012-11-19 14:55:58 -0800473 // the value returned by default implementation is not important as the
474 // strategy is only meaningful for PlaybackThread which implements this method
Andy Hung3e4c8742023-06-29 21:19:25 -0700475 product_strategy_t getStrategyForSession_l(
476 audio_session_t /* sessionId */) const override {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800477 return static_cast<product_strategy_t>(0);
478 }
Eric Laurent81784c32012-11-19 14:55:58 -0800479
Eric Laurent81784c32012-11-19 14:55:58 -0800480 // check if some effects must be suspended/restored when an effect is enabled
481 // or disabled
Andy Hung3e4c8742023-06-29 21:19:25 -0700482 void checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -0800483 audio_session_t sessionId,
Andy Hung3e4c8742023-06-29 21:19:25 -0700484 bool threadLocked) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800485
Eric Laurent81784c32012-11-19 14:55:58 -0800486
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700487 // Return a reference to a per-thread heap which can be used to allocate IMemory
488 // objects that will be read-only to client processes, read/write to mediaserver,
489 // and shared by all client processes of the thread.
490 // The heap is per-thread rather than common across all threads, because
491 // clients can't be trusted not to modify the offset of the IMemory they receive.
492 // If a thread does not have such a heap, this method returns 0.
Andy Hung3e4c8742023-06-29 21:19:25 -0700493 sp<MemoryDealer> readOnlyHeap() const override { return nullptr; }
Eric Laurent81784c32012-11-19 14:55:58 -0800494
Andy Hung3e4c8742023-06-29 21:19:25 -0700495 sp<IMemory> pipeMemory() const override { return nullptr; }
Glenn Kasten6181ffd2014-05-13 10:41:52 -0700496
Andy Hung3e4c8742023-06-29 21:19:25 -0700497 void systemReady() final;
Eric Laurent72e3f392015-05-20 14:43:50 -0700498
Andy Hung3e4c8742023-06-29 21:19:25 -0700499 void broadcast_l() final;
Eric Laurent4c415062016-06-17 16:14:16 -0700500
Andy Hung3e4c8742023-06-29 21:19:25 -0700501 bool isTimestampCorrectionEnabled() const override { return false; }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800502
Andy Hung3e4c8742023-06-29 21:19:25 -0700503 bool isMsdDevice() const final { return mIsMsdDevice; }
Andy Hungc8fddf32018-08-08 18:32:37 -0700504
Andy Hung3e4c8742023-06-29 21:19:25 -0700505 void dump(int fd, const Vector<String16>& args) override;
Andy Hungdc099c22018-09-18 13:46:39 -0700506
Andy Hungd0979812019-02-21 15:51:44 -0800507 // deliver stats to mediametrics.
Andy Hung3e4c8742023-06-29 21:19:25 -0700508 void sendStatistics(bool force) final;
Andy Hungd0979812019-02-21 15:51:44 -0800509
Andy Hung3e4c8742023-06-29 21:19:25 -0700510 Mutex& mutex() const final {
511 return mLock;
512 }
Eric Laurent81784c32012-11-19 14:55:58 -0800513 mutable Mutex mLock;
514
Andy Hung3e4c8742023-06-29 21:19:25 -0700515 void onEffectEnable(const sp<IAfEffectModule>& effect) final;
516 void onEffectDisable() final;
Eric Laurent6b446ce2019-12-13 10:56:31 -0800517
jiabineb3bda02020-06-30 14:07:03 -0700518 // invalidateTracksForAudioSession_l must be called with holding mLock.
Andy Hung3e4c8742023-06-29 21:19:25 -0700519 void invalidateTracksForAudioSession_l(audio_session_t /* sessionId */) const override {}
jiabineb3bda02020-06-30 14:07:03 -0700520 // Invalidate all the tracks with the given audio session.
Andy Hung3e4c8742023-06-29 21:19:25 -0700521 void invalidateTracksForAudioSession(audio_session_t sessionId) const final {
jiabineb3bda02020-06-30 14:07:03 -0700522 Mutex::Autolock _l(mLock);
523 invalidateTracksForAudioSession_l(sessionId);
524 }
525
526 template <typename T>
527 void invalidateTracksForAudioSession_l(audio_session_t sessionId,
528 const T& tracks) const {
529 for (size_t i = 0; i < tracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -0700530 const sp<IAfTrackBase>& track = tracks[i];
jiabineb3bda02020-06-30 14:07:03 -0700531 if (sessionId == track->sessionId()) {
532 track->invalidate();
533 }
534 }
535 }
536
Andy Hung3e4c8742023-06-29 21:19:25 -0700537 void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) override;
538 void stopMelComputation_l() override;
Vlad Popa6fbbfbf2023-02-22 15:05:43 +0100539
Eric Laurent81784c32012-11-19 14:55:58 -0800540protected:
541
542 // entry describing an effect being suspended in mSuspendedSessions keyed vector
543 class SuspendedSessionDesc : public RefBase {
544 public:
545 SuspendedSessionDesc() : mRefCount(0) {}
546
547 int mRefCount; // number of active suspend requests
548 effect_uuid_t mType; // effect type UUID
549 };
550
Andy Hungdae27702016-10-31 14:01:16 -0700551 void acquireWakeLock();
552 virtual void acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800553 void releaseWakeLock();
554 void releaseWakeLock_l();
Andy Hungd01b0f12016-11-07 16:10:30 -0800555 void updateWakeLockUids_l(const SortedVector<uid_t> &uids);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800556 void getPowerManager_l();
Eric Laurentd8365c52017-07-16 15:27:05 -0700557 // suspend or restore effects of the specified type (or all if type is NULL)
558 // on a given session. The number of suspend requests is counted and restore
559 // occurs when all suspend requests are cancelled.
Eric Laurent81784c32012-11-19 14:55:58 -0800560 void setEffectSuspended_l(const effect_uuid_t *type,
561 bool suspend,
Andy Hung0c1e11e2023-07-06 20:56:16 -0700562 audio_session_t sessionId) final;
Eric Laurentd8365c52017-07-16 15:27:05 -0700563 // updated mSuspendedSessions when an effect is suspended or restored
Eric Laurent81784c32012-11-19 14:55:58 -0800564 void updateSuspendedSessions_l(const effect_uuid_t *type,
565 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -0800566 audio_session_t sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800567 // check if some effects must be suspended when an effect chain is added
Andy Hung116bc262023-06-20 18:56:17 -0700568 void checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain);
Eric Laurent81784c32012-11-19 14:55:58 -0800569
Kevin Rocard069c2712018-03-29 19:09:14 -0700570 // sends the metadata of the active tracks to the HAL
Vlad Popa7e81cea2023-01-19 16:34:16 +0100571 struct MetadataUpdate {
572 std::vector<playback_track_metadata_v7_t> playbackMetadataUpdate;
573 std::vector<record_track_metadata_v7_t> recordMetadataUpdate;
574 };
575 virtual MetadataUpdate updateMetadata_l() = 0;
Kevin Rocard069c2712018-03-29 19:09:14 -0700576
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100577 String16 getWakeLockTag();
578
Eric Laurent81784c32012-11-19 14:55:58 -0800579 virtual void preExit() { }
Andy Hung2ddee192015-12-18 17:34:44 -0800580 virtual void setMasterMono_l(bool mono __unused) { }
581 virtual bool requireMonoBlend() { return false; }
Eric Laurent81784c32012-11-19 14:55:58 -0800582
Andy Hung1c86ebe2018-05-29 20:29:08 -0700583 // called within the threadLoop to obtain timestamp from the HAL.
584 virtual status_t threadloop_getHalTimestamp_l(
585 ExtendedTimestamp *timestamp __unused) const {
586 return INVALID_OPERATION;
587 }
Andy Hung116bc262023-06-20 18:56:17 -0700588public:
Andy Hungeb6b5f82023-07-14 11:00:08 -0700589// TODO(b/291317898) organize with publics
Eric Laurentd66d7a12021-07-13 13:35:32 +0200590 product_strategy_t getStrategyForStream(audio_stream_type_t stream) const;
Andy Hung116bc262023-06-20 18:56:17 -0700591protected:
Eric Laurentd66d7a12021-07-13 13:35:32 +0200592
Eric Laurentb0463942022-12-20 16:31:10 +0100593 virtual void onHalLatencyModesChanged_l() {}
594
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700595 virtual void dumpInternals_l(int fd __unused, const Vector<String16>& args __unused)
596 { }
597 virtual void dumpTracks_l(int fd __unused, const Vector<String16>& args __unused) { }
598
Eric Laurent81784c32012-11-19 14:55:58 -0800599 const type_t mType;
600
601 // Used by parameters, config events, addTrack_l, exit
602 Condition mWaitWorkCV;
603
Andy Hung7535ed92023-07-17 17:05:00 -0700604 const sp<IAfThreadCallback> mAfThreadCallback;
Andy Hungcf10d742020-04-28 15:38:24 -0700605 ThreadMetrics mThreadMetrics;
606 const bool mIsOut;
Glenn Kasten9b58f632013-07-16 11:37:48 -0700607
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800608 // updated by PlaybackThread::readOutputParameters_l() or
609 // RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800610 uint32_t mSampleRate;
611 size_t mFrameCount; // output HAL, direct output, record
Eric Laurent81784c32012-11-19 14:55:58 -0800612 audio_channel_mask_t mChannelMask;
Glenn Kastenf6ed4232013-07-16 11:16:27 -0700613 uint32_t mChannelCount;
Eric Laurent81784c32012-11-19 14:55:58 -0800614 size_t mFrameSize;
Glenn Kasten97b7b752014-09-28 13:04:24 -0700615 // not HAL frame size, this is for output sink (to pipe to fast mixer)
Andy Hung463be252014-07-10 16:56:07 -0700616 audio_format_t mFormat; // Source format for Recording and
617 // Sink format for Playback.
618 // Sink format may be different than
619 // HAL format if Fastmixer is used.
620 audio_format_t mHALFormat;
Glenn Kasten70949c42013-08-06 07:40:12 -0700621 size_t mBufferSize; // HAL buffer size for read() or write()
jiabinc52b1ff2019-10-31 17:20:42 -0700622 AudioDeviceTypeAddrVector mOutDeviceTypeAddrs; // output device types and addresses
623 AudioDeviceTypeAddr mInDeviceTypeAddr; // input device type and address
Eric Laurent10351942014-05-08 18:49:52 -0700624 Vector< sp<ConfigEvent> > mConfigEvents;
Eric Laurent72e3f392015-05-20 14:43:50 -0700625 Vector< sp<ConfigEvent> > mPendingConfigEvents; // events awaiting system ready
Eric Laurent81784c32012-11-19 14:55:58 -0800626
627 // These fields are written and read by thread itself without lock or barrier,
jiabinc52b1ff2019-10-31 17:20:42 -0700628 // and read by other threads without lock or barrier via standby(), outDeviceTypes()
629 // and inDeviceType().
Eric Laurent81784c32012-11-19 14:55:58 -0800630 // Because of the absence of a lock or barrier, any other thread that reads
631 // these fields must use the information in isolation, or be prepared to deal
632 // with possibility that it might be inconsistent with other information.
Glenn Kasten4944acb2013-08-19 08:39:20 -0700633 bool mStandby; // Whether thread is currently in standby.
jiabinc52b1ff2019-10-31 17:20:42 -0700634
Eric Laurent296fb132015-05-01 11:38:42 -0700635 struct audio_patch mPatch;
jiabinc52b1ff2019-10-31 17:20:42 -0700636
Glenn Kastenf59497b2015-01-26 16:35:47 -0800637 audio_source_t mAudioSource;
Eric Laurent81784c32012-11-19 14:55:58 -0800638
639 const audio_io_handle_t mId;
Andy Hung116bc262023-06-20 18:56:17 -0700640 Vector<sp<IAfEffectChain>> mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -0800641
Glenn Kastend7dca052015-03-05 16:05:54 -0800642 static const int kThreadNameLength = 16; // prctl(PR_SET_NAME) limit
643 char mThreadName[kThreadNameLength]; // guaranteed NUL-terminated
Chris Ye6597d732020-02-28 22:38:25 -0800644 sp<os::IPowerManager> mPowerManager;
Eric Laurent81784c32012-11-19 14:55:58 -0800645 sp<IBinder> mWakeLockToken;
646 const sp<PMDeathRecipient> mDeathRecipient;
Glenn Kastend848eb42016-03-08 13:42:11 -0800647 // list of suspended effects per session and per type. The first (outer) vector is
648 // keyed by session ID, the second (inner) by type UUID timeLow field
Eric Laurentd8365c52017-07-16 15:27:05 -0700649 // Updated by updateSuspendedSessions_l() only.
Glenn Kastend848eb42016-03-08 13:42:11 -0800650 KeyedVector< audio_session_t, KeyedVector< int, sp<SuspendedSessionDesc> > >
Eric Laurent81784c32012-11-19 14:55:58 -0800651 mSuspendedSessions;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -0700652 // TODO: add comment and adjust size as needed
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800653 static const size_t kLogSize = 4 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -0800654 sp<NBLog::Writer> mNBLogWriter;
Eric Laurent72e3f392015-05-20 14:43:50 -0700655 bool mSystemReady;
Andy Hung818e7a32016-02-16 18:08:07 -0800656 ExtendedTimestamp mTimestamp;
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700657 TimestampVerifier< // For timestamp statistics.
658 int64_t /* frame count */, int64_t /* time ns */> mTimestampVerifier;
Dean Wheatley12473e92021-03-18 23:00:55 +1100659 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush
660 // TODO: add confirmation checks:
661 // 1) DIRECT threads and linear PCM format really resets to 0?
662 // 2) Is frame count really valid if not linear pcm?
663 // 3) Are all 64 bits of position returned, not just lowest 32 bits?
jiabinc52b1ff2019-10-31 17:20:42 -0700664 // Timestamp corrected device should be a single device.
665 audio_devices_t mTimestampCorrectedDevice = AUDIO_DEVICE_NONE;
Andy Hung446f4df2019-02-21 12:26:41 -0800666
667 // ThreadLoop statistics per iteration.
668 int64_t mLastIoBeginNs = -1;
669 int64_t mLastIoEndNs = -1;
670
Andy Hung44d648b2022-04-08 17:33:40 -0700671 // ThreadSnapshot is thread-safe (internally locked)
672 mediautils::ThreadSnapshot mThreadSnapshot;
673
Andy Hung446f4df2019-02-21 12:26:41 -0800674 // This should be read under ThreadBase lock (if not on the threadLoop thread).
675 audio_utils::Statistics<double> mIoJitterMs{0.995 /* alpha */};
676 audio_utils::Statistics<double> mProcessTimeMs{0.995 /* alpha */};
Andy Hunge6c37112019-02-26 17:38:10 -0800677 audio_utils::Statistics<double> mLatencyMs{0.995 /* alpha */};
Robert Wu06db0a32021-08-10 19:05:34 +0000678 audio_utils::Statistics<double> mMonopipePipeDepthStats{0.999 /* alpha */};
Andy Hung446f4df2019-02-21 12:26:41 -0800679
Andy Hungd0979812019-02-21 15:51:44 -0800680 // Save the last count when we delivered statistics to mediametrics.
681 int64_t mLastRecordedTimestampVerifierN = 0;
682 int64_t mLastRecordedTimeNs = 0; // BOOTTIME to include suspend.
683
Andy Hungc8fddf32018-08-08 18:32:37 -0700684 bool mIsMsdDevice = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800685 // A condition that must be evaluated by the thread loop has changed and
686 // we must not wait for async write callback in the thread loop before evaluating it
687 bool mSignalPending;
Andy Hungdae27702016-10-31 14:01:16 -0700688
Andy Hung8946a282018-04-19 20:04:56 -0700689#ifdef TEE_SINK
690 NBAIO_Tee mTee;
691#endif
Andy Hungdae27702016-10-31 14:01:16 -0700692 // ActiveTracks is a sorted vector of track type T representing the
693 // active tracks of threadLoop() to be considered by the locked prepare portion.
694 // ActiveTracks should be accessed with the ThreadBase lock held.
695 //
696 // During processing and I/O, the threadLoop does not hold the lock;
697 // hence it does not directly use ActiveTracks. Care should be taken
698 // to hold local strong references or defer removal of tracks
699 // if the threadLoop may still be accessing those tracks due to mix, etc.
700 //
701 // This class updates power information appropriately.
702 //
703
704 template <typename T>
705 class ActiveTracks {
706 public:
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700707 explicit ActiveTracks(SimpleLog *localLog = nullptr)
Andy Hungdae27702016-10-31 14:01:16 -0700708 : mActiveTracksGeneration(0)
709 , mLastActiveTracksGeneration(0)
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700710 , mLocalLog(localLog)
Andy Hungdae27702016-10-31 14:01:16 -0700711 { }
712
713 ~ActiveTracks() {
714 ALOGW_IF(!mActiveTracks.isEmpty(),
715 "ActiveTracks should be empty in destructor");
716 }
717 // returns the last track added (even though it may have been
718 // subsequently removed from ActiveTracks).
719 //
720 // Used for DirectOutputThread to ensure a flush is called when transitioning
721 // to a new track (even though it may be on the same session).
722 // Used for OffloadThread to ensure that volume and mixer state is
723 // taken from the latest track added.
724 //
725 // The latest track is saved with a weak pointer to prevent keeping an
726 // otherwise useless track alive. Thus the function will return nullptr
727 // if the latest track has subsequently been removed and destroyed.
728 sp<T> getLatest() {
729 return mLatestActiveTrack.promote();
730 }
731
732 // SortedVector methods
733 ssize_t add(const sp<T> &track);
734 ssize_t remove(const sp<T> &track);
735 size_t size() const {
736 return mActiveTracks.size();
737 }
Eric Tan39ec8d62018-07-24 09:49:29 -0700738 bool isEmpty() const {
739 return mActiveTracks.isEmpty();
740 }
Andy Hung0c1e11e2023-07-06 20:56:16 -0700741 ssize_t indexOf(const sp<T>& item) const {
Andy Hungdae27702016-10-31 14:01:16 -0700742 return mActiveTracks.indexOf(item);
743 }
744 sp<T> operator[](size_t index) const {
745 return mActiveTracks[index];
746 }
747 typename SortedVector<sp<T>>::iterator begin() {
748 return mActiveTracks.begin();
749 }
750 typename SortedVector<sp<T>>::iterator end() {
751 return mActiveTracks.end();
752 }
753
754 // Due to Binder recursion optimization, clear() and updatePowerState()
755 // cannot be called from a Binder thread because they may call back into
756 // the original calling process (system server) for BatteryNotifier
757 // (which requires a Java environment that may not be present).
758 // Hence, call clear() and updatePowerState() only from the
759 // ThreadBase thread.
760 void clear();
761 // periodically called in the threadLoop() to update power state uids.
Andy Hung920f6572022-10-06 12:09:49 -0700762 void updatePowerState(const sp<ThreadBase>& thread, bool force = false);
Andy Hungdae27702016-10-31 14:01:16 -0700763
Kevin Rocardc86a7f72018-04-03 09:00:09 -0700764 /** @return true if one or move active tracks was added or removed since the
Jasmine Chaeaa10e42021-05-11 10:11:14 +0800765 * last time this function was called or the vector was created.
766 * true if volume of one of active tracks was changed.
767 */
Kevin Rocard069c2712018-03-29 19:09:14 -0700768 bool readAndClearHasChanged();
769
Eric Laurentdda206a2022-07-08 17:28:35 +0200770 /** Force updating track metadata to audio HAL stream next time
771 * readAndClearHasChanged() is called.
772 */
773 void setHasChanged() { mHasChanged = true; }
774
Andy Hungdae27702016-10-31 14:01:16 -0700775 private:
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700776 void logTrack(const char *funcName, const sp<T> &track) const;
777
Andy Hungd01b0f12016-11-07 16:10:30 -0800778 SortedVector<uid_t> getWakeLockUids() {
779 SortedVector<uid_t> wakeLockUids;
Andy Hungdae27702016-10-31 14:01:16 -0700780 for (const sp<T> &track : mActiveTracks) {
781 wakeLockUids.add(track->uid());
782 }
783 return wakeLockUids; // moved by underlying SharedBuffer
784 }
785
Andy Hungdae27702016-10-31 14:01:16 -0700786 SortedVector<sp<T>> mActiveTracks;
787 int mActiveTracksGeneration;
788 int mLastActiveTracksGeneration;
789 wp<T> mLatestActiveTrack; // latest track added to ActiveTracks
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700790 SimpleLog * const mLocalLog;
Kevin Rocardc86a7f72018-04-03 09:00:09 -0700791 // If the vector has changed since last call to readAndClearHasChanged
Kevin Rocard069c2712018-03-29 19:09:14 -0700792 bool mHasChanged = false;
Andy Hungdae27702016-10-31 14:01:16 -0700793 };
Andy Hung293558a2017-03-21 12:19:20 -0700794
795 SimpleLog mLocalLog;
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700796
797private:
798 void dumpBase_l(int fd, const Vector<String16>& args);
799 void dumpEffectChains_l(int fd, const Vector<String16>& args);
Eric Laurent81784c32012-11-19 14:55:58 -0800800};
801
802// --- PlaybackThread ---
Andy Hung3e4c8742023-06-29 21:19:25 -0700803class PlaybackThread : public ThreadBase, public virtual IAfPlaybackThread,
804 public StreamOutHalInterfaceCallback,
Andy Hung0c1e11e2023-07-06 20:56:16 -0700805 public virtual VolumeInterface, public StreamOutHalInterfaceEventCallback {
Eric Laurent81784c32012-11-19 14:55:58 -0800806public:
Andy Hung0c1e11e2023-07-06 20:56:16 -0700807 sp<IAfPlaybackThread> asIAfPlaybackThread() final {
808 return sp<IAfPlaybackThread>::fromExisting(this);
809 }
Eric Laurent81784c32012-11-19 14:55:58 -0800810
Eric Laurente93cc032016-05-05 10:15:10 -0700811 // retry count before removing active track in case of underrun on offloaded thread:
812 // we need to make sure that AudioTrack client has enough time to send large buffers
813 //FIXME may be more appropriate if expressed in time units. Need to revise how underrun is
814 // handled for offloaded tracks
815 static const int8_t kMaxTrackRetriesOffload = 20;
816 static const int8_t kMaxTrackStartupRetriesOffload = 100;
Andy Hung8ed196a2018-01-05 13:21:11 -0800817 static constexpr uint32_t kMaxTracksPerUid = 40;
Andy Hung1bc088a2018-02-09 15:57:31 -0800818 static constexpr size_t kMaxTracks = 256;
Eric Laurente93cc032016-05-05 10:15:10 -0700819
rago1bb90822017-05-02 18:31:48 -0700820 // Maximum delay (in nanoseconds) for upcoming buffers in suspend mode, otherwise
821 // if delay is greater, the estimated time for timeLoopNextNs is reset.
822 // This allows for catch-up to be done for small delays, while resetting the estimate
823 // for initial conditions or large delays.
824 static const nsecs_t kMaxNextBufferDelayNs = 100000000;
825
Andy Hung7535ed92023-07-17 17:05:00 -0700826 PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +0200827 audio_io_handle_t id, type_t type, bool systemReady,
828 audio_config_base_t *mixerConfig = nullptr);
Andy Hung3e4c8742023-06-29 21:19:25 -0700829 ~PlaybackThread() override;
Eric Laurent81784c32012-11-19 14:55:58 -0800830
Eric Laurent81784c32012-11-19 14:55:58 -0800831 // Thread virtuals
Andy Hung3e4c8742023-06-29 21:19:25 -0700832 bool threadLoop() final;
Eric Laurent81784c32012-11-19 14:55:58 -0800833
834 // RefBase
Andy Hung3e4c8742023-06-29 21:19:25 -0700835 void onFirstRef() override;
Eric Laurent81784c32012-11-19 14:55:58 -0800836
Andy Hung3e4c8742023-06-29 21:19:25 -0700837 status_t checkEffectCompatibility_l(
838 const effect_descriptor_t* desc, audio_session_t sessionId) final;
Eric Laurent4c415062016-06-17 16:14:16 -0700839
Andy Hung0c1e11e2023-07-06 20:56:16 -0700840 void addOutputTrack_l(const sp<IAfTrack>& track) final {
841 mTracks.add(track);
842 }
843
Eric Laurent81784c32012-11-19 14:55:58 -0800844protected:
845 // Code snippets that were lifted up out of threadLoop()
846 virtual void threadLoop_mix() = 0;
847 virtual void threadLoop_sleepTime() = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800848 virtual ssize_t threadLoop_write();
849 virtual void threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -0800850 virtual void threadLoop_standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800851 virtual void threadLoop_exit();
Andy Hung11e74242023-06-26 19:20:57 -0700852 virtual void threadLoop_removeTracks(const Vector<sp<IAfTrack>>& tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -0800853
854 // prepareTracks_l reads and writes mActiveTracks, and returns
855 // the pending set of tracks to remove via Vector 'tracksToRemove'. The caller
856 // is responsible for clearing or destroying this Vector later on, when it
857 // is safe to do so. That will drop the final ref count and destroy the tracks.
Andy Hung11e74242023-06-26 19:20:57 -0700858 virtual mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove) = 0;
859 void removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove);
Eric Laurenteab90452019-06-24 15:17:46 -0700860 status_t handleVoipVolume_l(float *volume);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800861
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700862 // StreamOutHalInterfaceCallback implementation
863 virtual void onWriteReady();
864 virtual void onDrainReady();
865 virtual void onError();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800866
Andy Hung4b17e882023-07-07 13:47:37 -0700867public: // AsyncCallbackThread
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700868 void resetWriteBlocked(uint32_t sequence);
869 void resetDraining(uint32_t sequence);
Andy Hung4b17e882023-07-07 13:47:37 -0700870protected:
Eric Laurentbfb1b832013-01-07 09:53:42 -0800871
872 virtual bool waitingAsyncCallback();
873 virtual bool waitingAsyncCallback_l();
874 virtual bool shouldStandby_l();
Haynes Mathew George4c6a4332014-01-15 12:31:39 -0800875 virtual void onAddNewTrack_l();
Andy Hung4b17e882023-07-07 13:47:37 -0700876public: // AsyncCallbackThread
Haynes Mathew George4527b9e2016-07-07 19:54:17 -0700877 void onAsyncError(); // error reported by AsyncCallbackThread
Andy Hung4b17e882023-07-07 13:47:37 -0700878protected:
jiabinf6eb4c32020-02-25 14:06:25 -0800879 // StreamHalInterfaceCodecFormatCallback implementation
880 void onCodecFormatChanged(
Andy Hung3e4c8742023-06-29 21:19:25 -0700881 const std::basic_string<uint8_t>& metadataBs) final;
jiabinf6eb4c32020-02-25 14:06:25 -0800882
Eric Laurent81784c32012-11-19 14:55:58 -0800883 // ThreadBase virtuals
884 virtual void preExit();
885
Eric Laurent64667972016-03-30 18:19:46 -0700886 virtual bool keepWakeLock() const { return true; }
Andy Hungdae27702016-10-31 14:01:16 -0700887 virtual void acquireWakeLock_l() {
888 ThreadBase::acquireWakeLock_l();
889 mActiveTracks.updatePowerState(this, true /* force */);
890 }
Eric Laurent64667972016-03-30 18:19:46 -0700891
Eric Laurentb3f315a2021-07-13 15:09:05 +0200892 virtual void checkOutputStageEffects() {}
Eric Laurent68a40a82022-05-03 18:15:04 +0200893 virtual void setHalLatencyMode_l() {}
894
Eric Laurentb3f315a2021-07-13 15:09:05 +0200895
Andy Hung3e4c8742023-06-29 21:19:25 -0700896 void dumpInternals_l(int fd, const Vector<String16>& args) override;
897 void dumpTracks_l(int fd, const Vector<String16>& args) final;
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700898
Eric Laurent81784c32012-11-19 14:55:58 -0800899public:
900
Andy Hung3e4c8742023-06-29 21:19:25 -0700901 status_t initCheck() const final { return mOutput == nullptr ? NO_INIT : NO_ERROR; }
Eric Laurent81784c32012-11-19 14:55:58 -0800902
903 // return estimated latency in milliseconds, as reported by HAL
Andy Hung3e4c8742023-06-29 21:19:25 -0700904 uint32_t latency() const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800905 // same, but lock must already be held
Andy Hung3e4c8742023-06-29 21:19:25 -0700906 uint32_t latency_l() const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800907
Eric Laurent6acd1d42017-01-04 14:23:29 -0800908 // VolumeInterface
Andy Hung3e4c8742023-06-29 21:19:25 -0700909 void setMasterVolume(float value) final;
910 void setMasterBalance(float balance) override;
911 void setMasterMute(bool muted) final;
912 void setStreamVolume(audio_stream_type_t stream, float value) final;
913 void setStreamMute(audio_stream_type_t stream, bool muted) final;
914 float streamVolume(audio_stream_type_t stream) const final;
915 void setVolumeForOutput_l(float left, float right) const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800916
Andy Hung3e4c8742023-06-29 21:19:25 -0700917 sp<IAfTrack> createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -0700918 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -0800919 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700920 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -0800921 uint32_t *sampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -0800922 audio_format_t format,
923 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -0800924 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -0800925 size_t *pNotificationFrameCount,
926 uint32_t notificationsPerBuffer,
927 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -0800928 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -0800929 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -0700930 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700931 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +0000932 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -0800933 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800934 status_t *status /*non-NULL*/,
jiabinf6eb4c32020-02-25 14:06:25 -0800935 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200936 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +0000937 bool isSpatialized,
Andy Hung3e4c8742023-06-29 21:19:25 -0700938 bool isBitPerfect) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800939
Andy Hung0c1e11e2023-07-06 20:56:16 -0700940 bool isTrackActive(const sp<IAfTrack>& track) const final {
941 return mActiveTracks.indexOf(track) >= 0;
942 }
943
944 AudioStreamOut* getOutput_l() const final { return mOutput; }
Andy Hung3e4c8742023-06-29 21:19:25 -0700945 AudioStreamOut* getOutput() const final;
946 AudioStreamOut* clearOutput() final;
947 sp<StreamHalInterface> stream() const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800948
949 // a very large number of suspend() will eventually wraparound, but unlikely
Andy Hung3e4c8742023-06-29 21:19:25 -0700950 void suspend() final { (void) android_atomic_inc(&mSuspended); }
951 void restore() final
Eric Laurent81784c32012-11-19 14:55:58 -0800952 {
953 // if restore() is done without suspend(), get back into
954 // range so that the next suspend() will operate correctly
955 if (android_atomic_dec(&mSuspended) <= 0) {
956 android_atomic_release_store(0, &mSuspended);
957 }
958 }
Andy Hung3e4c8742023-06-29 21:19:25 -0700959 bool isSuspended() const final
Eric Laurent81784c32012-11-19 14:55:58 -0800960 { return android_atomic_acquire_load(&mSuspended) > 0; }
961
Andy Hung3e4c8742023-06-29 21:19:25 -0700962 String8 getParameters(const String8& keys);
963 void ioConfigChanged(audio_io_config_event_t event, pid_t pid = 0,
964 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final;
965 status_t getRenderPosition(uint32_t* halFrames, uint32_t* dspFrames) const final;
Andy Hung010a1a12014-03-13 13:57:33 -0700966 // Consider also removing and passing an explicit mMainBuffer initialization
Andy Hung11e74242023-06-26 19:20:57 -0700967 // parameter to AF::IAfTrack::Track().
Andy Hung3e4c8742023-06-29 21:19:25 -0700968 float* sinkBuffer() const final {
Andy Hung319587b2023-05-23 14:01:03 -0700969 return reinterpret_cast<float *>(mSinkBuffer); };
Eric Laurent81784c32012-11-19 14:55:58 -0800970
Andy Hung3e4c8742023-06-29 21:19:25 -0700971 void detachAuxEffect_l(int effectId) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800972
Andy Hung3e4c8742023-06-29 21:19:25 -0700973 status_t attachAuxEffect(const sp<IAfTrack>& track, int EffectId) final;
974 status_t attachAuxEffect_l(const sp<IAfTrack>& track, int EffectId) final;
975
976 status_t addEffectChain_l(const sp<IAfEffectChain>& chain) final;
977 size_t removeEffectChain_l(const sp<IAfEffectChain>& chain) final;
978 uint32_t hasAudioSession_l(audio_session_t sessionId) const final {
Andy Hungc3d62f92019-03-14 13:38:51 -0700979 return ThreadBase::hasAudioSession_l(sessionId, mTracks);
980 }
Andy Hung3e4c8742023-06-29 21:19:25 -0700981 product_strategy_t getStrategyForSession_l(audio_session_t sessionId) const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800982
983
Andy Hung3e4c8742023-06-29 21:19:25 -0700984 status_t setSyncEvent(const sp<audioflinger::SyncEvent>& event) final;
985 bool isValidSyncEvent(const sp<audioflinger::SyncEvent>& event) const final;
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700986
987 // called with AudioFlinger lock held
Andy Hung3e4c8742023-06-29 21:19:25 -0700988 bool invalidateTracks_l(audio_stream_type_t streamType) final;
989 bool invalidateTracks_l(std::set<audio_port_handle_t>& portIds) final;
990 void invalidateTracks(audio_stream_type_t streamType) override;
jiabinc44b3462022-12-08 12:52:31 -0800991 // Invalidate tracks by a set of port ids. The port id will be removed from
992 // the given set if the corresponding track is found and invalidated.
Andy Hung3e4c8742023-06-29 21:19:25 -0700993 void invalidateTracks(std::set<audio_port_handle_t>& portIds) override;
Eric Laurent81784c32012-11-19 14:55:58 -0800994
Andy Hung0c1e11e2023-07-06 20:56:16 -0700995 size_t frameCount() const final { return mNormalFrameCount; }
Glenn Kasten9b58f632013-07-16 11:37:48 -0700996
Andy Hung3e4c8742023-06-29 21:19:25 -0700997 audio_channel_mask_t mixerChannelMask() const final {
Eric Laurentf1f22e72021-07-13 14:04:14 +0200998 return mMixerChannelMask;
999 }
1000
Andy Hung3e4c8742023-06-29 21:19:25 -07001001 status_t getTimestamp_l(AudioTimestamp& timestamp) final;
Eric Laurent83b88082014-06-20 18:31:16 -07001002
Andy Hung3e4c8742023-06-29 21:19:25 -07001003 void addPatchTrack(const sp<IAfPatchTrack>& track) final;
1004 void deletePatchTrack(const sp<IAfPatchTrack>& track) final;
Eric Laurent83b88082014-06-20 18:31:16 -07001005
Andy Hung3e4c8742023-06-29 21:19:25 -07001006 void toAudioPortConfig(struct audio_port_config* config) final;
Eric Laurentaccc1472013-09-20 09:36:34 -07001007
Andy Hung10cbff12017-02-21 17:30:14 -08001008 // Return the asynchronous signal wait time.
Andy Hung3e4c8742023-06-29 21:19:25 -07001009 int64_t computeWaitTimeNs_l() const override { return INT64_MAX; }
Andy Hung1bc088a2018-02-09 15:57:31 -08001010 // returns true if the track is allowed to be added to the thread.
Andy Hung3e4c8742023-06-29 21:19:25 -07001011 bool isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08001012 audio_channel_mask_t channelMask __unused,
1013 audio_format_t format __unused,
1014 audio_session_t sessionId __unused,
Andy Hung3e4c8742023-06-29 21:19:25 -07001015 uid_t uid) const override {
Andy Hung1bc088a2018-02-09 15:57:31 -08001016 return trackCountForUid_l(uid) < PlaybackThread::kMaxTracksPerUid
1017 && mTracks.size() < PlaybackThread::kMaxTracks;
1018 }
1019
Andy Hung3e4c8742023-06-29 21:19:25 -07001020 bool isTimestampCorrectionEnabled() const final {
jiabinc52b1ff2019-10-31 17:20:42 -07001021 return audio_is_output_devices(mTimestampCorrectedDevice)
1022 && outDeviceTypes().count(mTimestampCorrectedDevice) != 0;
Andy Hungc8fddf32018-08-08 18:32:37 -07001023 }
jiabinc52b1ff2019-10-31 17:20:42 -07001024
Andy Hung3e4c8742023-06-29 21:19:25 -07001025 bool isStreamInitialized() const final {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001026 return !(mOutput == nullptr || mOutput->stream == nullptr);
1027 }
1028
Andy Hung3e4c8742023-06-29 21:19:25 -07001029 audio_channel_mask_t hapticChannelMask() const final {
jiabineb3bda02020-06-30 14:07:03 -07001030 return mHapticChannelMask;
1031 }
Andy Hung0c1e11e2023-07-06 20:56:16 -07001032
1033 uint32_t hapticChannelCount() const final {
1034 return mHapticChannelCount;
1035 }
1036
Andy Hung3e4c8742023-06-29 21:19:25 -07001037 bool supportsHapticPlayback() const final {
jiabineb3bda02020-06-30 14:07:03 -07001038 return (mHapticChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE;
1039 }
1040
Andy Hung3e4c8742023-06-29 21:19:25 -07001041 void setDownStreamPatch(const struct audio_patch* patch) final {
Eric Laurent74c38dc2020-12-23 18:19:44 +01001042 Mutex::Autolock _l(mLock);
1043 mDownStreamPatch = *patch;
1044 }
1045
Andy Hung3e4c8742023-06-29 21:19:25 -07001046 IAfTrack* getTrackById_l(audio_port_handle_t trackId) final;
jiabinf042b9b2021-05-07 23:46:28 +00001047
Andy Hung3e4c8742023-06-29 21:19:25 -07001048 bool hasMixer() const final {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001049 return mType == MIXER || mType == DUPLICATING || mType == SPATIALIZER;
Eric Laurentb3f315a2021-07-13 15:09:05 +02001050 }
Eric Laurent68a40a82022-05-03 18:15:04 +02001051
Andy Hung3e4c8742023-06-29 21:19:25 -07001052 status_t setRequestedLatencyMode(
1053 audio_latency_mode_t /* mode */) override { return INVALID_OPERATION; }
Eric Laurent68a40a82022-05-03 18:15:04 +02001054
Andy Hung3e4c8742023-06-29 21:19:25 -07001055 status_t getSupportedLatencyModes(
1056 std::vector<audio_latency_mode_t>* /* modes */) override {
Eric Laurent68a40a82022-05-03 18:15:04 +02001057 return INVALID_OPERATION;
1058 }
1059
Andy Hung3e4c8742023-06-29 21:19:25 -07001060 status_t setBluetoothVariableLatencyEnabled(bool /* enabled */) override{
Eric Laurentb0463942022-12-20 16:31:10 +01001061 return INVALID_OPERATION;
1062 }
Eric Laurent52057642022-12-16 11:45:07 +01001063
Andy Hung3e4c8742023-06-29 21:19:25 -07001064 void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) override;
1065 void stopMelComputation_l() override;
Vlad Popab042ee62022-10-20 18:05:00 +02001066
Andy Hung3e4c8742023-06-29 21:19:25 -07001067 void setStandby() final {
Eric Laurent19952e12023-04-20 10:08:29 +02001068 Mutex::Autolock _l(mLock);
1069 setStandby_l();
1070 }
1071
Andy Hung3e4c8742023-06-29 21:19:25 -07001072 void setStandby_l() final {
Eric Laurent19952e12023-04-20 10:08:29 +02001073 mStandby = true;
1074 mHalStarted = false;
1075 mKernelPositionOnStandby =
1076 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
1077 }
1078
Andy Hung3e4c8742023-06-29 21:19:25 -07001079 bool waitForHalStart() final {
Eric Laurent19952e12023-04-20 10:08:29 +02001080 Mutex::Autolock _l(mLock);
1081 static const nsecs_t kWaitHalTimeoutNs = seconds(2);
1082 nsecs_t endWaitTimetNs = systemTime() + kWaitHalTimeoutNs;
1083 while (!mHalStarted) {
1084 nsecs_t timeNs = systemTime();
1085 if (timeNs >= endWaitTimetNs) {
1086 break;
1087 }
1088 nsecs_t waitTimeLeftNs = endWaitTimetNs - timeNs;
1089 mWaitHalStartCV.waitRelative(mLock, waitTimeLeftNs);
1090 }
1091 return mHalStarted;
1092 }
Eric Laurent81784c32012-11-19 14:55:58 -08001093protected:
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001094 // updated by readOutputParameters_l()
Glenn Kasten9b58f632013-07-16 11:37:48 -07001095 size_t mNormalFrameCount; // normal mixer and effects
1096
Andy Hung08fb1742015-05-31 23:22:10 -07001097 bool mThreadThrottle; // throttle the thread processing
Andy Hung40eb1a12015-06-18 13:42:02 -07001098 uint32_t mThreadThrottleTimeMs; // throttle time for MIXER threads
1099 uint32_t mThreadThrottleEndMs; // notify once per throttling
Andy Hung08fb1742015-05-31 23:22:10 -07001100 uint32_t mHalfBufferMs; // half the buffer size in milliseconds
1101
Andy Hung010a1a12014-03-13 13:57:33 -07001102 void* mSinkBuffer; // frame size aligned sink buffer
Eric Laurent81784c32012-11-19 14:55:58 -08001103
Andy Hung98ef9782014-03-04 14:46:50 -08001104 // TODO:
1105 // Rearrange the buffer info into a struct/class with
1106 // clear, copy, construction, destruction methods.
1107 //
1108 // mSinkBuffer also has associated with it:
1109 //
1110 // mSinkBufferSize: Sink Buffer Size
1111 // mFormat: Sink Buffer Format
1112
Andy Hung69aed5f2014-02-25 17:24:40 -08001113 // Mixer Buffer (mMixerBuffer*)
1114 //
1115 // In the case of floating point or multichannel data, which is not in the
1116 // sink format, it is required to accumulate in a higher precision or greater channel count
1117 // buffer before downmixing or data conversion to the sink buffer.
1118
1119 // Set to "true" to enable the Mixer Buffer otherwise mixer output goes to sink buffer.
1120 bool mMixerBufferEnabled;
1121
1122 // Storage, 32 byte aligned (may make this alignment a requirement later).
1123 // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
1124 void* mMixerBuffer;
1125
1126 // Size of mMixerBuffer in bytes: mNormalFrameCount * #channels * sampsize.
1127 size_t mMixerBufferSize;
1128
1129 // The audio format of mMixerBuffer. Set to AUDIO_FORMAT_PCM_(FLOAT|16_BIT) only.
1130 audio_format_t mMixerBufferFormat;
1131
1132 // An internal flag set to true by MixerThread::prepareTracks_l()
1133 // when mMixerBuffer contains valid data after mixing.
1134 bool mMixerBufferValid;
1135
Andy Hung98ef9782014-03-04 14:46:50 -08001136 // Effects Buffer (mEffectsBuffer*)
1137 //
1138 // In the case of effects data, which is not in the sink format,
1139 // it is required to accumulate in a different buffer before data conversion
1140 // to the sink buffer.
1141
1142 // Set to "true" to enable the Effects Buffer otherwise effects output goes to sink buffer.
1143 bool mEffectBufferEnabled;
1144
1145 // Storage, 32 byte aligned (may make this alignment a requirement later).
1146 // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
1147 void* mEffectBuffer;
1148
1149 // Size of mEffectsBuffer in bytes: mNormalFrameCount * #channels * sampsize.
1150 size_t mEffectBufferSize;
1151
1152 // The audio format of mEffectsBuffer. Set to AUDIO_FORMAT_PCM_16_BIT only.
1153 audio_format_t mEffectBufferFormat;
1154
1155 // An internal flag set to true by MixerThread::prepareTracks_l()
1156 // when mEffectsBuffer contains valid data after mixing.
1157 //
1158 // When this is set, all mixer data is routed into the effects buffer
1159 // for any processing (including output processing).
1160 bool mEffectBufferValid;
1161
jiabinc658e452022-10-21 20:52:21 +00001162 // Set to "true" to enable when data has already copied to sink
1163 bool mHasDataCopiedToSinkBuffer = false;
1164
Eric Laurentb62d0362021-10-26 17:40:18 +02001165 // Frame size aligned buffer used as input and output to all post processing effects
1166 // except the Spatializer in a SPATIALIZER thread. Non spatialized tracks are mixed into
1167 // this buffer so that post processing effects can be applied.
1168 void* mPostSpatializerBuffer = nullptr;
1169
1170 // Size of mPostSpatializerBuffer in bytes
1171 size_t mPostSpatializerBufferSize;
Eric Laurent39095982021-08-24 18:29:27 +02001172
1173
Eric Laurent81784c32012-11-19 14:55:58 -08001174 // suspend count, > 0 means suspended. While suspended, the thread continues to pull from
1175 // tracks and mix, but doesn't write to HAL. A2DP and SCO HAL implementations can't handle
1176 // concurrent use of both of them, so Audio Policy Service suspends one of the threads to
1177 // workaround that restriction.
1178 // 'volatile' means accessed via atomic operations and no lock.
1179 volatile int32_t mSuspended;
1180
Andy Hung818e7a32016-02-16 18:08:07 -08001181 int64_t mBytesWritten;
yucliu6cfb5932022-07-20 17:40:39 -07001182 std::atomic<int64_t> mFramesWritten; // not reset on standby
Dean Wheatley12473e92021-03-18 23:00:55 +11001183 int64_t mLastFramesWritten = -1; // track changes in timestamp
1184 // server frames written.
Andy Hung238fa3d2016-07-28 10:53:22 -07001185 int64_t mSuspendedFrames; // not reset on standby
jiabin245cdd92018-12-07 17:55:15 -08001186
1187 // mHapticChannelMask and mHapticChannelCount will only be valid when the thread support
1188 // haptic playback.
1189 audio_channel_mask_t mHapticChannelMask = AUDIO_CHANNEL_NONE;
1190 uint32_t mHapticChannelCount = 0;
Eric Laurentf1f22e72021-07-13 14:04:14 +02001191
1192 audio_channel_mask_t mMixerChannelMask = AUDIO_CHANNEL_NONE;
1193
Eric Laurent81784c32012-11-19 14:55:58 -08001194 // mMasterMute is in both PlaybackThread and in AudioFlinger. When a
1195 // PlaybackThread needs to find out if master-muted, it checks it's local
1196 // copy rather than the one in AudioFlinger. This optimization saves a lock.
1197 bool mMasterMute;
1198 void setMasterMute_l(bool muted) { mMasterMute = muted; }
Dean Wheatley12473e92021-03-18 23:00:55 +11001199
1200 auto discontinuityForStandbyOrFlush() const { // call on threadLoop or with lock.
1201 return ((mType == DIRECT && !audio_is_linear_pcm(mFormat))
1202 || mType == OFFLOAD)
1203 ? mTimestampVerifier.DISCONTINUITY_MODE_ZERO
1204 : mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS;
1205 }
1206
Andy Hung11e74242023-06-26 19:20:57 -07001207 ActiveTracks<IAfTrack> mActiveTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08001208
Eric Laurent81784c32012-11-19 14:55:58 -08001209 // Time to sleep between cycles when:
1210 virtual uint32_t activeSleepTimeUs() const; // mixer state MIXER_TRACKS_ENABLED
1211 virtual uint32_t idleSleepTimeUs() const = 0; // mixer state MIXER_IDLE
1212 virtual uint32_t suspendSleepTimeUs() const = 0; // audio policy manager suspended us
1213 // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write()
1214 // No sleep in standby mode; waits on a condition
1215
1216 // Code snippets that are temporarily lifted up out of threadLoop() until the merge
Andy Hung3e4c8742023-06-29 21:19:25 -07001217 virtual void checkSilentMode_l() final; // consider unification with MMapThread
Eric Laurent81784c32012-11-19 14:55:58 -08001218
1219 // Non-trivial for DUPLICATING only
1220 virtual void saveOutputTracks() { }
1221 virtual void clearOutputTracks() { }
1222
1223 // Cache various calculated values, at threadLoop() entry and after a parameter change
1224 virtual void cacheParameters_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02001225 void setCheckOutputStageEffects() override {
1226 mCheckOutputStageEffects.store(true);
1227 }
Eric Laurent81784c32012-11-19 14:55:58 -08001228
1229 virtual uint32_t correctLatency_l(uint32_t latency) const;
1230
Eric Laurent1c333e22014-05-20 10:48:17 -07001231 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
1232 audio_patch_handle_t *handle);
1233 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle);
1234
Andy Hung0c1e11e2023-07-06 20:56:16 -07001235 bool usesHwAvSync() const final { return mType == DIRECT && mOutput != nullptr
Phil Burk6fc2a7c2015-04-30 16:08:10 -07001236 && mHwSupportsPause
1237 && (mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC); }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08001238
Andy Hung1bc088a2018-02-09 15:57:31 -08001239 uint32_t trackCountForUid_l(uid_t uid) const;
Eric Laurentad7dd962016-09-22 12:38:37 -07001240
jiabineb3bda02020-06-30 14:07:03 -07001241 void invalidateTracksForAudioSession_l(
Andy Hung3e4c8742023-06-29 21:19:25 -07001242 audio_session_t sessionId) const override {
jiabineb3bda02020-06-30 14:07:03 -07001243 ThreadBase::invalidateTracksForAudioSession_l(sessionId, mTracks);
1244 }
1245
Mikhail Naganovbf493082017-04-17 17:37:12 -07001246 DISALLOW_COPY_AND_ASSIGN(PlaybackThread);
Eric Laurent81784c32012-11-19 14:55:58 -08001247
Andy Hung0c1e11e2023-07-06 20:56:16 -07001248 status_t addTrack_l(const sp<IAfTrack>& track) final;
1249 bool destroyTrack_l(const sp<IAfTrack>& track) final;
1250
Andy Hung11e74242023-06-26 19:20:57 -07001251 void removeTrack_l(const sp<IAfTrack>& track);
Eric Laurent81784c32012-11-19 14:55:58 -08001252
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001253 void readOutputParameters_l();
Vlad Popa7e81cea2023-01-19 16:34:16 +01001254 MetadataUpdate updateMetadata_l() final;
Kevin Rocardc86a7f72018-04-03 09:00:09 -07001255 virtual void sendMetadataToBackend_l(const StreamOutHalInterface::SourceMetadata& metadata);
Eric Laurent81784c32012-11-19 14:55:58 -08001256
Dean Wheatley12473e92021-03-18 23:00:55 +11001257 void collectTimestamps_l();
1258
Andy Hungc0691382018-09-12 18:01:57 -07001259 // The Tracks class manages tracks added and removed from the Thread.
Andy Hung1bc088a2018-02-09 15:57:31 -08001260 template <typename T>
1261 class Tracks {
1262 public:
Andy Hung920f6572022-10-06 12:09:49 -07001263 explicit Tracks(bool saveDeletedTrackIds) :
Andy Hungc0691382018-09-12 18:01:57 -07001264 mSaveDeletedTrackIds(saveDeletedTrackIds) { }
Andy Hung1bc088a2018-02-09 15:57:31 -08001265
1266 // SortedVector methods
Andy Hungc0691382018-09-12 18:01:57 -07001267 ssize_t add(const sp<T> &track) {
1268 const ssize_t index = mTracks.add(track);
1269 LOG_ALWAYS_FATAL_IF(index < 0, "cannot add track");
1270 return index;
1271 }
Andy Hung1bc088a2018-02-09 15:57:31 -08001272 ssize_t remove(const sp<T> &track);
1273 size_t size() const {
1274 return mTracks.size();
1275 }
1276 bool isEmpty() const {
1277 return mTracks.isEmpty();
1278 }
1279 ssize_t indexOf(const sp<T> &item) {
1280 return mTracks.indexOf(item);
1281 }
1282 sp<T> operator[](size_t index) const {
1283 return mTracks[index];
1284 }
1285 typename SortedVector<sp<T>>::iterator begin() {
1286 return mTracks.begin();
1287 }
1288 typename SortedVector<sp<T>>::iterator end() {
1289 return mTracks.end();
1290 }
1291
Andy Hung920f6572022-10-06 12:09:49 -07001292 size_t processDeletedTrackIds(const std::function<void(int)>& f) {
Andy Hungc0691382018-09-12 18:01:57 -07001293 for (const int trackId : mDeletedTrackIds) {
1294 f(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08001295 }
Andy Hungc0691382018-09-12 18:01:57 -07001296 return mDeletedTrackIds.size();
Andy Hung1bc088a2018-02-09 15:57:31 -08001297 }
1298
Andy Hungc0691382018-09-12 18:01:57 -07001299 void clearDeletedTrackIds() { mDeletedTrackIds.clear(); }
Andy Hung1bc088a2018-02-09 15:57:31 -08001300
1301 private:
Andy Hungc0691382018-09-12 18:01:57 -07001302 // Tracks pending deletion for MIXER type threads
1303 const bool mSaveDeletedTrackIds; // true to enable tracking
1304 std::set<int> mDeletedTrackIds;
Andy Hung1bc088a2018-02-09 15:57:31 -08001305
1306 SortedVector<sp<T>> mTracks; // wrapped SortedVector.
1307 };
1308
Andy Hung11e74242023-06-26 19:20:57 -07001309 Tracks<IAfTrack> mTracks;
Andy Hung1bc088a2018-02-09 15:57:31 -08001310
Eric Laurent223fd5c2014-11-11 13:43:36 -08001311 stream_type_t mStreamTypes[AUDIO_STREAM_CNT];
Andy Hung4b17e882023-07-07 13:47:37 -07001312
Eric Laurent81784c32012-11-19 14:55:58 -08001313 AudioStreamOut *mOutput;
1314
1315 float mMasterVolume;
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001316 std::atomic<float> mMasterBalance{};
1317 audio_utils::Balance mBalance;
Eric Laurent81784c32012-11-19 14:55:58 -08001318 int mNumWrites;
1319 int mNumDelayedWrites;
1320 bool mInWrite;
1321
1322 // FIXME rename these former local variables of threadLoop to standard "m" names
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001323 nsecs_t mStandbyTimeNs;
Andy Hung25c2dac2014-02-27 14:56:00 -08001324 size_t mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001325
1326 // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l()
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001327 uint32_t mActiveSleepTimeUs;
1328 uint32_t mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08001329
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001330 uint32_t mSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08001331
1332 // mixer status returned by prepareTracks_l()
1333 mixer_state mMixerStatus; // current cycle
1334 // previous cycle when in prepareTracks_l()
1335 mixer_state mMixerStatusIgnoringFastTracks;
1336 // FIXME or a separate ready state per track
1337
1338 // FIXME move these declarations into the specific sub-class that needs them
1339 // MIXER only
1340 uint32_t sleepTimeShift;
1341
1342 // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001343 nsecs_t mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08001344
1345 // MIXER only
1346 nsecs_t maxPeriod;
1347
1348 // DUPLICATING only
1349 uint32_t writeFrames;
1350
Eric Laurentbfb1b832013-01-07 09:53:42 -08001351 size_t mBytesRemaining;
1352 size_t mCurrentWriteLength;
1353 bool mUseAsyncWrite;
Eric Laurent3b4529e2013-09-05 18:09:19 -07001354 // mWriteAckSequence contains current write sequence on bits 31-1. The write sequence is
1355 // incremented each time a write(), a flush() or a standby() occurs.
1356 // Bit 0 is set when a write blocks and indicates a callback is expected.
1357 // Bit 0 is reset by the async callback thread calling resetWriteBlocked(). Out of sequence
1358 // callbacks are ignored.
1359 uint32_t mWriteAckSequence;
1360 // mDrainSequence contains current drain sequence on bits 31-1. The drain sequence is
1361 // incremented each time a drain is requested or a flush() or standby() occurs.
1362 // Bit 0 is set when the drain() command is called at the HAL and indicates a callback is
1363 // expected.
1364 // Bit 0 is reset by the async callback thread calling resetDraining(). Out of sequence
1365 // callbacks are ignored.
1366 uint32_t mDrainSequence;
Andy Hung4b17e882023-07-07 13:47:37 -07001367
Eric Laurentbfb1b832013-01-07 09:53:42 -08001368 sp<AsyncCallbackThread> mCallbackThread;
1369
jiabinf6eb4c32020-02-25 14:06:25 -08001370 Mutex mAudioTrackCbLock;
1371 // Record of IAudioTrackCallback
Andy Hung11e74242023-06-26 19:20:57 -07001372 std::map<sp<IAfTrack>, sp<media::IAudioTrackCallback>> mAudioTrackCallbacks;
jiabinf6eb4c32020-02-25 14:06:25 -08001373
Eric Laurent81784c32012-11-19 14:55:58 -08001374 // The HAL output sink is treated as non-blocking, but current implementation is blocking
1375 sp<NBAIO_Sink> mOutputSink;
1376 // If a fast mixer is present, the blocking pipe sink, otherwise clear
1377 sp<NBAIO_Sink> mPipeSink;
1378 // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink
1379 sp<NBAIO_Sink> mNormalSink;
Andy Hung4b17e882023-07-07 13:47:37 -07001380
Eric Laurent81784c32012-11-19 14:55:58 -08001381 uint32_t mScreenState; // cached copy of gScreenState
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07001382 // TODO: add comment and adjust size as needed
Glenn Kasteneef598c2017-04-03 14:41:13 -07001383 static const size_t kFastMixerLogSize = 8 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -08001384 sp<NBLog::Writer> mFastMixerNBLogWriter;
Andy Hung2148bf02016-11-28 19:01:02 -08001385
Dean Wheatley30d28422018-11-06 10:27:40 +11001386 // Downstream patch latency, available if mDownstreamLatencyStatMs.getN() > 0.
1387 audio_utils::Statistics<double> mDownstreamLatencyStatMs{0.999};
Andy Hung2148bf02016-11-28 19:01:02 -08001388
Eric Laurent19952e12023-04-20 10:08:29 +02001389 // output stream start detection based on render position returned by the kernel
1390 // condition signalled when the output stream has started
1391 Condition mWaitHalStartCV;
1392 // true when the output stream render position has moved, reset to false in standby
1393 bool mHalStarted = false;
1394 // last kernel render position saved when entering standby
1395 int64_t mKernelPositionOnStandby = 0;
1396
Eric Laurent81784c32012-11-19 14:55:58 -08001397public:
Andy Hung3e4c8742023-06-29 21:19:25 -07001398 FastTrackUnderruns getFastTrackUnderruns(size_t /* fastIndex */) const override
1399 { return {}; }
1400 const std::atomic<int64_t>& framesWritten() const final { return mFramesWritten; }
Eric Laurent81784c32012-11-19 14:55:58 -08001401
1402protected:
1403 // accessed by both binder threads and within threadLoop(), lock on mutex needed
Andy Hung0c1e11e2023-07-06 20:56:16 -07001404 uint32_t& fastTrackAvailMask_l() final { return mFastTrackAvailMask; }
1405 uint32_t mFastTrackAvailMask; // bit i set if fast track [i] is available
Eric Laurentd1f69b02014-12-15 14:33:13 -08001406 bool mHwSupportsPause;
1407 bool mHwPaused;
1408 bool mFlushPending;
Eric Laurent7c29ec92017-09-20 17:54:22 -07001409 // volumes last sent to audio HAL with stream->setVolume()
1410 float mLeftVolFloat;
1411 float mRightVolFloat;
Eric Laurent74c38dc2020-12-23 18:19:44 +01001412
1413 // audio patch used by the downstream software patch.
1414 // Only used if ThreadBase::mIsMsdDevice is true.
1415 struct audio_patch mDownStreamPatch;
Eric Laurentb3f315a2021-07-13 15:09:05 +02001416
1417 std::atomic_bool mCheckOutputStageEffects{};
ziyangch8f194f12021-12-01 13:48:04 -08001418
ziyangch8f194f12021-12-01 13:48:04 -08001419
Brian Lindahl65e90012022-07-27 18:01:07 +02001420 // Provides periodic checking for timestamp advancement for underrun detection.
1421 class IsTimestampAdvancing {
1422 public:
1423 // The timestamp will not be checked any faster than the specified time.
Andy Hung920f6572022-10-06 12:09:49 -07001424 explicit IsTimestampAdvancing(nsecs_t minimumTimeBetweenChecksNs)
Brian Lindahl65e90012022-07-27 18:01:07 +02001425 : mMinimumTimeBetweenChecksNs(minimumTimeBetweenChecksNs)
1426 {
1427 clear();
1428 }
1429 // Check if the presentation position has advanced in the last periodic time.
1430 bool check(AudioStreamOut * output);
1431 // Clear the internal state when the playback state changes for the output
1432 // stream.
1433 void clear();
1434 private:
1435 // The minimum time between timestamp checks.
1436 const nsecs_t mMinimumTimeBetweenChecksNs;
1437 // Add differential check on the timestamps to see if there is a change in the
1438 // timestamp frame position between the last call to check.
1439 uint64_t mPreviousPosition;
1440 // The time at which the last check occurred, to ensure we don't check too
1441 // frequently, giving the Audio HAL enough time to update its timestamps.
1442 nsecs_t mPreviousNs;
1443 // The valued is latched so we don't check timestamps too frequently.
1444 bool mLatchedValue;
1445 };
1446 IsTimestampAdvancing mIsTimestampAdvancing;
ziyangch8f194f12021-12-01 13:48:04 -08001447
Brian Lindahl65e90012022-07-27 18:01:07 +02001448 virtual void flushHw_l() {
1449 mIsTimestampAdvancing.clear();
1450 }
Eric Laurent81784c32012-11-19 14:55:58 -08001451};
1452
Eric Laurentb0463942022-12-20 16:31:10 +01001453class MixerThread : public PlaybackThread,
1454 public StreamOutHalInterfaceLatencyModeCallback {
Eric Laurent81784c32012-11-19 14:55:58 -08001455public:
Andy Hung7535ed92023-07-17 17:05:00 -07001456 MixerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08001457 AudioStreamOut* output,
1458 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001459 bool systemReady,
Eric Laurentf1f22e72021-07-13 14:04:14 +02001460 type_t type = MIXER,
1461 audio_config_base_t *mixerConfig = nullptr);
Andy Hung3e4c8742023-06-29 21:19:25 -07001462 ~MixerThread() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001463
Eric Laurentb0463942022-12-20 16:31:10 +01001464 // RefBase
Andy Hung3e4c8742023-06-29 21:19:25 -07001465 void onFirstRef() override;
Eric Laurentb0463942022-12-20 16:31:10 +01001466
1467 // StreamOutHalInterfaceLatencyModeCallback
1468 void onRecommendedLatencyModeChanged(
Andy Hung3e4c8742023-06-29 21:19:25 -07001469 std::vector<audio_latency_mode_t> modes) final;
Eric Laurentb0463942022-12-20 16:31:10 +01001470
Eric Laurent81784c32012-11-19 14:55:58 -08001471 // Thread virtuals
1472
Andy Hung3e4c8742023-06-29 21:19:25 -07001473 bool checkForNewParameter_l(const String8& keyValuePair, status_t& status) final;
Eric Laurent81784c32012-11-19 14:55:58 -08001474
Andy Hung3e4c8742023-06-29 21:19:25 -07001475 bool isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08001476 audio_channel_mask_t channelMask, audio_format_t format,
Andy Hung3e4c8742023-06-29 21:19:25 -07001477 audio_session_t sessionId, uid_t uid) const final;
Eric Laurent81784c32012-11-19 14:55:58 -08001478protected:
Andy Hung3e4c8742023-06-29 21:19:25 -07001479 mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove) override;
1480 uint32_t idleSleepTimeUs() const final;
1481 uint32_t suspendSleepTimeUs() const final;
1482 void cacheParameters_l() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001483
Andy Hung3e4c8742023-06-29 21:19:25 -07001484 void acquireWakeLock_l() final {
Andy Hungdae27702016-10-31 14:01:16 -07001485 PlaybackThread::acquireWakeLock_l();
Andy Hung818e7a32016-02-16 18:08:07 -08001486 if (hasFastMixer()) {
1487 mFastMixer->setBoottimeOffset(
1488 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME]);
1489 }
1490 }
1491
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001492 void dumpInternals_l(int fd, const Vector<String16>& args) override;
1493
Eric Laurent81784c32012-11-19 14:55:58 -08001494 // threadLoop snippets
Andy Hung3e4c8742023-06-29 21:19:25 -07001495 ssize_t threadLoop_write() override;
1496 void threadLoop_standby() override;
1497 void threadLoop_mix() override;
1498 void threadLoop_sleepTime() override;
1499 uint32_t correctLatency_l(uint32_t latency) const final;
Eric Laurent81784c32012-11-19 14:55:58 -08001500
Andy Hung3e4c8742023-06-29 21:19:25 -07001501 status_t createAudioPatch_l(
1502 const struct audio_patch* patch, audio_patch_handle_t* handle) final;
1503 status_t releaseAudioPatch_l(const audio_patch_handle_t handle) final;
Eric Laurent054d9d32015-04-24 08:48:48 -07001504
Eric Laurent81784c32012-11-19 14:55:58 -08001505 AudioMixer* mAudioMixer; // normal mixer
Eric Laurentb0463942022-12-20 16:31:10 +01001506
1507 // Support low latency mode by default as unless explicitly indicated by the audio HAL
1508 // we assume the audio path is compatible with the head tracking latency requirements
1509 std::vector<audio_latency_mode_t> mSupportedLatencyModes = {AUDIO_LATENCY_MODE_LOW};
1510 // default to invalid value to force first update to the audio HAL
1511 audio_latency_mode_t mSetLatencyMode =
1512 (audio_latency_mode_t)AUDIO_LATENCY_MODE_INVALID;
1513
1514 // Bluetooth Variable latency control logic is enabled or disabled for this thread
1515 std::atomic_bool mBluetoothLatencyModesEnabled;
1516
Eric Laurent81784c32012-11-19 14:55:58 -08001517private:
1518 // one-time initialization, no locks required
Glenn Kasten4d23ca32014-05-13 10:39:51 -07001519 sp<FastMixer> mFastMixer; // non-0 if there is also a fast mixer
Eric Laurent81784c32012-11-19 14:55:58 -08001520 sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread
1521
1522 // contents are not guaranteed to be consistent, no locks required
1523 FastMixerDumpState mFastMixerDumpState;
1524#ifdef STATE_QUEUE_DUMP
1525 StateQueueObserverDump mStateQueueObserverDump;
1526 StateQueueMutatorDump mStateQueueMutatorDump;
1527#endif
1528 AudioWatchdogDump mAudioWatchdogDump;
1529
1530 // accessible only within the threadLoop(), no locks required
1531 // mFastMixer->sq() // for mutating and pushing state
1532 int32_t mFastMixerFutex; // for cold idle
1533
Andy Hung2ddee192015-12-18 17:34:44 -08001534 std::atomic_bool mMasterMono;
Eric Laurent81784c32012-11-19 14:55:58 -08001535public:
Glenn Kasten4d23ca32014-05-13 10:39:51 -07001536 virtual bool hasFastMixer() const { return mFastMixer != 0; }
Eric Laurent81784c32012-11-19 14:55:58 -08001537 virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const {
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001538 ALOG_ASSERT(fastIndex < FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08001539 return mFastMixerDumpState.mTracks[fastIndex].mUnderruns;
1540 }
Eric Laurent83b88082014-06-20 18:31:16 -07001541
Andy Hung1c86ebe2018-05-29 20:29:08 -07001542 status_t threadloop_getHalTimestamp_l(
1543 ExtendedTimestamp *timestamp) const override {
1544 if (mNormalSink.get() != nullptr) {
1545 return mNormalSink->getTimestamp(*timestamp);
1546 }
1547 return INVALID_OPERATION;
1548 }
1549
Eric Laurentb0463942022-12-20 16:31:10 +01001550 status_t getSupportedLatencyModes(
1551 std::vector<audio_latency_mode_t>* modes) override;
1552
1553 status_t setBluetoothVariableLatencyEnabled(bool enabled) override;
1554
Andy Hung2ddee192015-12-18 17:34:44 -08001555protected:
1556 virtual void setMasterMono_l(bool mono) {
1557 mMasterMono.store(mono);
1558 if (mFastMixer != nullptr) { /* hasFastMixer() */
1559 mFastMixer->setMasterMono(mMasterMono);
1560 }
1561 }
1562 // the FastMixer performs mono blend if it exists.
Glenn Kasten03c48d52016-01-27 17:25:17 -08001563 // Blending with limiter is not idempotent,
1564 // and blending without limiter is idempotent but inefficient to do twice.
Andy Hung2ddee192015-12-18 17:34:44 -08001565 virtual bool requireMonoBlend() { return mMasterMono.load() && !hasFastMixer(); }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001566
1567 void setMasterBalance(float balance) override {
1568 mMasterBalance.store(balance);
1569 if (hasFastMixer()) {
1570 mFastMixer->setMasterBalance(balance);
1571 }
1572 }
Eric Laurentb0463942022-12-20 16:31:10 +01001573
1574 void updateHalSupportedLatencyModes_l();
1575 void onHalLatencyModesChanged_l() override;
1576 void setHalLatencyMode_l() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001577};
1578
Andy Hung0c1e11e2023-07-06 20:56:16 -07001579class DirectOutputThread : public PlaybackThread, public virtual IAfDirectOutputThread {
Eric Laurent81784c32012-11-19 14:55:58 -08001580public:
1581
Andy Hung0c1e11e2023-07-06 20:56:16 -07001582 sp<IAfDirectOutputThread> asIAfDirectOutputThread() final {
1583 return sp<IAfDirectOutputThread>::fromExisting(this);
1584 }
1585
Andy Hung7535ed92023-07-17 17:05:00 -07001586 DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Gareth Fennb18c1a32022-10-05 13:42:36 -07001587 audio_io_handle_t id, bool systemReady,
1588 const audio_offload_info_t& offloadInfo)
Andy Hung7535ed92023-07-17 17:05:00 -07001589 : DirectOutputThread(afThreadCallback, output, id, DIRECT, systemReady, offloadInfo) { }
Andy Hung48f59ed2019-01-28 15:06:59 -08001590
Eric Laurent81784c32012-11-19 14:55:58 -08001591 virtual ~DirectOutputThread();
1592
Andy Hung0c1e11e2023-07-06 20:56:16 -07001593 status_t selectPresentation(int presentationId, int programId) final;
Mikhail Naganovac917ac2018-11-28 14:03:52 -08001594
Eric Laurent81784c32012-11-19 14:55:58 -08001595 // Thread virtuals
1596
Eric Laurent10351942014-05-08 18:49:52 -07001597 virtual bool checkForNewParameter_l(const String8& keyValuePair,
1598 status_t& status);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001599
ziyangch8f194f12021-12-01 13:48:04 -08001600 void flushHw_l() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001601
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001602 void setMasterBalance(float balance) override;
1603
Eric Laurent81784c32012-11-19 14:55:58 -08001604protected:
Eric Laurent81784c32012-11-19 14:55:58 -08001605 virtual uint32_t activeSleepTimeUs() const;
1606 virtual uint32_t idleSleepTimeUs() const;
1607 virtual uint32_t suspendSleepTimeUs() const;
1608 virtual void cacheParameters_l();
1609
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001610 void dumpInternals_l(int fd, const Vector<String16>& args) override;
1611
Eric Laurent81784c32012-11-19 14:55:58 -08001612 // threadLoop snippets
Andy Hung11e74242023-06-26 19:20:57 -07001613 virtual mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08001614 virtual void threadLoop_mix();
1615 virtual void threadLoop_sleepTime();
Eric Laurentd1f69b02014-12-15 14:33:13 -08001616 virtual void threadLoop_exit();
1617 virtual bool shouldStandby_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001618
Phil Burk43b4dcc2015-06-09 16:53:44 -07001619 virtual void onAddNewTrack_l();
1620
Gareth Fennb18c1a32022-10-05 13:42:36 -07001621 const audio_offload_info_t mOffloadInfo;
Andy Hung398ffa22022-12-13 19:19:53 -08001622
1623 audioflinger::MonotonicFrameCounter mMonotonicFrameCounter; // for VolumeShaper
Andy Hung48f59ed2019-01-28 15:06:59 -08001624 bool mVolumeShaperActive = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001625
Andy Hung7535ed92023-07-17 17:05:00 -07001626 DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Gareth Fennb18c1a32022-10-05 13:42:36 -07001627 audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
1628 const audio_offload_info_t& offloadInfo);
Andy Hung11e74242023-06-26 19:20:57 -07001629 void processVolume_l(IAfTrack *track, bool lastTrack);
Gareth Fennb18c1a32022-10-05 13:42:36 -07001630 bool isTunerStream() const { return (mOffloadInfo.content_id > 0); }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001631
Eric Laurent81784c32012-11-19 14:55:58 -08001632 // prepareTracks_l() tells threadLoop_mix() the name of the single active track
Andy Hung11e74242023-06-26 19:20:57 -07001633 sp<IAfTrack> mActiveTrack;
Phil Burk43b4dcc2015-06-09 16:53:44 -07001634
Andy Hung11e74242023-06-26 19:20:57 -07001635 wp<IAfTrack> mPreviousTrack; // used to detect track switch
Phil Burk43b4dcc2015-06-09 16:53:44 -07001636
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001637 // This must be initialized for initial condition of mMasterBalance = 0 (disabled).
1638 float mMasterBalanceLeft = 1.f;
1639 float mMasterBalanceRight = 1.f;
1640
Eric Laurent81784c32012-11-19 14:55:58 -08001641public:
1642 virtual bool hasFastMixer() const { return false; }
Andy Hung10cbff12017-02-21 17:30:14 -08001643
1644 virtual int64_t computeWaitTimeNs_l() const override;
Andy Hungf3234512018-07-03 14:51:47 -07001645
1646 status_t threadloop_getHalTimestamp_l(ExtendedTimestamp *timestamp) const override {
1647 // For DIRECT and OFFLOAD threads, query the output sink directly.
1648 if (mOutput != nullptr) {
1649 uint64_t uposition64;
1650 struct timespec time;
1651 if (mOutput->getPresentationPosition(
1652 &uposition64, &time) == OK) {
1653 timestamp->mPosition[ExtendedTimestamp::LOCATION_KERNEL]
1654 = (int64_t)uposition64;
1655 timestamp->mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
1656 = audio_utils_ns_from_timespec(&time);
1657 return NO_ERROR;
1658 }
1659 }
1660 return INVALID_OPERATION;
1661 }
Eric Laurent81784c32012-11-19 14:55:58 -08001662};
1663
Eric Laurentbfb1b832013-01-07 09:53:42 -08001664class OffloadThread : public DirectOutputThread {
1665public:
1666
Andy Hung7535ed92023-07-17 17:05:00 -07001667 OffloadThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Gareth Fennb18c1a32022-10-05 13:42:36 -07001668 audio_io_handle_t id, bool systemReady,
1669 const audio_offload_info_t& offloadInfo);
Eric Laurent6a51d7e2013-10-17 18:59:26 -07001670 virtual ~OffloadThread() {};
ziyangch8f194f12021-12-01 13:48:04 -08001671 void flushHw_l() override;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001672
1673protected:
1674 // threadLoop snippets
Andy Hung11e74242023-06-26 19:20:57 -07001675 virtual mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001676 virtual void threadLoop_exit();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001677
1678 virtual bool waitingAsyncCallback();
1679 virtual bool waitingAsyncCallback_l();
Haynes Mathew George05317d22016-05-03 16:34:26 -07001680 virtual void invalidateTracks(audio_stream_type_t streamType);
jiabinc44b3462022-12-08 12:52:31 -08001681 void invalidateTracks(std::set<audio_port_handle_t>& portIds) override;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001682
Eric Laurentde0613d2016-07-22 18:19:11 -07001683 virtual bool keepWakeLock() const { return (mKeepWakeLock || (mDrainSequence & 1)); }
Eric Laurent64667972016-03-30 18:19:46 -07001684
Eric Laurentbfb1b832013-01-07 09:53:42 -08001685private:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001686 size_t mPausedWriteLength; // length in bytes of write interrupted by pause
1687 size_t mPausedBytesRemaining; // bytes still waiting in mixbuffer after resume
Eric Laurent64667972016-03-30 18:19:46 -07001688 bool mKeepWakeLock; // keep wake lock while waiting for write callback
Eric Laurentbfb1b832013-01-07 09:53:42 -08001689};
1690
1691class AsyncCallbackThread : public Thread {
1692public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001693 explicit AsyncCallbackThread(const wp<PlaybackThread>& playbackThread);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001694
Eric Laurentbfb1b832013-01-07 09:53:42 -08001695 // Thread virtuals
1696 virtual bool threadLoop();
1697
1698 // RefBase
1699 virtual void onFirstRef();
1700
1701 void exit();
Eric Laurent3b4529e2013-09-05 18:09:19 -07001702 void setWriteBlocked(uint32_t sequence);
1703 void resetWriteBlocked();
1704 void setDraining(uint32_t sequence);
1705 void resetDraining();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07001706 void setAsyncError();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001707
1708private:
Eric Laurent4de95592013-09-26 15:28:21 -07001709 const wp<PlaybackThread> mPlaybackThread;
Eric Laurent3b4529e2013-09-05 18:09:19 -07001710 // mWriteAckSequence corresponds to the last write sequence passed by the offload thread via
1711 // setWriteBlocked(). The sequence is shifted one bit to the left and the lsb is used
1712 // to indicate that the callback has been received via resetWriteBlocked()
Eric Laurent4de95592013-09-26 15:28:21 -07001713 uint32_t mWriteAckSequence;
Eric Laurent3b4529e2013-09-05 18:09:19 -07001714 // mDrainSequence corresponds to the last drain sequence passed by the offload thread via
1715 // setDraining(). The sequence is shifted one bit to the left and the lsb is used
1716 // to indicate that the callback has been received via resetDraining()
Eric Laurent4de95592013-09-26 15:28:21 -07001717 uint32_t mDrainSequence;
1718 Condition mWaitWorkCV;
1719 Mutex mLock;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07001720 bool mAsyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001721};
1722
Andy Hung0c1e11e2023-07-06 20:56:16 -07001723class DuplicatingThread : public MixerThread, public IAfDuplicatingThread {
Eric Laurent81784c32012-11-19 14:55:58 -08001724public:
Andy Hung7535ed92023-07-17 17:05:00 -07001725 DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
1726 IAfPlaybackThread* mainThread,
Eric Laurent72e3f392015-05-20 14:43:50 -07001727 audio_io_handle_t id, bool systemReady);
Andy Hung0c1e11e2023-07-06 20:56:16 -07001728 ~DuplicatingThread() override;
1729
1730 sp<IAfDuplicatingThread> asIAfDuplicatingThread() final {
1731 return sp<IAfDuplicatingThread>::fromExisting(this);
1732 }
Eric Laurent81784c32012-11-19 14:55:58 -08001733
1734 // Thread virtuals
Andy Hung0c1e11e2023-07-06 20:56:16 -07001735 void addOutputTrack(IAfPlaybackThread* thread) final;
1736 void removeOutputTrack(IAfPlaybackThread* thread) final;
1737 uint32_t waitTimeMs() const final { return mWaitTimeMs; }
Kevin Rocard069c2712018-03-29 19:09:14 -07001738
Kevin Rocardc86a7f72018-04-03 09:00:09 -07001739 void sendMetadataToBackend_l(
1740 const StreamOutHalInterface::SourceMetadata& metadata) override;
Eric Laurent81784c32012-11-19 14:55:58 -08001741protected:
1742 virtual uint32_t activeSleepTimeUs() const;
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001743 void dumpInternals_l(int fd, const Vector<String16>& args) override;
Eric Laurent81784c32012-11-19 14:55:58 -08001744
1745private:
Andy Hung920f6572022-10-06 12:09:49 -07001746 bool outputsReady();
Eric Laurent81784c32012-11-19 14:55:58 -08001747protected:
1748 // threadLoop snippets
1749 virtual void threadLoop_mix();
1750 virtual void threadLoop_sleepTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001751 virtual ssize_t threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08001752 virtual void threadLoop_standby();
1753 virtual void cacheParameters_l();
1754
1755private:
1756 // called from threadLoop, addOutputTrack, removeOutputTrack
1757 virtual void updateWaitTime_l();
1758protected:
1759 virtual void saveOutputTracks();
1760 virtual void clearOutputTracks();
1761private:
1762
1763 uint32_t mWaitTimeMs;
Andy Hung11e74242023-06-26 19:20:57 -07001764 SortedVector <sp<IAfOutputTrack>> outputTracks;
1765 SortedVector <sp<IAfOutputTrack>> mOutputTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08001766public:
1767 virtual bool hasFastMixer() const { return false; }
Andy Hung1c86ebe2018-05-29 20:29:08 -07001768 status_t threadloop_getHalTimestamp_l(
1769 ExtendedTimestamp *timestamp) const override {
1770 if (mOutputTracks.size() > 0) {
1771 // forward the first OutputTrack's kernel information for timestamp.
1772 const ExtendedTimestamp trackTimestamp =
1773 mOutputTracks[0]->getClientProxyTimestamp();
1774 if (trackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] > 0) {
1775 timestamp->mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
1776 trackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
1777 timestamp->mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
1778 trackTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
1779 return OK; // discard server timestamp - that's ignored.
1780 }
1781 }
1782 return INVALID_OPERATION;
1783 }
Eric Laurent81784c32012-11-19 14:55:58 -08001784};
1785
Eric Laurentb0463942022-12-20 16:31:10 +01001786class SpatializerThread : public MixerThread {
Eric Laurentb3f315a2021-07-13 15:09:05 +02001787public:
Andy Hung7535ed92023-07-17 17:05:00 -07001788 SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02001789 AudioStreamOut* output,
1790 audio_io_handle_t id,
1791 bool systemReady,
1792 audio_config_base_t *mixerConfig);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001793
Andy Hung3e4c8742023-06-29 21:19:25 -07001794 bool hasFastMixer() const final { return false; }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001795
Eric Laurent68a40a82022-05-03 18:15:04 +02001796 // RefBase
Andy Hung3e4c8742023-06-29 21:19:25 -07001797 void onFirstRef() final;
Eric Laurent68a40a82022-05-03 18:15:04 +02001798
Andy Hung3e4c8742023-06-29 21:19:25 -07001799 status_t setRequestedLatencyMode(audio_latency_mode_t mode) final;
Eric Laurent68a40a82022-05-03 18:15:04 +02001800
Eric Laurentb3f315a2021-07-13 15:09:05 +02001801protected:
Andy Hung3e4c8742023-06-29 21:19:25 -07001802 void checkOutputStageEffects() final;
1803 void setHalLatencyMode_l() final;
Eric Laurentb3f315a2021-07-13 15:09:05 +02001804
1805private:
Eric Laurent68a40a82022-05-03 18:15:04 +02001806 // Do not request a specific mode by default
1807 audio_latency_mode_t mRequestedLatencyMode = AUDIO_LATENCY_MODE_FREE;
1808
Andy Hung116bc262023-06-20 18:56:17 -07001809 sp<IAfEffectHandle> mFinalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02001810};
1811
Eric Laurent81784c32012-11-19 14:55:58 -08001812// record thread
Andy Hung0c1e11e2023-07-06 20:56:16 -07001813class RecordThread : public IAfRecordThread, public ThreadBase
Eric Laurent81784c32012-11-19 14:55:58 -08001814{
Andy Hung11e74242023-06-26 19:20:57 -07001815 friend class ResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08001816public:
Andy Hung0c1e11e2023-07-06 20:56:16 -07001817 sp<IAfRecordThread> asIAfRecordThread() final {
1818 return sp<IAfRecordThread>::fromExisting(this);
1819 }
Eric Laurent81784c32012-11-19 14:55:58 -08001820
Andy Hung7535ed92023-07-17 17:05:00 -07001821 RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08001822 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08001823 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001824 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08001825 );
Andy Hung3e4c8742023-06-29 21:19:25 -07001826 ~RecordThread() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001827
1828 // no addTrack_l ?
Andy Hung0c1e11e2023-07-06 20:56:16 -07001829 void destroyTrack_l(const sp<IAfRecordTrack>& track) final;
1830 void removeTrack_l(const sp<IAfRecordTrack>& track) final;
Eric Laurent81784c32012-11-19 14:55:58 -08001831
Eric Laurent81784c32012-11-19 14:55:58 -08001832 // Thread virtuals
Andy Hung3e4c8742023-06-29 21:19:25 -07001833 bool threadLoop() final;
1834 void preExit() final;
Eric Laurent81784c32012-11-19 14:55:58 -08001835
1836 // RefBase
Andy Hung3e4c8742023-06-29 21:19:25 -07001837 void onFirstRef() final;
Eric Laurent81784c32012-11-19 14:55:58 -08001838
Andy Hung3e4c8742023-06-29 21:19:25 -07001839 status_t initCheck() const final { return mInput == nullptr ? NO_INIT : NO_ERROR; }
Glenn Kastene198c362013-08-13 09:13:36 -07001840
Andy Hung3e4c8742023-06-29 21:19:25 -07001841 sp<MemoryDealer> readOnlyHeap() const final { return mReadOnlyHeap; }
Glenn Kastenb880f5e2014-05-07 08:43:45 -07001842
Andy Hung3e4c8742023-06-29 21:19:25 -07001843 sp<IMemory> pipeMemory() const final { return mPipeMemory; }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001844
Andy Hung0c1e11e2023-07-06 20:56:16 -07001845 sp<IAfRecordTrack> createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001846 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001847 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001848 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001849 audio_format_t format,
1850 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001851 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08001852 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001853 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07001854 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00001855 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07001856 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001857 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001858 status_t *status /*non-NULL*/,
Eric Laurentec376dc2021-04-08 20:41:22 +02001859 audio_port_handle_t portId,
Andy Hung0c1e11e2023-07-06 20:56:16 -07001860 int32_t maxSharedAudioHistoryMs) final;
Eric Laurent81784c32012-11-19 14:55:58 -08001861
Andy Hung11e74242023-06-26 19:20:57 -07001862 status_t start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08001863 AudioSystem::sync_event_t event,
Andy Hung0c1e11e2023-07-06 20:56:16 -07001864 audio_session_t triggerSession) final;
Eric Laurent81784c32012-11-19 14:55:58 -08001865
1866 // ask the thread to stop the specified track, and
1867 // return true if the caller should then do it's part of the stopping process
Andy Hung0c1e11e2023-07-06 20:56:16 -07001868 bool stop(IAfRecordTrack* recordTrack) final;
1869 AudioStreamIn* getInput() const final { return mInput; }
1870 AudioStreamIn* clearInput() final;
Eric Laurent81784c32012-11-19 14:55:58 -08001871
Andy Hungeb6b5f82023-07-14 11:00:08 -07001872 // TODO(b/291317898) Unify with IAfThreadBase
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001873 virtual sp<StreamHalInterface> stream() const;
Eric Laurent81784c32012-11-19 14:55:58 -08001874
Eric Laurent81784c32012-11-19 14:55:58 -08001875
Eric Laurent10351942014-05-08 18:49:52 -07001876 virtual bool checkForNewParameter_l(const String8& keyValuePair,
1877 status_t& status);
1878 virtual void cacheParameters_l() {}
Eric Laurent81784c32012-11-19 14:55:58 -08001879 virtual String8 getParameters(const String8& keys);
Andy Hung0c1e11e2023-07-06 20:56:16 -07001880 void ioConfigChanged(audio_io_config_event_t event, pid_t pid = 0,
1881 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final;
Eric Laurent1c333e22014-05-20 10:48:17 -07001882 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
1883 audio_patch_handle_t *handle);
1884 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle);
jiabinc52b1ff2019-10-31 17:20:42 -07001885 void updateOutDevices(const DeviceDescriptorBaseVector& outDevices) override;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02001886 void resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs) override;
Eric Laurent83b88082014-06-20 18:31:16 -07001887
Andy Hung0c1e11e2023-07-06 20:56:16 -07001888 void addPatchTrack(const sp<IAfPatchRecord>& record) final;
1889 void deletePatchTrack(const sp<IAfPatchRecord>& record) final;
Eric Laurent83b88082014-06-20 18:31:16 -07001890
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001891 void readInputParameters_l();
Andy Hung0c1e11e2023-07-06 20:56:16 -07001892 uint32_t getInputFramesLost() const final;
Eric Laurent81784c32012-11-19 14:55:58 -08001893
Andy Hung116bc262023-06-20 18:56:17 -07001894 virtual status_t addEffectChain_l(const sp<IAfEffectChain>& chain);
1895 virtual size_t removeEffectChain_l(const sp<IAfEffectChain>& chain);
Andy Hungc3d62f92019-03-14 13:38:51 -07001896 uint32_t hasAudioSession_l(audio_session_t sessionId) const override {
1897 return ThreadBase::hasAudioSession_l(sessionId, mTracks);
1898 }
Eric Laurent81784c32012-11-19 14:55:58 -08001899
1900 // Return the set of unique session IDs across all tracks.
1901 // The keys are the session IDs, and the associated values are meaningless.
1902 // FIXME replace by Set [and implement Bag/Multiset for other uses].
Glenn Kastend848eb42016-03-08 13:42:11 -08001903 KeyedVector<audio_session_t, bool> sessionIds() const;
Eric Laurent81784c32012-11-19 14:55:58 -08001904
Andy Hung068e08e2023-05-15 19:02:55 -07001905 status_t setSyncEvent(const sp<audioflinger::SyncEvent>& event) override;
1906 bool isValidSyncEvent(const sp<audioflinger::SyncEvent>& event) const override;
Eric Laurent81784c32012-11-19 14:55:58 -08001907
Andy Hung068e08e2023-05-15 19:02:55 -07001908 static void syncStartEventCallback(const wp<audioflinger::SyncEvent>& event);
Eric Laurent81784c32012-11-19 14:55:58 -08001909
Glenn Kasten9b58f632013-07-16 11:37:48 -07001910 virtual size_t frameCount() const { return mFrameCount; }
Andy Hung0c1e11e2023-07-06 20:56:16 -07001911 bool hasFastCapture() const final { return mFastCapture != 0; }
Mikhail Naganovdc769682018-05-04 15:34:08 -07001912 virtual void toAudioPortConfig(struct audio_port_config *config);
Glenn Kasten9b58f632013-07-16 11:37:48 -07001913
Eric Laurent4c415062016-06-17 16:14:16 -07001914 virtual status_t checkEffectCompatibility_l(const effect_descriptor_t *desc,
1915 audio_session_t sessionId);
1916
Andy Hungdae27702016-10-31 14:01:16 -07001917 virtual void acquireWakeLock_l() {
1918 ThreadBase::acquireWakeLock_l();
1919 mActiveTracks.updatePowerState(this, true /* force */);
1920 }
1921
Andy Hung0c1e11e2023-07-06 20:56:16 -07001922 void checkBtNrec() final;
Eric Laurentd8365c52017-07-16 15:27:05 -07001923
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001924 // Sets the UID records silence
Andy Hung0c1e11e2023-07-06 20:56:16 -07001925 void setRecordSilenced(audio_port_handle_t portId, bool silenced) final;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001926
Andy Hung0c1e11e2023-07-06 20:56:16 -07001927 status_t getActiveMicrophones(
1928 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const final;
1929 status_t setPreferredMicrophoneDirection(audio_microphone_direction_t direction) final;
1930 status_t setPreferredMicrophoneFieldDimension(float zoom) final;
Paul McLean03a6e6a2018-12-04 10:54:13 -07001931
Vlad Popa7e81cea2023-01-19 16:34:16 +01001932 MetadataUpdate updateMetadata_l() override;
Kevin Rocard069c2712018-03-29 19:09:14 -07001933
Andy Hung0c1e11e2023-07-06 20:56:16 -07001934 bool fastTrackAvailable() const final { return mFastTrackAvail; }
1935 void setFastTrackAvailable(bool available) final { mFastTrackAvail = available; }
jiabin01c8f562018-07-19 17:47:28 -07001936
Andy Hungc8fddf32018-08-08 18:32:37 -07001937 bool isTimestampCorrectionEnabled() const override {
1938 // checks popcount for exactly one device.
Atneya Nair497fff12022-01-18 16:23:04 -05001939 // Is currently disabled. Before enabling,
1940 // verify compressed record timestamps.
jiabinc52b1ff2019-10-31 17:20:42 -07001941 return audio_is_input_device(mTimestampCorrectedDevice)
1942 && inDeviceType() == mTimestampCorrectedDevice;
Andy Hungc8fddf32018-08-08 18:32:37 -07001943 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001944
Andy Hung0c1e11e2023-07-06 20:56:16 -07001945 status_t shareAudioHistory(const std::string& sharedAudioPackageName,
Eric Laurentec376dc2021-04-08 20:41:22 +02001946 audio_session_t sharedSessionId = AUDIO_SESSION_NONE,
Andy Hung0c1e11e2023-07-06 20:56:16 -07001947 int64_t sharedAudioStartMs = -1) final;
Eric Laurentec376dc2021-04-08 20:41:22 +02001948 status_t shareAudioHistory_l(const std::string& sharedAudioPackageName,
1949 audio_session_t sharedSessionId = AUDIO_SESSION_NONE,
1950 int64_t sharedAudioStartMs = -1);
Andy Hung0c1e11e2023-07-06 20:56:16 -07001951 void resetAudioHistory_l() final;
Eric Laurentec376dc2021-04-08 20:41:22 +02001952
Andy Hung3e4c8742023-06-29 21:19:25 -07001953 bool isStreamInitialized() const final {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001954 return !(mInput == nullptr || mInput->stream == nullptr);
1955 }
1956
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001957protected:
1958 void dumpInternals_l(int fd, const Vector<String16>& args) override;
1959 void dumpTracks_l(int fd, const Vector<String16>& args) override;
1960
Eric Laurent81784c32012-11-19 14:55:58 -08001961private:
Eric Laurent81784c32012-11-19 14:55:58 -08001962 // Enter standby if not already in standby, and set mStandby flag
Glenn Kasten93e471f2013-08-19 08:40:07 -07001963 void standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08001964
1965 // Call the HAL standby method unconditionally, and don't change mStandby flag
Glenn Kastene198c362013-08-13 09:13:36 -07001966 void inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08001967
Eric Laurentd8365c52017-07-16 15:27:05 -07001968 void checkBtNrec_l();
1969
Eric Laurentec376dc2021-04-08 20:41:22 +02001970 int32_t getOldestFront_l();
1971 void updateFronts_l(int32_t offset);
1972
Eric Laurent81784c32012-11-19 14:55:58 -08001973 AudioStreamIn *mInput;
Mikhail Naganov2534b382019-09-25 13:05:02 -07001974 Source *mSource;
Andy Hung11e74242023-06-26 19:20:57 -07001975 SortedVector <sp<IAfRecordTrack>> mTracks;
Glenn Kasten2b806402013-11-20 16:37:38 -08001976 // mActiveTracks has dual roles: it indicates the current active track(s), and
Eric Laurent81784c32012-11-19 14:55:58 -08001977 // is used together with mStartStopCond to indicate start()/stop() progress
Andy Hung11e74242023-06-26 19:20:57 -07001978 ActiveTracks<IAfRecordTrack> mActiveTracks;
Andy Hungdae27702016-10-31 14:01:16 -07001979
Eric Laurent81784c32012-11-19 14:55:58 -08001980 Condition mStartStopCond;
Glenn Kasten9b58f632013-07-16 11:37:48 -07001981
Glenn Kasten85948432013-08-19 12:09:05 -07001982 // resampler converts input at HAL Hz to output at AudioRecord client Hz
Glenn Kasten1b291842016-07-18 14:55:21 -07001983 void *mRsmpInBuffer; // size = mRsmpInFramesOA
Glenn Kasten85948432013-08-19 12:09:05 -07001984 size_t mRsmpInFrames; // size of resampler input in frames
1985 size_t mRsmpInFramesP2;// size rounded up to a power-of-2
Glenn Kasten1b291842016-07-18 14:55:21 -07001986 size_t mRsmpInFramesOA;// mRsmpInFramesP2 + over-allocation
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001987
1988 // rolling index that is never cleared
Glenn Kasten85948432013-08-19 12:09:05 -07001989 int32_t mRsmpInRear; // last filled frame + 1
Glenn Kasten85948432013-08-19 12:09:05 -07001990
Eric Laurent81784c32012-11-19 14:55:58 -08001991 // For dumpsys
Glenn Kastenb880f5e2014-05-07 08:43:45 -07001992 const sp<MemoryDealer> mReadOnlyHeap;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001993
1994 // one-time initialization, no locks required
Glenn Kastenb187de12014-12-30 08:18:15 -08001995 sp<FastCapture> mFastCapture; // non-0 if there is also
1996 // a fast capture
Eric Laurent72e3f392015-05-20 14:43:50 -07001997
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001998 // FIXME audio watchdog thread
1999
2000 // contents are not guaranteed to be consistent, no locks required
2001 FastCaptureDumpState mFastCaptureDumpState;
2002#ifdef STATE_QUEUE_DUMP
2003 // FIXME StateQueue observer and mutator dump fields
2004#endif
2005 // FIXME audio watchdog dump
2006
2007 // accessible only within the threadLoop(), no locks required
2008 // mFastCapture->sq() // for mutating and pushing state
2009 int32_t mFastCaptureFutex; // for cold idle
2010
2011 // The HAL input source is treated as non-blocking,
2012 // but current implementation is blocking
2013 sp<NBAIO_Source> mInputSource;
2014 // The source for the normal capture thread to read from: mInputSource or mPipeSource
2015 sp<NBAIO_Source> mNormalSource;
2016 // If a fast capture is present, the non-blocking pipe sink written to by fast capture,
2017 // otherwise clear
2018 sp<NBAIO_Sink> mPipeSink;
2019 // If a fast capture is present, the non-blocking pipe source read by normal thread,
2020 // otherwise clear
2021 sp<NBAIO_Source> mPipeSource;
2022 // Depth of pipe from fast capture to normal thread and fast clients, always power of 2
2023 size_t mPipeFramesP2;
2024 // If a fast capture is present, the Pipe as IMemory, otherwise clear
2025 sp<IMemory> mPipeMemory;
2026
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002027 // TODO: add comment and adjust size as needed
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07002028 static const size_t kFastCaptureLogSize = 4 * 1024;
2029 sp<NBLog::Writer> mFastCaptureNBLogWriter;
2030
2031 bool mFastTrackAvail; // true if fast track available
Eric Laurentd8365c52017-07-16 15:27:05 -07002032 // common state to all record threads
2033 std::atomic_bool mBtNrecSuspended;
Andy Hung6427e442018-08-09 12:51:02 -07002034
2035 int64_t mFramesRead = 0; // continuous running counter.
jiabinc52b1ff2019-10-31 17:20:42 -07002036
2037 DeviceDescriptorBaseVector mOutDevices;
Eric Laurentec376dc2021-04-08 20:41:22 +02002038
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02002039 int32_t mMaxSharedAudioHistoryMs = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02002040 std::string mSharedAudioPackageName = {};
Eric Laurent2407ce32021-04-26 14:56:03 +02002041 int32_t mSharedAudioStartFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02002042 audio_session_t mSharedAudioSessionId = AUDIO_SESSION_NONE;
Eric Laurent81784c32012-11-19 14:55:58 -08002043};
Eric Laurent6acd1d42017-01-04 14:23:29 -08002044
Andy Hung765de282023-07-07 15:58:48 -07002045class MmapThread : public ThreadBase, public virtual IAfMmapThread
Eric Laurent6acd1d42017-01-04 14:23:29 -08002046{
2047 public:
Andy Hung7535ed92023-07-17 17:05:00 -07002048 MmapThread(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -07002049 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady,
Andy Hungcf10d742020-04-28 15:38:24 -07002050 bool isOut);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002051
Andy Hung765de282023-07-07 15:58:48 -07002052 void configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08002053 audio_stream_type_t streamType,
2054 audio_session_t sessionId,
2055 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07002056 audio_port_handle_t deviceId,
Andy Hung765de282023-07-07 15:58:48 -07002057 audio_port_handle_t portId) override;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002058
Andy Hung765de282023-07-07 15:58:48 -07002059 void disconnect() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002060
Andy Hung3e4c8742023-06-29 21:19:25 -07002061 // MmapStreamInterface for adapter.
Andy Hung765de282023-07-07 15:58:48 -07002062 status_t createMmapBuffer(int32_t minSizeFrames, struct audio_mmap_buffer_info* info) final;
2063 status_t getMmapPosition(struct audio_mmap_position* position) const override;
2064 status_t start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07002065 const audio_attributes_t *attr,
Andy Hung765de282023-07-07 15:58:48 -07002066 audio_port_handle_t* handle) final;
2067 status_t stop(audio_port_handle_t handle) final;
2068 status_t standby() final;
2069 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) const = 0;
2070 status_t reportData(const void* buffer, size_t frameCount) override;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002071
2072 // RefBase
Andy Hung3e4c8742023-06-29 21:19:25 -07002073 void onFirstRef() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002074
2075 // Thread virtuals
Andy Hung3e4c8742023-06-29 21:19:25 -07002076 bool threadLoop() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002077
Andy Hung3e4c8742023-06-29 21:19:25 -07002078 // Not in ThreadBase
2079 virtual void threadLoop_exit() final;
2080 virtual void threadLoop_standby() final;
2081 virtual bool shouldStandby_l() final { return false; }
2082 virtual status_t exitStandby_l() REQUIRES(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002083
Andy Hung3e4c8742023-06-29 21:19:25 -07002084 status_t initCheck() const final { return mHalStream == nullptr ? NO_INIT : NO_ERROR; }
2085 size_t frameCount() const final { return mFrameCount; }
2086 bool checkForNewParameter_l(const String8& keyValuePair, status_t& status) final;
2087 String8 getParameters(const String8& keys) final;
2088 void ioConfigChanged(audio_io_config_event_t event, pid_t pid = 0,
2089 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002090 void readHalParameters_l();
Andy Hung3e4c8742023-06-29 21:19:25 -07002091 void cacheParameters_l() final {}
2092 status_t createAudioPatch_l(
2093 const struct audio_patch* patch, audio_patch_handle_t* handle) final;
2094 status_t releaseAudioPatch_l(const audio_patch_handle_t handle) final;
2095 void toAudioPortConfig(struct audio_port_config* config) override;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002096
Andy Hung3e4c8742023-06-29 21:19:25 -07002097 sp<StreamHalInterface> stream() const final { return mHalStream; }
2098 status_t addEffectChain_l(const sp<IAfEffectChain>& chain) final;
2099 size_t removeEffectChain_l(const sp<IAfEffectChain>& chain) final;
2100 status_t checkEffectCompatibility_l(
2101 const effect_descriptor_t *desc, audio_session_t sessionId) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002102
Andy Hung3e4c8742023-06-29 21:19:25 -07002103 uint32_t hasAudioSession_l(audio_session_t sessionId) const override {
Andy Hungc3d62f92019-03-14 13:38:51 -07002104 // Note: using mActiveTracks as no mTracks here.
2105 return ThreadBase::hasAudioSession_l(sessionId, mActiveTracks);
2106 }
Andy Hung3e4c8742023-06-29 21:19:25 -07002107 status_t setSyncEvent(const sp<audioflinger::SyncEvent>& event) final;
2108 bool isValidSyncEvent(const sp<audioflinger::SyncEvent>& event) const final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002109
Andy Hung3e4c8742023-06-29 21:19:25 -07002110 virtual void checkSilentMode_l() {} // cannot be const (RecordThread)
2111 virtual void processVolume_l() {}
Eric Laurent6acd1d42017-01-04 14:23:29 -08002112 void checkInvalidTracks_l();
2113
Andy Hung3e4c8742023-06-29 21:19:25 -07002114 // Not in ThreadBase
2115 virtual audio_stream_type_t streamType() const { return AUDIO_STREAM_DEFAULT; }
2116 virtual void invalidateTracks(audio_stream_type_t /* streamType */) {}
Andy Hung765de282023-07-07 15:58:48 -07002117 void invalidateTracks(std::set<audio_port_handle_t>& /* portIds */) override {}
Eric Laurent6acd1d42017-01-04 14:23:29 -08002118
Eric Laurent331679c2018-04-16 17:03:16 -07002119 // Sets the UID records silence
Andy Hung765de282023-07-07 15:58:48 -07002120 void setRecordSilenced(
2121 audio_port_handle_t /* portId */, bool /* silenced */) override {}
Eric Laurent331679c2018-04-16 17:03:16 -07002122
Andy Hung3e4c8742023-06-29 21:19:25 -07002123 bool isStreamInitialized() const override { return false; }
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002124
jiabin09609032022-06-15 19:26:01 +00002125 void setClientSilencedState_l(audio_port_handle_t portId, bool silenced) {
2126 mClientSilencedStates[portId] = silenced;
2127 }
2128
2129 size_t eraseClientSilencedState_l(audio_port_handle_t portId) {
2130 return mClientSilencedStates.erase(portId);
2131 }
2132
2133 bool isClientSilenced_l(audio_port_handle_t portId) const {
2134 const auto it = mClientSilencedStates.find(portId);
2135 return it != mClientSilencedStates.end() ? it->second : false;
2136 }
2137
2138 void setClientSilencedIfExists_l(audio_port_handle_t portId, bool silenced) {
2139 const auto it = mClientSilencedStates.find(portId);
2140 if (it != mClientSilencedStates.end()) {
2141 it->second = silenced;
2142 }
2143 }
2144
Eric Laurent6acd1d42017-01-04 14:23:29 -08002145 protected:
Andy Hung3e4c8742023-06-29 21:19:25 -07002146 void dumpInternals_l(int fd, const Vector<String16>& args) override;
2147 void dumpTracks_l(int fd, const Vector<String16>& args) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002148
jiabinc52b1ff2019-10-31 17:20:42 -07002149 /**
2150 * @brief mDeviceId current device port unique identifier
2151 */
2152 audio_port_handle_t mDeviceId = AUDIO_PORT_HANDLE_NONE;
2153
Eric Laurent6acd1d42017-01-04 14:23:29 -08002154 audio_attributes_t mAttr;
2155 audio_session_t mSessionId;
2156 audio_port_handle_t mPortId;
2157
Phil Burk7f6b40d2017-02-09 13:18:38 -08002158 wp<MmapStreamCallback> mCallback;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002159 sp<StreamHalInterface> mHalStream;
2160 sp<DeviceHalInterface> mHalDevice;
2161 AudioHwDevice* const mAudioHwDev;
Andy Hung11e74242023-06-26 19:20:57 -07002162 ActiveTracks<IAfMmapTrack> mActiveTracks;
Eric Laurent67f97292018-04-20 18:05:41 -07002163 float mHalVolFloat;
jiabin09609032022-06-15 19:26:01 +00002164 std::map<audio_port_handle_t, bool> mClientSilencedStates;
Eric Laurent331679c2018-04-16 17:03:16 -07002165
2166 int32_t mNoCallbackWarningCount;
2167 static constexpr int32_t kMaxNoCallbackWarnings = 5;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002168};
2169
Andy Hung765de282023-07-07 15:58:48 -07002170class MmapPlaybackThread : public MmapThread, public IAfMmapPlaybackThread,
2171 public virtual VolumeInterface {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002172public:
Andy Hung7535ed92023-07-17 17:05:00 -07002173 MmapPlaybackThread(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07002174 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002175
Andy Hung765de282023-07-07 15:58:48 -07002176 sp<IAfMmapPlaybackThread> asIAfMmapPlaybackThread() final {
2177 return sp<IAfMmapPlaybackThread>::fromExisting(this);
2178 }
2179
Andy Hung3e4c8742023-06-29 21:19:25 -07002180 void configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08002181 audio_stream_type_t streamType,
2182 audio_session_t sessionId,
2183 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07002184 audio_port_handle_t deviceId,
Andy Hung3e4c8742023-06-29 21:19:25 -07002185 audio_port_handle_t portId) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002186
Andy Hung765de282023-07-07 15:58:48 -07002187 AudioStreamOut* clearOutput() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002188
2189 // VolumeInterface
Andy Hung3e4c8742023-06-29 21:19:25 -07002190 void setMasterVolume(float value) final;
2191 void setMasterBalance(float /* value */) final {} // Needs implementation?
2192 void setMasterMute(bool muted) final;
2193 void setStreamVolume(audio_stream_type_t stream, float value) final;
2194 void setStreamMute(audio_stream_type_t stream, bool muted) final;
2195 float streamVolume(audio_stream_type_t stream) const final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002196
2197 void setMasterMute_l(bool muted) { mMasterMute = muted; }
2198
Andy Hung3e4c8742023-06-29 21:19:25 -07002199 void invalidateTracks(audio_stream_type_t streamType) final;
2200 void invalidateTracks(std::set<audio_port_handle_t>& portIds) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002201
Andy Hung3e4c8742023-06-29 21:19:25 -07002202 audio_stream_type_t streamType() const final { return mStreamType; }
2203 void checkSilentMode_l() final;
2204 void processVolume_l() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002205
Andy Hung3e4c8742023-06-29 21:19:25 -07002206 MetadataUpdate updateMetadata_l() final;
Kevin Rocard069c2712018-03-29 19:09:14 -07002207
Andy Hung3e4c8742023-06-29 21:19:25 -07002208 void toAudioPortConfig(struct audio_port_config* config) final;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07002209
Andy Hung3e4c8742023-06-29 21:19:25 -07002210 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) const final;
jiabinb7d8c5a2020-08-26 17:24:52 -07002211
Andy Hung3e4c8742023-06-29 21:19:25 -07002212 bool isStreamInitialized() const final {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002213 return !(mOutput == nullptr || mOutput->stream == nullptr);
2214 }
2215
Andy Hung3e4c8742023-06-29 21:19:25 -07002216 status_t reportData(const void* buffer, size_t frameCount) final;
jiabinfc791ee2023-02-15 19:43:40 +00002217
Andy Hung3e4c8742023-06-29 21:19:25 -07002218 void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) final;
2219 void stopMelComputation_l() final;
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002220
Eric Laurent6acd1d42017-01-04 14:23:29 -08002221protected:
Andy Hung3e4c8742023-06-29 21:19:25 -07002222 void dumpInternals_l(int fd, const Vector<String16>& args) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002223
2224 audio_stream_type_t mStreamType;
2225 float mMasterVolume;
2226 float mStreamVolume;
2227 bool mMasterMute;
2228 bool mStreamMute;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002229 AudioStreamOut* mOutput;
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002230
2231 mediautils::atomic_sp<audio_utils::MelProcessor> mMelProcessor;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002232};
2233
Andy Hung765de282023-07-07 15:58:48 -07002234class MmapCaptureThread : public MmapThread, public IAfMmapCaptureThread
Eric Laurent6acd1d42017-01-04 14:23:29 -08002235{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002236public:
Andy Hung7535ed92023-07-17 17:05:00 -07002237 MmapCaptureThread(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07002238 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002239
Andy Hung765de282023-07-07 15:58:48 -07002240 sp<IAfMmapCaptureThread> asIAfMmapCaptureThread() final {
2241 return sp<IAfMmapCaptureThread>::fromExisting(this);
2242 }
2243
2244 AudioStreamIn* clearInput() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002245
Andy Hung3e4c8742023-06-29 21:19:25 -07002246 status_t exitStandby_l() REQUIRES(mLock) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002247
Andy Hung3e4c8742023-06-29 21:19:25 -07002248 MetadataUpdate updateMetadata_l() final;
2249 void processVolume_l() final;
2250 void setRecordSilenced(audio_port_handle_t portId, bool silenced) final;
Kevin Rocard069c2712018-03-29 19:09:14 -07002251
Andy Hung3e4c8742023-06-29 21:19:25 -07002252 void toAudioPortConfig(struct audio_port_config* config) final;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07002253
Andy Hung3e4c8742023-06-29 21:19:25 -07002254 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) const final;
jiabinb7d8c5a2020-08-26 17:24:52 -07002255
Andy Hung3e4c8742023-06-29 21:19:25 -07002256 bool isStreamInitialized() const final {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002257 return !(mInput == nullptr || mInput->stream == nullptr);
2258 }
2259
Eric Laurent6acd1d42017-01-04 14:23:29 -08002260protected:
2261
2262 AudioStreamIn* mInput;
2263};
jiabinc658e452022-10-21 20:52:21 +00002264
2265class BitPerfectThread : public MixerThread {
2266public:
Andy Hung7535ed92023-07-17 17:05:00 -07002267 BitPerfectThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut *output,
jiabinc658e452022-10-21 20:52:21 +00002268 audio_io_handle_t id, bool systemReady);
2269
2270protected:
Andy Hung3e4c8742023-06-29 21:19:25 -07002271 mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove) final;
2272 void threadLoop_mix() final;
jiabinc658e452022-10-21 20:52:21 +00002273
2274private:
2275 bool mIsBitPerfect;
jiabin76d94692022-12-15 21:51:21 +00002276 float mVolumeLeft = 0.f;
2277 float mVolumeRight = 0.f;
jiabinc658e452022-10-21 20:52:21 +00002278};
Andy Hunga6426302023-06-23 19:27:19 -07002279
Andy Hung4b17e882023-07-07 13:47:37 -07002280} // namespace android