blob: a62886784c65dedd796d0c3fcc746d6cb2797219 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
Andy Hungee58e4a2023-07-07 13:47:37 -070018#pragma once
Eric Laurent81784c32012-11-19 14:55:58 -080019
Andy Hungee58e4a2023-07-07 13:47:37 -070020namespace android {
Andy Hung440901d2023-06-29 21:19:25 -070021
22class AsyncCallbackThread;
23
24class ThreadBase : public virtual IAfThreadBase, public Thread {
Eric Laurent81784c32012-11-19 14:55:58 -080025public:
Glenn Kasten97b7b752014-09-28 13:04:24 -070026 static const char *threadTypeToString(type_t type);
27
Andy Hung583043b2023-07-17 17:05:00 -070028 IAfThreadCallback* afThreadCallback() const final { return mAfThreadCallback.get(); }
Andy Hung87c693c2023-07-06 20:56:16 -070029
Andy Hung583043b2023-07-17 17:05:00 -070030 ThreadBase(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -070031 type_t type, bool systemReady, bool isOut);
Andy Hung440901d2023-06-29 21:19:25 -070032 ~ThreadBase() override;
Eric Laurent81784c32012-11-19 14:55:58 -080033
Andy Hung440901d2023-06-29 21:19:25 -070034 status_t readyToRun() final;
35 void clearPowerManager() final;
Eric Laurent81784c32012-11-19 14:55:58 -080036
37 // base for record and playback
38 enum {
39 CFG_EVENT_IO,
Eric Laurent10351942014-05-08 18:49:52 -070040 CFG_EVENT_PRIO,
41 CFG_EVENT_SET_PARAMETER,
Eric Laurent1c333e22014-05-20 10:48:17 -070042 CFG_EVENT_CREATE_AUDIO_PATCH,
43 CFG_EVENT_RELEASE_AUDIO_PATCH,
jiabinc52b1ff2019-10-31 17:20:42 -070044 CFG_EVENT_UPDATE_OUT_DEVICE,
Eric Laurentb3f315a2021-07-13 15:09:05 +020045 CFG_EVENT_RESIZE_BUFFER,
Eric Laurent68a40a82022-05-03 18:15:04 +020046 CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS,
47 CFG_EVENT_HAL_LATENCY_MODES_CHANGED,
Eric Laurent81784c32012-11-19 14:55:58 -080048 };
49
Eric Laurent10351942014-05-08 18:49:52 -070050 class ConfigEventData: public RefBase {
Eric Laurent81784c32012-11-19 14:55:58 -080051 public:
Eric Laurent10351942014-05-08 18:49:52 -070052 virtual ~ConfigEventData() {}
Eric Laurent81784c32012-11-19 14:55:58 -080053
54 virtual void dump(char *buffer, size_t size) = 0;
Eric Laurent10351942014-05-08 18:49:52 -070055 protected:
56 ConfigEventData() {}
Eric Laurent81784c32012-11-19 14:55:58 -080057 };
58
Eric Laurent10351942014-05-08 18:49:52 -070059 // Config event sequence by client if status needed (e.g binder thread calling setParameters()):
60 // 1. create SetParameterConfigEvent. This sets mWaitStatus in config event
61 // 2. Lock mLock
62 // 3. Call sendConfigEvent_l(): Append to mConfigEvents and mWaitWorkCV.signal
63 // 4. sendConfigEvent_l() reads status from event->mStatus;
64 // 5. sendConfigEvent_l() returns status
65 // 6. Unlock
66 //
67 // Parameter sequence by server: threadLoop calling processConfigEvents_l():
68 // 1. Lock mLock
69 // 2. If there is an entry in mConfigEvents proceed ...
70 // 3. Read first entry in mConfigEvents
71 // 4. Remove first entry from mConfigEvents
72 // 5. Process
73 // 6. Set event->mStatus
74 // 7. event->mCond.signal
75 // 8. Unlock
Eric Laurent81784c32012-11-19 14:55:58 -080076
Eric Laurent10351942014-05-08 18:49:52 -070077 class ConfigEvent: public RefBase {
78 public:
Eric Laurentb3f315a2021-07-13 15:09:05 +020079 void dump(char *buffer, size_t size) {
80 snprintf(buffer, size, "Event type: %d\n", mType);
81 if (mData != nullptr) {
82 snprintf(buffer, size, "Data:\n");
83 mData->dump(buffer, size);
84 }
85 }
Eric Laurent10351942014-05-08 18:49:52 -070086
87 const int mType; // event type e.g. CFG_EVENT_IO
88 Mutex mLock; // mutex associated with mCond
89 Condition mCond; // condition for status return
90 status_t mStatus; // status communicated to sender
91 bool mWaitStatus; // true if sender is waiting for status
Eric Laurent72e3f392015-05-20 14:43:50 -070092 bool mRequiresSystemReady; // true if must wait for system ready to enter event queue
Eric Laurent10351942014-05-08 18:49:52 -070093 sp<ConfigEventData> mData; // event specific parameter data
94
95 protected:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -070096 explicit ConfigEvent(int type, bool requiresSystemReady = false) :
Eric Laurent72e3f392015-05-20 14:43:50 -070097 mType(type), mStatus(NO_ERROR), mWaitStatus(false),
98 mRequiresSystemReady(requiresSystemReady), mData(NULL) {}
Eric Laurent10351942014-05-08 18:49:52 -070099 };
100
101 class IoConfigEventData : public ConfigEventData {
102 public:
Mikhail Naganov88536df2021-07-26 17:30:29 -0700103 IoConfigEventData(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700104 audio_port_handle_t portId) :
105 mEvent(event), mPid(pid), mPortId(portId) {}
Eric Laurent81784c32012-11-19 14:55:58 -0800106
107 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200108 snprintf(buffer, size, "- IO event: event %d\n", mEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800109 }
110
Mikhail Naganov88536df2021-07-26 17:30:29 -0700111 const audio_io_config_event_t mEvent;
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700112 const pid_t mPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -0700113 const audio_port_handle_t mPortId;
Eric Laurent81784c32012-11-19 14:55:58 -0800114 };
115
Eric Laurent10351942014-05-08 18:49:52 -0700116 class IoConfigEvent : public ConfigEvent {
Eric Laurent81784c32012-11-19 14:55:58 -0800117 public:
Mikhail Naganov88536df2021-07-26 17:30:29 -0700118 IoConfigEvent(audio_io_config_event_t event, pid_t pid, audio_port_handle_t portId) :
Eric Laurent10351942014-05-08 18:49:52 -0700119 ConfigEvent(CFG_EVENT_IO) {
Eric Laurent09f1ed22019-04-24 17:45:17 -0700120 mData = new IoConfigEventData(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700121 }
Eric Laurent10351942014-05-08 18:49:52 -0700122 };
Eric Laurent81784c32012-11-19 14:55:58 -0800123
Eric Laurent10351942014-05-08 18:49:52 -0700124 class PrioConfigEventData : public ConfigEventData {
125 public:
Mikhail Naganov83f04272017-02-07 10:45:09 -0800126 PrioConfigEventData(pid_t pid, pid_t tid, int32_t prio, bool forApp) :
127 mPid(pid), mTid(tid), mPrio(prio), mForApp(forApp) {}
Eric Laurent81784c32012-11-19 14:55:58 -0800128
129 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200130 snprintf(buffer, size, "- Prio event: pid %d, tid %d, prio %d, for app? %d\n",
Mikhail Naganov83f04272017-02-07 10:45:09 -0800131 mPid, mTid, mPrio, mForApp);
Eric Laurent81784c32012-11-19 14:55:58 -0800132 }
133
Eric Laurent81784c32012-11-19 14:55:58 -0800134 const pid_t mPid;
135 const pid_t mTid;
136 const int32_t mPrio;
Mikhail Naganov83f04272017-02-07 10:45:09 -0800137 const bool mForApp;
Eric Laurent81784c32012-11-19 14:55:58 -0800138 };
139
Eric Laurent10351942014-05-08 18:49:52 -0700140 class PrioConfigEvent : public ConfigEvent {
141 public:
Mikhail Naganov83f04272017-02-07 10:45:09 -0800142 PrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp) :
Eric Laurent72e3f392015-05-20 14:43:50 -0700143 ConfigEvent(CFG_EVENT_PRIO, true) {
Mikhail Naganov83f04272017-02-07 10:45:09 -0800144 mData = new PrioConfigEventData(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700145 }
Eric Laurent10351942014-05-08 18:49:52 -0700146 };
147
148 class SetParameterConfigEventData : public ConfigEventData {
149 public:
Andy Hung920f6572022-10-06 12:09:49 -0700150 explicit SetParameterConfigEventData(const String8& keyValuePairs) :
Eric Laurent10351942014-05-08 18:49:52 -0700151 mKeyValuePairs(keyValuePairs) {}
152
153 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200154 snprintf(buffer, size, "- KeyValue: %s\n", mKeyValuePairs.string());
Eric Laurent10351942014-05-08 18:49:52 -0700155 }
156
157 const String8 mKeyValuePairs;
158 };
159
160 class SetParameterConfigEvent : public ConfigEvent {
161 public:
Andy Hung920f6572022-10-06 12:09:49 -0700162 explicit SetParameterConfigEvent(const String8& keyValuePairs) :
Eric Laurent10351942014-05-08 18:49:52 -0700163 ConfigEvent(CFG_EVENT_SET_PARAMETER) {
164 mData = new SetParameterConfigEventData(keyValuePairs);
165 mWaitStatus = true;
166 }
Eric Laurent10351942014-05-08 18:49:52 -0700167 };
168
Eric Laurent1c333e22014-05-20 10:48:17 -0700169 class CreateAudioPatchConfigEventData : public ConfigEventData {
170 public:
171 CreateAudioPatchConfigEventData(const struct audio_patch patch,
172 audio_patch_handle_t handle) :
173 mPatch(patch), mHandle(handle) {}
174
175 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200176 snprintf(buffer, size, "- Patch handle: %u\n", mHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -0700177 }
178
179 const struct audio_patch mPatch;
180 audio_patch_handle_t mHandle;
181 };
182
183 class CreateAudioPatchConfigEvent : public ConfigEvent {
184 public:
185 CreateAudioPatchConfigEvent(const struct audio_patch patch,
186 audio_patch_handle_t handle) :
187 ConfigEvent(CFG_EVENT_CREATE_AUDIO_PATCH) {
188 mData = new CreateAudioPatchConfigEventData(patch, handle);
189 mWaitStatus = true;
190 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700191 };
192
193 class ReleaseAudioPatchConfigEventData : public ConfigEventData {
194 public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700195 explicit ReleaseAudioPatchConfigEventData(const audio_patch_handle_t handle) :
Eric Laurent1c333e22014-05-20 10:48:17 -0700196 mHandle(handle) {}
197
198 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200199 snprintf(buffer, size, "- Patch handle: %u\n", mHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -0700200 }
201
202 audio_patch_handle_t mHandle;
203 };
204
205 class ReleaseAudioPatchConfigEvent : public ConfigEvent {
206 public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700207 explicit ReleaseAudioPatchConfigEvent(const audio_patch_handle_t handle) :
Eric Laurent1c333e22014-05-20 10:48:17 -0700208 ConfigEvent(CFG_EVENT_RELEASE_AUDIO_PATCH) {
209 mData = new ReleaseAudioPatchConfigEventData(handle);
210 mWaitStatus = true;
211 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700212 };
Eric Laurent81784c32012-11-19 14:55:58 -0800213
jiabinc52b1ff2019-10-31 17:20:42 -0700214 class UpdateOutDevicesConfigEventData : public ConfigEventData {
215 public:
216 explicit UpdateOutDevicesConfigEventData(const DeviceDescriptorBaseVector& outDevices) :
217 mOutDevices(outDevices) {}
218
219 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200220 snprintf(buffer, size, "- Devices: %s", android::toString(mOutDevices).c_str());
jiabinc52b1ff2019-10-31 17:20:42 -0700221 }
222
223 DeviceDescriptorBaseVector mOutDevices;
224 };
225
226 class UpdateOutDevicesConfigEvent : public ConfigEvent {
227 public:
228 explicit UpdateOutDevicesConfigEvent(const DeviceDescriptorBaseVector& outDevices) :
229 ConfigEvent(CFG_EVENT_UPDATE_OUT_DEVICE) {
230 mData = new UpdateOutDevicesConfigEventData(outDevices);
231 }
jiabinc52b1ff2019-10-31 17:20:42 -0700232 };
233
Eric Laurentec376dc2021-04-08 20:41:22 +0200234 class ResizeBufferConfigEventData : public ConfigEventData {
235 public:
236 explicit ResizeBufferConfigEventData(int32_t maxSharedAudioHistoryMs) :
237 mMaxSharedAudioHistoryMs(maxSharedAudioHistoryMs) {}
238
239 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200240 snprintf(buffer, size, "- mMaxSharedAudioHistoryMs: %d", mMaxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +0200241 }
242
243 int32_t mMaxSharedAudioHistoryMs;
244 };
245
246 class ResizeBufferConfigEvent : public ConfigEvent {
247 public:
248 explicit ResizeBufferConfigEvent(int32_t maxSharedAudioHistoryMs) :
249 ConfigEvent(CFG_EVENT_RESIZE_BUFFER) {
250 mData = new ResizeBufferConfigEventData(maxSharedAudioHistoryMs);
251 }
Eric Laurentec376dc2021-04-08 20:41:22 +0200252 };
253
Eric Laurentb3f315a2021-07-13 15:09:05 +0200254 class CheckOutputStageEffectsEvent : public ConfigEvent {
255 public:
256 CheckOutputStageEffectsEvent() :
257 ConfigEvent(CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS) {
258 }
Eric Laurentb3f315a2021-07-13 15:09:05 +0200259 };
260
Eric Laurent68a40a82022-05-03 18:15:04 +0200261 class HalLatencyModesChangedEvent : public ConfigEvent {
262 public:
263 HalLatencyModesChangedEvent() :
264 ConfigEvent(CFG_EVENT_HAL_LATENCY_MODES_CHANGED) {
265 }
Eric Laurent68a40a82022-05-03 18:15:04 +0200266 };
267
Eric Laurentb3f315a2021-07-13 15:09:05 +0200268
Eric Laurent81784c32012-11-19 14:55:58 -0800269 class PMDeathRecipient : public IBinder::DeathRecipient {
270 public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700271 explicit PMDeathRecipient(const wp<ThreadBase>& thread) : mThread(thread) {}
Eric Laurent81784c32012-11-19 14:55:58 -0800272 virtual ~PMDeathRecipient() {}
273
274 // IBinder::DeathRecipient
275 virtual void binderDied(const wp<IBinder>& who);
276
277 private:
Mikhail Naganovbf493082017-04-17 17:37:12 -0700278 DISALLOW_COPY_AND_ASSIGN(PMDeathRecipient);
Eric Laurent81784c32012-11-19 14:55:58 -0800279
280 wp<ThreadBase> mThread;
281 };
282
Andy Hung440901d2023-06-29 21:19:25 -0700283 type_t type() const final { return mType; }
284 bool isDuplicating() const final { return (mType == DUPLICATING); }
285 audio_io_handle_t id() const final { return mId;}
Eric Laurent81784c32012-11-19 14:55:58 -0800286
Andy Hung440901d2023-06-29 21:19:25 -0700287 uint32_t sampleRate() const final { return mSampleRate; }
288 audio_channel_mask_t channelMask() const final { return mChannelMask; }
289 audio_channel_mask_t mixerChannelMask() const override { return mChannelMask; }
290 audio_format_t format() const final { return mHALFormat; }
291 uint32_t channelCount() const final { return mChannelCount; }
292 audio_channel_mask_t hapticChannelMask() const override { return AUDIO_CHANNEL_NONE; }
Andy Hung87c693c2023-07-06 20:56:16 -0700293 uint32_t hapticChannelCount() const override { return 0; }
Andy Hung440901d2023-06-29 21:19:25 -0700294 uint32_t latency_l() const override { return 0; }
295 void setVolumeForOutput_l(float /* left */, float /* right */) const override {}
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700296
297 // Return's the HAL's frame count i.e. fast mixer buffer size.
Andy Hung440901d2023-06-29 21:19:25 -0700298 size_t frameCountHAL() const final { return mFrameCount; }
299 size_t frameSize() const final { return mFrameSize; }
Eric Laurent81784c32012-11-19 14:55:58 -0800300
301 // Should be "virtual status_t requestExitAndWait()" and override same
302 // method in Thread, but Thread::requestExitAndWait() is not yet virtual.
Andy Hung440901d2023-06-29 21:19:25 -0700303 void exit() final;
304 status_t setParameters(const String8& keyValuePairs) final;
305
Eric Laurent10351942014-05-08 18:49:52 -0700306 // sendConfigEvent_l() must be called with ThreadBase::mLock held
307 // Can temporarily release the lock if waiting for a reply from
308 // processConfigEvents_l().
Andy Hung440901d2023-06-29 21:19:25 -0700309 status_t sendConfigEvent_l(sp<ConfigEvent>& event);
310 void sendIoConfigEvent(audio_io_config_event_t event, pid_t pid = 0,
311 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final;
312 void sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid = 0,
313 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final;
314 void sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp) final;
315 void sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio, bool forApp) final;
316 status_t sendSetParameterConfigEvent_l(const String8& keyValuePair) final;
317 status_t sendCreateAudioPatchConfigEvent(const struct audio_patch* patch,
318 audio_patch_handle_t* handle) final;
319 status_t sendReleaseAudioPatchConfigEvent(audio_patch_handle_t handle) final;
320 status_t sendUpdateOutDeviceConfigEvent(
321 const DeviceDescriptorBaseVector& outDevices) final;
322 void sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs) final;
323 void sendCheckOutputStageEffectsEvent() final;
324 void sendCheckOutputStageEffectsEvent_l() final;
325 void sendHalLatencyModesChangedEvent_l() final;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200326
Andy Hung440901d2023-06-29 21:19:25 -0700327 void processConfigEvents_l() final;
328 void setCheckOutputStageEffects() override {}
329 void updateOutDevices(const DeviceDescriptorBaseVector& outDevices) override;
330 void toAudioPortConfig(struct audio_port_config* config) override;
331 void resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs) override;
Eric Laurent1c333e22014-05-20 10:48:17 -0700332
Andy Hung440901d2023-06-29 21:19:25 -0700333 // see note at declaration of mStandby, mOutDevice and mInDevice
334 bool inStandby() const override { return mStandby; }
335 const DeviceTypeSet outDeviceTypes() const final {
336 return getAudioDeviceTypes(mOutDeviceTypeAddrs);
337 }
338 audio_devices_t inDeviceType() const final { return mInDeviceTypeAddr.mType; }
339 DeviceTypeSet getDeviceTypes() const final {
340 return isOutput() ? outDeviceTypes() : DeviceTypeSet({inDeviceType()});
341 }
Eric Laurent81784c32012-11-19 14:55:58 -0800342
Andy Hung440901d2023-06-29 21:19:25 -0700343 const AudioDeviceTypeAddrVector& outDeviceTypeAddrs() const final {
344 return mOutDeviceTypeAddrs;
345 }
346 const AudioDeviceTypeAddr& inDeviceTypeAddr() const final {
347 return mInDeviceTypeAddr;
348 }
Andy Hung293558a2017-03-21 12:19:20 -0700349
Andy Hung440901d2023-06-29 21:19:25 -0700350 bool isOutput() const final { return mIsOut; }
jiabin8f278ee2019-11-11 12:16:27 -0800351
Andy Hung440901d2023-06-29 21:19:25 -0700352 bool isOffloadOrMmap() const final {
353 switch (mType) {
354 case OFFLOAD:
355 case MMAP_PLAYBACK:
356 case MMAP_CAPTURE:
357 return true;
358 default:
359 return false;
360 }
361 }
Eric Laurent81784c32012-11-19 14:55:58 -0800362
Andy Hung440901d2023-06-29 21:19:25 -0700363 sp<IAfEffectHandle> createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -0700364 const sp<Client>& client,
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700365 const sp<media::IEffectClient>& effectClient,
Eric Laurent81784c32012-11-19 14:55:58 -0800366 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -0800367 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800368 effect_descriptor_t *desc,
369 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -0800370 status_t *status /*non-NULL*/,
Eric Laurent2fe0acd2020-03-13 14:30:46 -0700371 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +0200372 bool probe,
Andy Hung440901d2023-06-29 21:19:25 -0700373 bool notifyFramesProcessed) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800374
375 // return values for hasAudioSession (bit field)
376 enum effect_state {
377 EFFECT_SESSION = 0x1, // the audio session corresponds to at least one
378 // effect
Eric Laurent4c415062016-06-17 16:14:16 -0700379 TRACK_SESSION = 0x2, // the audio session corresponds to at least one
Eric Laurent81784c32012-11-19 14:55:58 -0800380 // track
Eric Laurentb62d0362021-10-26 17:40:18 +0200381 FAST_SESSION = 0x4, // the audio session corresponds to at least one
Eric Laurent4c415062016-06-17 16:14:16 -0700382 // fast track
jiabinc658e452022-10-21 20:52:21 +0000383 SPATIALIZED_SESSION = 0x8, // the audio session corresponds to at least one
384 // spatialized track
385 BIT_PERFECT_SESSION = 0x10 // the audio session corresponds to at least one
386 // bit-perfect track
Eric Laurent81784c32012-11-19 14:55:58 -0800387 };
388
Andy Hung440901d2023-06-29 21:19:25 -0700389 // get effect chain corresponding to session Id.
390 sp<IAfEffectChain> getEffectChain(audio_session_t sessionId) const final;
391 // same as getEffectChain() but must be called with ThreadBase mutex locked
392 sp<IAfEffectChain> getEffectChain_l(audio_session_t sessionId) const final;
393 std::vector<int> getEffectIds_l(audio_session_t sessionId) const final;
394
Eric Laurent81784c32012-11-19 14:55:58 -0800395 // lock all effect chains Mutexes. Must be called before releasing the
396 // ThreadBase mutex before processing the mixer and effects. This guarantees the
397 // integrity of the chains during the process.
398 // Also sets the parameter 'effectChains' to current value of mEffectChains.
Andy Hung440901d2023-06-29 21:19:25 -0700399 void lockEffectChains_l(Vector<sp<IAfEffectChain>>& effectChains) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800400 // unlock effect chains after process
Andy Hung440901d2023-06-29 21:19:25 -0700401 void unlockEffectChains(const Vector<sp<IAfEffectChain>>& effectChains) final;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800402 // get a copy of mEffectChains vector
Andy Hung440901d2023-06-29 21:19:25 -0700403 Vector<sp<IAfEffectChain>> getEffectChains_l() const final { return mEffectChains; };
Eric Laurent81784c32012-11-19 14:55:58 -0800404 // set audio mode to all effect chains
Andy Hung440901d2023-06-29 21:19:25 -0700405 void setMode(audio_mode_t mode) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800406 // get effect module with corresponding ID on specified audio session
Andy Hung440901d2023-06-29 21:19:25 -0700407 sp<IAfEffectModule> getEffect(audio_session_t sessionId, int effectId) const final;
408 sp<IAfEffectModule> getEffect_l(audio_session_t sessionId, int effectId) const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800409 // add and effect module. Also creates the effect chain is none exists for
Eric Laurent6c796322019-04-09 14:13:17 -0700410 // the effects audio session. Only called in a context of moving an effect
411 // from one thread to another
Andy Hung440901d2023-06-29 21:19:25 -0700412 status_t addEffect_l(const sp<IAfEffectModule>& effect) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800413 // remove and effect module. Also removes the effect chain is this was the last
414 // effect
Andy Hung440901d2023-06-29 21:19:25 -0700415 void removeEffect_l(const sp<IAfEffectModule>& effect, bool release = false) final;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -0800416 // disconnect an effect handle from module and destroy module if last handle
Andy Hung440901d2023-06-29 21:19:25 -0700417 void disconnectEffectHandle(IAfEffectHandle* handle, bool unpinIfLast) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800418 // detach all tracks connected to an auxiliary effect
Andy Hung440901d2023-06-29 21:19:25 -0700419 void detachAuxEffect_l(int /* effectId */) override {}
Andy Hung99b1ba62023-07-14 11:00:08 -0700420 // TODO(b/291317898) - remove hasAudioSession_l below.
Andy Hung440901d2023-06-29 21:19:25 -0700421 uint32_t hasAudioSession_l(audio_session_t sessionId) const override = 0;
422 uint32_t hasAudioSession(audio_session_t sessionId) const final {
Eric Laurent4c415062016-06-17 16:14:16 -0700423 Mutex::Autolock _l(mLock);
424 return hasAudioSession_l(sessionId);
425 }
426
Andy Hungc3d62f92019-03-14 13:38:51 -0700427 template <typename T>
428 uint32_t hasAudioSession_l(audio_session_t sessionId, const T& tracks) const {
429 uint32_t result = 0;
430 if (getEffectChain_l(sessionId) != 0) {
431 result = EFFECT_SESSION;
432 }
433 for (size_t i = 0; i < tracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -0700434 const sp<IAfTrackBase>& track = tracks[i];
Andy Hungc3d62f92019-03-14 13:38:51 -0700435 if (sessionId == track->sessionId()
436 && !track->isInvalid() // not yet removed from tracks.
437 && !track->isTerminated()) {
438 result |= TRACK_SESSION;
439 if (track->isFastTrack()) {
440 result |= FAST_SESSION; // caution, only represents first track.
441 }
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200442 if (track->isSpatialized()) {
Eric Laurentb62d0362021-10-26 17:40:18 +0200443 result |= SPATIALIZED_SESSION; // caution, only first track.
444 }
jiabinc658e452022-10-21 20:52:21 +0000445 if (track->isBitPerfect()) {
446 result |= BIT_PERFECT_SESSION;
447 }
Andy Hungc3d62f92019-03-14 13:38:51 -0700448 break;
449 }
450 }
451 return result;
452 }
453
Eric Laurent81784c32012-11-19 14:55:58 -0800454 // the value returned by default implementation is not important as the
455 // strategy is only meaningful for PlaybackThread which implements this method
Andy Hung440901d2023-06-29 21:19:25 -0700456 product_strategy_t getStrategyForSession_l(
457 audio_session_t /* sessionId */) const override {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800458 return static_cast<product_strategy_t>(0);
459 }
Eric Laurent81784c32012-11-19 14:55:58 -0800460
Eric Laurent81784c32012-11-19 14:55:58 -0800461 // check if some effects must be suspended/restored when an effect is enabled
462 // or disabled
Andy Hung440901d2023-06-29 21:19:25 -0700463 void checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -0800464 audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -0700465 bool threadLocked) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800466
Eric Laurent81784c32012-11-19 14:55:58 -0800467
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700468 // Return a reference to a per-thread heap which can be used to allocate IMemory
469 // objects that will be read-only to client processes, read/write to mediaserver,
470 // and shared by all client processes of the thread.
471 // The heap is per-thread rather than common across all threads, because
472 // clients can't be trusted not to modify the offset of the IMemory they receive.
473 // If a thread does not have such a heap, this method returns 0.
Andy Hung440901d2023-06-29 21:19:25 -0700474 sp<MemoryDealer> readOnlyHeap() const override { return nullptr; }
Eric Laurent81784c32012-11-19 14:55:58 -0800475
Andy Hung440901d2023-06-29 21:19:25 -0700476 sp<IMemory> pipeMemory() const override { return nullptr; }
Glenn Kasten6181ffd2014-05-13 10:41:52 -0700477
Andy Hung440901d2023-06-29 21:19:25 -0700478 void systemReady() final;
Eric Laurent72e3f392015-05-20 14:43:50 -0700479
Andy Hung440901d2023-06-29 21:19:25 -0700480 void broadcast_l() final;
Eric Laurent4c415062016-06-17 16:14:16 -0700481
Andy Hung440901d2023-06-29 21:19:25 -0700482 bool isTimestampCorrectionEnabled() const override { return false; }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800483
Andy Hung440901d2023-06-29 21:19:25 -0700484 bool isMsdDevice() const final { return mIsMsdDevice; }
Andy Hungc8fddf32018-08-08 18:32:37 -0700485
Andy Hung440901d2023-06-29 21:19:25 -0700486 void dump(int fd, const Vector<String16>& args) override;
Andy Hungdc099c22018-09-18 13:46:39 -0700487
Andy Hungd0979812019-02-21 15:51:44 -0800488 // deliver stats to mediametrics.
Andy Hung440901d2023-06-29 21:19:25 -0700489 void sendStatistics(bool force) final;
Andy Hungd0979812019-02-21 15:51:44 -0800490
Andy Hung440901d2023-06-29 21:19:25 -0700491 Mutex& mutex() const final {
492 return mLock;
493 }
Eric Laurent81784c32012-11-19 14:55:58 -0800494 mutable Mutex mLock;
495
Andy Hung440901d2023-06-29 21:19:25 -0700496 void onEffectEnable(const sp<IAfEffectModule>& effect) final;
497 void onEffectDisable() final;
Eric Laurent6b446ce2019-12-13 10:56:31 -0800498
jiabineb3bda02020-06-30 14:07:03 -0700499 // invalidateTracksForAudioSession_l must be called with holding mLock.
Andy Hung440901d2023-06-29 21:19:25 -0700500 void invalidateTracksForAudioSession_l(audio_session_t /* sessionId */) const override {}
jiabineb3bda02020-06-30 14:07:03 -0700501 // Invalidate all the tracks with the given audio session.
Andy Hung440901d2023-06-29 21:19:25 -0700502 void invalidateTracksForAudioSession(audio_session_t sessionId) const final {
jiabineb3bda02020-06-30 14:07:03 -0700503 Mutex::Autolock _l(mLock);
504 invalidateTracksForAudioSession_l(sessionId);
505 }
506
507 template <typename T>
508 void invalidateTracksForAudioSession_l(audio_session_t sessionId,
509 const T& tracks) const {
510 for (size_t i = 0; i < tracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -0700511 const sp<IAfTrackBase>& track = tracks[i];
jiabineb3bda02020-06-30 14:07:03 -0700512 if (sessionId == track->sessionId()) {
513 track->invalidate();
514 }
515 }
516 }
517
Andy Hung440901d2023-06-29 21:19:25 -0700518 void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) override;
519 void stopMelComputation_l() override;
Vlad Popa6fbbfbf2023-02-22 15:05:43 +0100520
Eric Laurent81784c32012-11-19 14:55:58 -0800521protected:
522
523 // entry describing an effect being suspended in mSuspendedSessions keyed vector
524 class SuspendedSessionDesc : public RefBase {
525 public:
526 SuspendedSessionDesc() : mRefCount(0) {}
527
528 int mRefCount; // number of active suspend requests
529 effect_uuid_t mType; // effect type UUID
530 };
531
Andy Hungdae27702016-10-31 14:01:16 -0700532 void acquireWakeLock();
533 virtual void acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800534 void releaseWakeLock();
535 void releaseWakeLock_l();
Andy Hungd01b0f12016-11-07 16:10:30 -0800536 void updateWakeLockUids_l(const SortedVector<uid_t> &uids);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800537 void getPowerManager_l();
Eric Laurentd8365c52017-07-16 15:27:05 -0700538 // suspend or restore effects of the specified type (or all if type is NULL)
539 // on a given session. The number of suspend requests is counted and restore
540 // occurs when all suspend requests are cancelled.
Eric Laurent81784c32012-11-19 14:55:58 -0800541 void setEffectSuspended_l(const effect_uuid_t *type,
542 bool suspend,
Andy Hung87c693c2023-07-06 20:56:16 -0700543 audio_session_t sessionId) final;
Eric Laurentd8365c52017-07-16 15:27:05 -0700544 // updated mSuspendedSessions when an effect is suspended or restored
Eric Laurent81784c32012-11-19 14:55:58 -0800545 void updateSuspendedSessions_l(const effect_uuid_t *type,
546 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -0800547 audio_session_t sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800548 // check if some effects must be suspended when an effect chain is added
Andy Hung116bc262023-06-20 18:56:17 -0700549 void checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain);
Eric Laurent81784c32012-11-19 14:55:58 -0800550
Kevin Rocard069c2712018-03-29 19:09:14 -0700551 // sends the metadata of the active tracks to the HAL
Vlad Popa7e81cea2023-01-19 16:34:16 +0100552 struct MetadataUpdate {
553 std::vector<playback_track_metadata_v7_t> playbackMetadataUpdate;
554 std::vector<record_track_metadata_v7_t> recordMetadataUpdate;
555 };
556 virtual MetadataUpdate updateMetadata_l() = 0;
Kevin Rocard069c2712018-03-29 19:09:14 -0700557
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100558 String16 getWakeLockTag();
559
Eric Laurent81784c32012-11-19 14:55:58 -0800560 virtual void preExit() { }
Andy Hung2ddee192015-12-18 17:34:44 -0800561 virtual void setMasterMono_l(bool mono __unused) { }
562 virtual bool requireMonoBlend() { return false; }
Eric Laurent81784c32012-11-19 14:55:58 -0800563
Andy Hung1c86ebe2018-05-29 20:29:08 -0700564 // called within the threadLoop to obtain timestamp from the HAL.
565 virtual status_t threadloop_getHalTimestamp_l(
566 ExtendedTimestamp *timestamp __unused) const {
567 return INVALID_OPERATION;
568 }
Andy Hung116bc262023-06-20 18:56:17 -0700569public:
Andy Hung99b1ba62023-07-14 11:00:08 -0700570// TODO(b/291317898) organize with publics
Eric Laurentd66d7a12021-07-13 13:35:32 +0200571 product_strategy_t getStrategyForStream(audio_stream_type_t stream) const;
Andy Hung116bc262023-06-20 18:56:17 -0700572protected:
Eric Laurentd66d7a12021-07-13 13:35:32 +0200573
Eric Laurentb0463942022-12-20 16:31:10 +0100574 virtual void onHalLatencyModesChanged_l() {}
575
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700576 virtual void dumpInternals_l(int fd __unused, const Vector<String16>& args __unused)
577 { }
578 virtual void dumpTracks_l(int fd __unused, const Vector<String16>& args __unused) { }
579
Eric Laurent81784c32012-11-19 14:55:58 -0800580 const type_t mType;
581
582 // Used by parameters, config events, addTrack_l, exit
583 Condition mWaitWorkCV;
584
Andy Hung583043b2023-07-17 17:05:00 -0700585 const sp<IAfThreadCallback> mAfThreadCallback;
Andy Hungcf10d742020-04-28 15:38:24 -0700586 ThreadMetrics mThreadMetrics;
587 const bool mIsOut;
Glenn Kasten9b58f632013-07-16 11:37:48 -0700588
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800589 // updated by PlaybackThread::readOutputParameters_l() or
590 // RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800591 uint32_t mSampleRate;
592 size_t mFrameCount; // output HAL, direct output, record
Eric Laurent81784c32012-11-19 14:55:58 -0800593 audio_channel_mask_t mChannelMask;
Glenn Kastenf6ed4232013-07-16 11:16:27 -0700594 uint32_t mChannelCount;
Eric Laurent81784c32012-11-19 14:55:58 -0800595 size_t mFrameSize;
Glenn Kasten97b7b752014-09-28 13:04:24 -0700596 // not HAL frame size, this is for output sink (to pipe to fast mixer)
Andy Hung463be252014-07-10 16:56:07 -0700597 audio_format_t mFormat; // Source format for Recording and
598 // Sink format for Playback.
599 // Sink format may be different than
600 // HAL format if Fastmixer is used.
601 audio_format_t mHALFormat;
Glenn Kasten70949c42013-08-06 07:40:12 -0700602 size_t mBufferSize; // HAL buffer size for read() or write()
jiabinc52b1ff2019-10-31 17:20:42 -0700603 AudioDeviceTypeAddrVector mOutDeviceTypeAddrs; // output device types and addresses
604 AudioDeviceTypeAddr mInDeviceTypeAddr; // input device type and address
Eric Laurent10351942014-05-08 18:49:52 -0700605 Vector< sp<ConfigEvent> > mConfigEvents;
Eric Laurent72e3f392015-05-20 14:43:50 -0700606 Vector< sp<ConfigEvent> > mPendingConfigEvents; // events awaiting system ready
Eric Laurent81784c32012-11-19 14:55:58 -0800607
608 // These fields are written and read by thread itself without lock or barrier,
jiabinc52b1ff2019-10-31 17:20:42 -0700609 // and read by other threads without lock or barrier via standby(), outDeviceTypes()
610 // and inDeviceType().
Eric Laurent81784c32012-11-19 14:55:58 -0800611 // Because of the absence of a lock or barrier, any other thread that reads
612 // these fields must use the information in isolation, or be prepared to deal
613 // with possibility that it might be inconsistent with other information.
Glenn Kasten4944acb2013-08-19 08:39:20 -0700614 bool mStandby; // Whether thread is currently in standby.
jiabinc52b1ff2019-10-31 17:20:42 -0700615
Eric Laurent296fb132015-05-01 11:38:42 -0700616 struct audio_patch mPatch;
jiabinc52b1ff2019-10-31 17:20:42 -0700617
Glenn Kastenf59497b2015-01-26 16:35:47 -0800618 audio_source_t mAudioSource;
Eric Laurent81784c32012-11-19 14:55:58 -0800619
620 const audio_io_handle_t mId;
Andy Hung116bc262023-06-20 18:56:17 -0700621 Vector<sp<IAfEffectChain>> mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -0800622
Glenn Kastend7dca052015-03-05 16:05:54 -0800623 static const int kThreadNameLength = 16; // prctl(PR_SET_NAME) limit
624 char mThreadName[kThreadNameLength]; // guaranteed NUL-terminated
Chris Ye6597d732020-02-28 22:38:25 -0800625 sp<os::IPowerManager> mPowerManager;
Eric Laurent81784c32012-11-19 14:55:58 -0800626 sp<IBinder> mWakeLockToken;
627 const sp<PMDeathRecipient> mDeathRecipient;
Glenn Kastend848eb42016-03-08 13:42:11 -0800628 // list of suspended effects per session and per type. The first (outer) vector is
629 // keyed by session ID, the second (inner) by type UUID timeLow field
Eric Laurentd8365c52017-07-16 15:27:05 -0700630 // Updated by updateSuspendedSessions_l() only.
Glenn Kastend848eb42016-03-08 13:42:11 -0800631 KeyedVector< audio_session_t, KeyedVector< int, sp<SuspendedSessionDesc> > >
Eric Laurent81784c32012-11-19 14:55:58 -0800632 mSuspendedSessions;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -0700633 // TODO: add comment and adjust size as needed
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800634 static const size_t kLogSize = 4 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -0800635 sp<NBLog::Writer> mNBLogWriter;
Eric Laurent72e3f392015-05-20 14:43:50 -0700636 bool mSystemReady;
Andy Hung818e7a32016-02-16 18:08:07 -0800637 ExtendedTimestamp mTimestamp;
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700638 TimestampVerifier< // For timestamp statistics.
639 int64_t /* frame count */, int64_t /* time ns */> mTimestampVerifier;
Dean Wheatley12473e92021-03-18 23:00:55 +1100640 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush
641 // TODO: add confirmation checks:
642 // 1) DIRECT threads and linear PCM format really resets to 0?
643 // 2) Is frame count really valid if not linear pcm?
644 // 3) Are all 64 bits of position returned, not just lowest 32 bits?
jiabinc52b1ff2019-10-31 17:20:42 -0700645 // Timestamp corrected device should be a single device.
646 audio_devices_t mTimestampCorrectedDevice = AUDIO_DEVICE_NONE;
Andy Hung446f4df2019-02-21 12:26:41 -0800647
648 // ThreadLoop statistics per iteration.
649 int64_t mLastIoBeginNs = -1;
650 int64_t mLastIoEndNs = -1;
651
Andy Hung44d648b2022-04-08 17:33:40 -0700652 // ThreadSnapshot is thread-safe (internally locked)
653 mediautils::ThreadSnapshot mThreadSnapshot;
654
Andy Hung446f4df2019-02-21 12:26:41 -0800655 // This should be read under ThreadBase lock (if not on the threadLoop thread).
656 audio_utils::Statistics<double> mIoJitterMs{0.995 /* alpha */};
657 audio_utils::Statistics<double> mProcessTimeMs{0.995 /* alpha */};
Andy Hunge6c37112019-02-26 17:38:10 -0800658 audio_utils::Statistics<double> mLatencyMs{0.995 /* alpha */};
Robert Wu06db0a32021-08-10 19:05:34 +0000659 audio_utils::Statistics<double> mMonopipePipeDepthStats{0.999 /* alpha */};
Andy Hung446f4df2019-02-21 12:26:41 -0800660
Andy Hungd0979812019-02-21 15:51:44 -0800661 // Save the last count when we delivered statistics to mediametrics.
662 int64_t mLastRecordedTimestampVerifierN = 0;
663 int64_t mLastRecordedTimeNs = 0; // BOOTTIME to include suspend.
664
Andy Hungc8fddf32018-08-08 18:32:37 -0700665 bool mIsMsdDevice = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800666 // A condition that must be evaluated by the thread loop has changed and
667 // we must not wait for async write callback in the thread loop before evaluating it
668 bool mSignalPending;
Andy Hungdae27702016-10-31 14:01:16 -0700669
Andy Hung8946a282018-04-19 20:04:56 -0700670#ifdef TEE_SINK
671 NBAIO_Tee mTee;
672#endif
Andy Hungdae27702016-10-31 14:01:16 -0700673 // ActiveTracks is a sorted vector of track type T representing the
674 // active tracks of threadLoop() to be considered by the locked prepare portion.
675 // ActiveTracks should be accessed with the ThreadBase lock held.
676 //
677 // During processing and I/O, the threadLoop does not hold the lock;
678 // hence it does not directly use ActiveTracks. Care should be taken
679 // to hold local strong references or defer removal of tracks
680 // if the threadLoop may still be accessing those tracks due to mix, etc.
681 //
682 // This class updates power information appropriately.
683 //
684
685 template <typename T>
686 class ActiveTracks {
687 public:
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700688 explicit ActiveTracks(SimpleLog *localLog = nullptr)
Andy Hungdae27702016-10-31 14:01:16 -0700689 : mActiveTracksGeneration(0)
690 , mLastActiveTracksGeneration(0)
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700691 , mLocalLog(localLog)
Andy Hungdae27702016-10-31 14:01:16 -0700692 { }
693
694 ~ActiveTracks() {
695 ALOGW_IF(!mActiveTracks.isEmpty(),
696 "ActiveTracks should be empty in destructor");
697 }
698 // returns the last track added (even though it may have been
699 // subsequently removed from ActiveTracks).
700 //
701 // Used for DirectOutputThread to ensure a flush is called when transitioning
702 // to a new track (even though it may be on the same session).
703 // Used for OffloadThread to ensure that volume and mixer state is
704 // taken from the latest track added.
705 //
706 // The latest track is saved with a weak pointer to prevent keeping an
707 // otherwise useless track alive. Thus the function will return nullptr
708 // if the latest track has subsequently been removed and destroyed.
709 sp<T> getLatest() {
710 return mLatestActiveTrack.promote();
711 }
712
713 // SortedVector methods
714 ssize_t add(const sp<T> &track);
715 ssize_t remove(const sp<T> &track);
716 size_t size() const {
717 return mActiveTracks.size();
718 }
Eric Tan39ec8d62018-07-24 09:49:29 -0700719 bool isEmpty() const {
720 return mActiveTracks.isEmpty();
721 }
Andy Hung87c693c2023-07-06 20:56:16 -0700722 ssize_t indexOf(const sp<T>& item) const {
Andy Hungdae27702016-10-31 14:01:16 -0700723 return mActiveTracks.indexOf(item);
724 }
725 sp<T> operator[](size_t index) const {
726 return mActiveTracks[index];
727 }
728 typename SortedVector<sp<T>>::iterator begin() {
729 return mActiveTracks.begin();
730 }
731 typename SortedVector<sp<T>>::iterator end() {
732 return mActiveTracks.end();
733 }
734
735 // Due to Binder recursion optimization, clear() and updatePowerState()
736 // cannot be called from a Binder thread because they may call back into
737 // the original calling process (system server) for BatteryNotifier
738 // (which requires a Java environment that may not be present).
739 // Hence, call clear() and updatePowerState() only from the
740 // ThreadBase thread.
741 void clear();
742 // periodically called in the threadLoop() to update power state uids.
Andy Hung920f6572022-10-06 12:09:49 -0700743 void updatePowerState(const sp<ThreadBase>& thread, bool force = false);
Andy Hungdae27702016-10-31 14:01:16 -0700744
Kevin Rocardc86a7f72018-04-03 09:00:09 -0700745 /** @return true if one or move active tracks was added or removed since the
Jasmine Chaeaa10e42021-05-11 10:11:14 +0800746 * last time this function was called or the vector was created.
747 * true if volume of one of active tracks was changed.
748 */
Kevin Rocard069c2712018-03-29 19:09:14 -0700749 bool readAndClearHasChanged();
750
Eric Laurentdda206a2022-07-08 17:28:35 +0200751 /** Force updating track metadata to audio HAL stream next time
752 * readAndClearHasChanged() is called.
753 */
754 void setHasChanged() { mHasChanged = true; }
755
Andy Hungdae27702016-10-31 14:01:16 -0700756 private:
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700757 void logTrack(const char *funcName, const sp<T> &track) const;
758
Andy Hungd01b0f12016-11-07 16:10:30 -0800759 SortedVector<uid_t> getWakeLockUids() {
760 SortedVector<uid_t> wakeLockUids;
Andy Hungdae27702016-10-31 14:01:16 -0700761 for (const sp<T> &track : mActiveTracks) {
762 wakeLockUids.add(track->uid());
763 }
764 return wakeLockUids; // moved by underlying SharedBuffer
765 }
766
Andy Hungdae27702016-10-31 14:01:16 -0700767 SortedVector<sp<T>> mActiveTracks;
768 int mActiveTracksGeneration;
769 int mLastActiveTracksGeneration;
770 wp<T> mLatestActiveTrack; // latest track added to ActiveTracks
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700771 SimpleLog * const mLocalLog;
Kevin Rocardc86a7f72018-04-03 09:00:09 -0700772 // If the vector has changed since last call to readAndClearHasChanged
Kevin Rocard069c2712018-03-29 19:09:14 -0700773 bool mHasChanged = false;
Andy Hungdae27702016-10-31 14:01:16 -0700774 };
Andy Hung293558a2017-03-21 12:19:20 -0700775
776 SimpleLog mLocalLog;
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700777
778private:
779 void dumpBase_l(int fd, const Vector<String16>& args);
780 void dumpEffectChains_l(int fd, const Vector<String16>& args);
Eric Laurent81784c32012-11-19 14:55:58 -0800781};
782
783// --- PlaybackThread ---
Andy Hung440901d2023-06-29 21:19:25 -0700784class PlaybackThread : public ThreadBase, public virtual IAfPlaybackThread,
785 public StreamOutHalInterfaceCallback,
Andy Hung87c693c2023-07-06 20:56:16 -0700786 public virtual VolumeInterface, public StreamOutHalInterfaceEventCallback {
Eric Laurent81784c32012-11-19 14:55:58 -0800787public:
Andy Hung87c693c2023-07-06 20:56:16 -0700788 sp<IAfPlaybackThread> asIAfPlaybackThread() final {
789 return sp<IAfPlaybackThread>::fromExisting(this);
790 }
Eric Laurent81784c32012-11-19 14:55:58 -0800791
Eric Laurente93cc032016-05-05 10:15:10 -0700792 // retry count before removing active track in case of underrun on offloaded thread:
793 // we need to make sure that AudioTrack client has enough time to send large buffers
794 //FIXME may be more appropriate if expressed in time units. Need to revise how underrun is
795 // handled for offloaded tracks
796 static const int8_t kMaxTrackRetriesOffload = 20;
797 static const int8_t kMaxTrackStartupRetriesOffload = 100;
Andy Hung8ed196a2018-01-05 13:21:11 -0800798 static constexpr uint32_t kMaxTracksPerUid = 40;
Andy Hung1bc088a2018-02-09 15:57:31 -0800799 static constexpr size_t kMaxTracks = 256;
Eric Laurente93cc032016-05-05 10:15:10 -0700800
rago1bb90822017-05-02 18:31:48 -0700801 // Maximum delay (in nanoseconds) for upcoming buffers in suspend mode, otherwise
802 // if delay is greater, the estimated time for timeLoopNextNs is reset.
803 // This allows for catch-up to be done for small delays, while resetting the estimate
804 // for initial conditions or large delays.
805 static const nsecs_t kMaxNextBufferDelayNs = 100000000;
806
Andy Hung583043b2023-07-17 17:05:00 -0700807 PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +0200808 audio_io_handle_t id, type_t type, bool systemReady,
809 audio_config_base_t *mixerConfig = nullptr);
Andy Hung440901d2023-06-29 21:19:25 -0700810 ~PlaybackThread() override;
Eric Laurent81784c32012-11-19 14:55:58 -0800811
Eric Laurent81784c32012-11-19 14:55:58 -0800812 // Thread virtuals
Andy Hung440901d2023-06-29 21:19:25 -0700813 bool threadLoop() final;
Eric Laurent81784c32012-11-19 14:55:58 -0800814
815 // RefBase
Andy Hung440901d2023-06-29 21:19:25 -0700816 void onFirstRef() override;
Eric Laurent81784c32012-11-19 14:55:58 -0800817
Andy Hung440901d2023-06-29 21:19:25 -0700818 status_t checkEffectCompatibility_l(
819 const effect_descriptor_t* desc, audio_session_t sessionId) final;
Eric Laurent4c415062016-06-17 16:14:16 -0700820
Andy Hung87c693c2023-07-06 20:56:16 -0700821 void addOutputTrack_l(const sp<IAfTrack>& track) final {
822 mTracks.add(track);
823 }
824
Eric Laurent81784c32012-11-19 14:55:58 -0800825protected:
826 // Code snippets that were lifted up out of threadLoop()
827 virtual void threadLoop_mix() = 0;
828 virtual void threadLoop_sleepTime() = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800829 virtual ssize_t threadLoop_write();
830 virtual void threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -0800831 virtual void threadLoop_standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800832 virtual void threadLoop_exit();
Andy Hung8d31fd22023-06-26 19:20:57 -0700833 virtual void threadLoop_removeTracks(const Vector<sp<IAfTrack>>& tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -0800834
835 // prepareTracks_l reads and writes mActiveTracks, and returns
836 // the pending set of tracks to remove via Vector 'tracksToRemove'. The caller
837 // is responsible for clearing or destroying this Vector later on, when it
838 // is safe to do so. That will drop the final ref count and destroy the tracks.
Andy Hung8d31fd22023-06-26 19:20:57 -0700839 virtual mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove) = 0;
840 void removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove);
Eric Laurenteab90452019-06-24 15:17:46 -0700841 status_t handleVoipVolume_l(float *volume);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800842
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700843 // StreamOutHalInterfaceCallback implementation
844 virtual void onWriteReady();
845 virtual void onDrainReady();
846 virtual void onError();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800847
Andy Hungee58e4a2023-07-07 13:47:37 -0700848public: // AsyncCallbackThread
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700849 void resetWriteBlocked(uint32_t sequence);
850 void resetDraining(uint32_t sequence);
Andy Hungee58e4a2023-07-07 13:47:37 -0700851protected:
Eric Laurentbfb1b832013-01-07 09:53:42 -0800852
853 virtual bool waitingAsyncCallback();
854 virtual bool waitingAsyncCallback_l();
855 virtual bool shouldStandby_l();
Haynes Mathew George4c6a4332014-01-15 12:31:39 -0800856 virtual void onAddNewTrack_l();
Andy Hungee58e4a2023-07-07 13:47:37 -0700857public: // AsyncCallbackThread
Haynes Mathew George4527b9e2016-07-07 19:54:17 -0700858 void onAsyncError(); // error reported by AsyncCallbackThread
Andy Hungee58e4a2023-07-07 13:47:37 -0700859protected:
jiabinf6eb4c32020-02-25 14:06:25 -0800860 // StreamHalInterfaceCodecFormatCallback implementation
861 void onCodecFormatChanged(
Andy Hung440901d2023-06-29 21:19:25 -0700862 const std::basic_string<uint8_t>& metadataBs) final;
jiabinf6eb4c32020-02-25 14:06:25 -0800863
Eric Laurent81784c32012-11-19 14:55:58 -0800864 // ThreadBase virtuals
865 virtual void preExit();
866
Eric Laurent64667972016-03-30 18:19:46 -0700867 virtual bool keepWakeLock() const { return true; }
Andy Hungdae27702016-10-31 14:01:16 -0700868 virtual void acquireWakeLock_l() {
869 ThreadBase::acquireWakeLock_l();
870 mActiveTracks.updatePowerState(this, true /* force */);
871 }
Eric Laurent64667972016-03-30 18:19:46 -0700872
Eric Laurentb3f315a2021-07-13 15:09:05 +0200873 virtual void checkOutputStageEffects() {}
Eric Laurent68a40a82022-05-03 18:15:04 +0200874 virtual void setHalLatencyMode_l() {}
875
Eric Laurentb3f315a2021-07-13 15:09:05 +0200876
Andy Hung440901d2023-06-29 21:19:25 -0700877 void dumpInternals_l(int fd, const Vector<String16>& args) override;
878 void dumpTracks_l(int fd, const Vector<String16>& args) final;
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700879
Eric Laurent81784c32012-11-19 14:55:58 -0800880public:
881
Andy Hung440901d2023-06-29 21:19:25 -0700882 status_t initCheck() const final { return mOutput == nullptr ? NO_INIT : NO_ERROR; }
Eric Laurent81784c32012-11-19 14:55:58 -0800883
884 // return estimated latency in milliseconds, as reported by HAL
Andy Hung440901d2023-06-29 21:19:25 -0700885 uint32_t latency() const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800886 // same, but lock must already be held
Andy Hung440901d2023-06-29 21:19:25 -0700887 uint32_t latency_l() const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800888
Eric Laurent6acd1d42017-01-04 14:23:29 -0800889 // VolumeInterface
Andy Hung440901d2023-06-29 21:19:25 -0700890 void setMasterVolume(float value) final;
891 void setMasterBalance(float balance) override;
892 void setMasterMute(bool muted) final;
893 void setStreamVolume(audio_stream_type_t stream, float value) final;
894 void setStreamMute(audio_stream_type_t stream, bool muted) final;
895 float streamVolume(audio_stream_type_t stream) const final;
896 void setVolumeForOutput_l(float left, float right) const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800897
Andy Hung440901d2023-06-29 21:19:25 -0700898 sp<IAfTrack> createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -0700899 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -0800900 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700901 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -0800902 uint32_t *sampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -0800903 audio_format_t format,
904 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -0800905 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -0800906 size_t *pNotificationFrameCount,
907 uint32_t notificationsPerBuffer,
908 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -0800909 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -0800910 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -0700911 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700912 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +0000913 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -0800914 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800915 status_t *status /*non-NULL*/,
jiabinf6eb4c32020-02-25 14:06:25 -0800916 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200917 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +0000918 bool isSpatialized,
Andy Hung440901d2023-06-29 21:19:25 -0700919 bool isBitPerfect) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800920
Andy Hung87c693c2023-07-06 20:56:16 -0700921 bool isTrackActive(const sp<IAfTrack>& track) const final {
922 return mActiveTracks.indexOf(track) >= 0;
923 }
924
925 AudioStreamOut* getOutput_l() const final { return mOutput; }
Andy Hung440901d2023-06-29 21:19:25 -0700926 AudioStreamOut* getOutput() const final;
927 AudioStreamOut* clearOutput() final;
928 sp<StreamHalInterface> stream() const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800929
930 // a very large number of suspend() will eventually wraparound, but unlikely
Andy Hung440901d2023-06-29 21:19:25 -0700931 void suspend() final { (void) android_atomic_inc(&mSuspended); }
932 void restore() final
Eric Laurent81784c32012-11-19 14:55:58 -0800933 {
934 // if restore() is done without suspend(), get back into
935 // range so that the next suspend() will operate correctly
936 if (android_atomic_dec(&mSuspended) <= 0) {
937 android_atomic_release_store(0, &mSuspended);
938 }
939 }
Andy Hung440901d2023-06-29 21:19:25 -0700940 bool isSuspended() const final
Eric Laurent81784c32012-11-19 14:55:58 -0800941 { return android_atomic_acquire_load(&mSuspended) > 0; }
942
Andy Hung440901d2023-06-29 21:19:25 -0700943 String8 getParameters(const String8& keys);
944 void ioConfigChanged(audio_io_config_event_t event, pid_t pid = 0,
945 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final;
946 status_t getRenderPosition(uint32_t* halFrames, uint32_t* dspFrames) const final;
Andy Hung010a1a12014-03-13 13:57:33 -0700947 // Consider also removing and passing an explicit mMainBuffer initialization
Andy Hung8d31fd22023-06-26 19:20:57 -0700948 // parameter to AF::IAfTrack::Track().
Andy Hung440901d2023-06-29 21:19:25 -0700949 float* sinkBuffer() const final {
Andy Hung319587b2023-05-23 14:01:03 -0700950 return reinterpret_cast<float *>(mSinkBuffer); };
Eric Laurent81784c32012-11-19 14:55:58 -0800951
Andy Hung440901d2023-06-29 21:19:25 -0700952 void detachAuxEffect_l(int effectId) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800953
Andy Hung440901d2023-06-29 21:19:25 -0700954 status_t attachAuxEffect(const sp<IAfTrack>& track, int EffectId) final;
955 status_t attachAuxEffect_l(const sp<IAfTrack>& track, int EffectId) final;
956
957 status_t addEffectChain_l(const sp<IAfEffectChain>& chain) final;
958 size_t removeEffectChain_l(const sp<IAfEffectChain>& chain) final;
959 uint32_t hasAudioSession_l(audio_session_t sessionId) const final {
Andy Hungc3d62f92019-03-14 13:38:51 -0700960 return ThreadBase::hasAudioSession_l(sessionId, mTracks);
961 }
Andy Hung440901d2023-06-29 21:19:25 -0700962 product_strategy_t getStrategyForSession_l(audio_session_t sessionId) const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800963
964
Andy Hung440901d2023-06-29 21:19:25 -0700965 status_t setSyncEvent(const sp<audioflinger::SyncEvent>& event) final;
966 bool isValidSyncEvent(const sp<audioflinger::SyncEvent>& event) const final;
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700967
968 // called with AudioFlinger lock held
Andy Hung440901d2023-06-29 21:19:25 -0700969 bool invalidateTracks_l(audio_stream_type_t streamType) final;
970 bool invalidateTracks_l(std::set<audio_port_handle_t>& portIds) final;
971 void invalidateTracks(audio_stream_type_t streamType) override;
jiabinc44b3462022-12-08 12:52:31 -0800972 // Invalidate tracks by a set of port ids. The port id will be removed from
973 // the given set if the corresponding track is found and invalidated.
Andy Hung440901d2023-06-29 21:19:25 -0700974 void invalidateTracks(std::set<audio_port_handle_t>& portIds) override;
Eric Laurent81784c32012-11-19 14:55:58 -0800975
Andy Hung87c693c2023-07-06 20:56:16 -0700976 size_t frameCount() const final { return mNormalFrameCount; }
Glenn Kasten9b58f632013-07-16 11:37:48 -0700977
Andy Hung440901d2023-06-29 21:19:25 -0700978 audio_channel_mask_t mixerChannelMask() const final {
Eric Laurentf1f22e72021-07-13 14:04:14 +0200979 return mMixerChannelMask;
980 }
981
Andy Hung440901d2023-06-29 21:19:25 -0700982 status_t getTimestamp_l(AudioTimestamp& timestamp) final;
Eric Laurent83b88082014-06-20 18:31:16 -0700983
Andy Hung440901d2023-06-29 21:19:25 -0700984 void addPatchTrack(const sp<IAfPatchTrack>& track) final;
985 void deletePatchTrack(const sp<IAfPatchTrack>& track) final;
Eric Laurent83b88082014-06-20 18:31:16 -0700986
Andy Hung440901d2023-06-29 21:19:25 -0700987 void toAudioPortConfig(struct audio_port_config* config) final;
Eric Laurentaccc1472013-09-20 09:36:34 -0700988
Andy Hung10cbff12017-02-21 17:30:14 -0800989 // Return the asynchronous signal wait time.
Andy Hung440901d2023-06-29 21:19:25 -0700990 int64_t computeWaitTimeNs_l() const override { return INT64_MAX; }
Andy Hung1bc088a2018-02-09 15:57:31 -0800991 // returns true if the track is allowed to be added to the thread.
Andy Hung440901d2023-06-29 21:19:25 -0700992 bool isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -0800993 audio_channel_mask_t channelMask __unused,
994 audio_format_t format __unused,
995 audio_session_t sessionId __unused,
Andy Hung440901d2023-06-29 21:19:25 -0700996 uid_t uid) const override {
Andy Hung1bc088a2018-02-09 15:57:31 -0800997 return trackCountForUid_l(uid) < PlaybackThread::kMaxTracksPerUid
998 && mTracks.size() < PlaybackThread::kMaxTracks;
999 }
1000
Andy Hung440901d2023-06-29 21:19:25 -07001001 bool isTimestampCorrectionEnabled() const final {
jiabinc52b1ff2019-10-31 17:20:42 -07001002 return audio_is_output_devices(mTimestampCorrectedDevice)
1003 && outDeviceTypes().count(mTimestampCorrectedDevice) != 0;
Andy Hungc8fddf32018-08-08 18:32:37 -07001004 }
jiabinc52b1ff2019-10-31 17:20:42 -07001005
Andy Hung440901d2023-06-29 21:19:25 -07001006 bool isStreamInitialized() const final {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001007 return !(mOutput == nullptr || mOutput->stream == nullptr);
1008 }
1009
Andy Hung440901d2023-06-29 21:19:25 -07001010 audio_channel_mask_t hapticChannelMask() const final {
jiabineb3bda02020-06-30 14:07:03 -07001011 return mHapticChannelMask;
1012 }
Andy Hung87c693c2023-07-06 20:56:16 -07001013
1014 uint32_t hapticChannelCount() const final {
1015 return mHapticChannelCount;
1016 }
1017
Andy Hung440901d2023-06-29 21:19:25 -07001018 bool supportsHapticPlayback() const final {
jiabineb3bda02020-06-30 14:07:03 -07001019 return (mHapticChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE;
1020 }
1021
Andy Hung440901d2023-06-29 21:19:25 -07001022 void setDownStreamPatch(const struct audio_patch* patch) final {
Eric Laurent74c38dc2020-12-23 18:19:44 +01001023 Mutex::Autolock _l(mLock);
1024 mDownStreamPatch = *patch;
1025 }
1026
Andy Hung440901d2023-06-29 21:19:25 -07001027 IAfTrack* getTrackById_l(audio_port_handle_t trackId) final;
jiabinf042b9b2021-05-07 23:46:28 +00001028
Andy Hung440901d2023-06-29 21:19:25 -07001029 bool hasMixer() const final {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001030 return mType == MIXER || mType == DUPLICATING || mType == SPATIALIZER;
Eric Laurentb3f315a2021-07-13 15:09:05 +02001031 }
Eric Laurent68a40a82022-05-03 18:15:04 +02001032
Andy Hung440901d2023-06-29 21:19:25 -07001033 status_t setRequestedLatencyMode(
1034 audio_latency_mode_t /* mode */) override { return INVALID_OPERATION; }
Eric Laurent68a40a82022-05-03 18:15:04 +02001035
Andy Hung440901d2023-06-29 21:19:25 -07001036 status_t getSupportedLatencyModes(
1037 std::vector<audio_latency_mode_t>* /* modes */) override {
Eric Laurent68a40a82022-05-03 18:15:04 +02001038 return INVALID_OPERATION;
1039 }
1040
Andy Hung440901d2023-06-29 21:19:25 -07001041 status_t setBluetoothVariableLatencyEnabled(bool /* enabled */) override{
Eric Laurentb0463942022-12-20 16:31:10 +01001042 return INVALID_OPERATION;
1043 }
Eric Laurent52057642022-12-16 11:45:07 +01001044
Andy Hung440901d2023-06-29 21:19:25 -07001045 void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) override;
1046 void stopMelComputation_l() override;
Vlad Popab042ee62022-10-20 18:05:00 +02001047
Andy Hung440901d2023-06-29 21:19:25 -07001048 void setStandby() final {
Eric Laurent19952e12023-04-20 10:08:29 +02001049 Mutex::Autolock _l(mLock);
1050 setStandby_l();
1051 }
1052
Andy Hung440901d2023-06-29 21:19:25 -07001053 void setStandby_l() final {
Eric Laurent19952e12023-04-20 10:08:29 +02001054 mStandby = true;
1055 mHalStarted = false;
1056 mKernelPositionOnStandby =
1057 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
1058 }
1059
Andy Hung440901d2023-06-29 21:19:25 -07001060 bool waitForHalStart() final {
Eric Laurent19952e12023-04-20 10:08:29 +02001061 Mutex::Autolock _l(mLock);
1062 static const nsecs_t kWaitHalTimeoutNs = seconds(2);
1063 nsecs_t endWaitTimetNs = systemTime() + kWaitHalTimeoutNs;
1064 while (!mHalStarted) {
1065 nsecs_t timeNs = systemTime();
1066 if (timeNs >= endWaitTimetNs) {
1067 break;
1068 }
1069 nsecs_t waitTimeLeftNs = endWaitTimetNs - timeNs;
1070 mWaitHalStartCV.waitRelative(mLock, waitTimeLeftNs);
1071 }
1072 return mHalStarted;
1073 }
Eric Laurent81784c32012-11-19 14:55:58 -08001074protected:
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001075 // updated by readOutputParameters_l()
Glenn Kasten9b58f632013-07-16 11:37:48 -07001076 size_t mNormalFrameCount; // normal mixer and effects
1077
Andy Hung08fb1742015-05-31 23:22:10 -07001078 bool mThreadThrottle; // throttle the thread processing
Andy Hung40eb1a12015-06-18 13:42:02 -07001079 uint32_t mThreadThrottleTimeMs; // throttle time for MIXER threads
1080 uint32_t mThreadThrottleEndMs; // notify once per throttling
Andy Hung08fb1742015-05-31 23:22:10 -07001081 uint32_t mHalfBufferMs; // half the buffer size in milliseconds
1082
Andy Hung010a1a12014-03-13 13:57:33 -07001083 void* mSinkBuffer; // frame size aligned sink buffer
Eric Laurent81784c32012-11-19 14:55:58 -08001084
Andy Hung98ef9782014-03-04 14:46:50 -08001085 // TODO:
1086 // Rearrange the buffer info into a struct/class with
1087 // clear, copy, construction, destruction methods.
1088 //
1089 // mSinkBuffer also has associated with it:
1090 //
1091 // mSinkBufferSize: Sink Buffer Size
1092 // mFormat: Sink Buffer Format
1093
Andy Hung69aed5f2014-02-25 17:24:40 -08001094 // Mixer Buffer (mMixerBuffer*)
1095 //
1096 // In the case of floating point or multichannel data, which is not in the
1097 // sink format, it is required to accumulate in a higher precision or greater channel count
1098 // buffer before downmixing or data conversion to the sink buffer.
1099
1100 // Set to "true" to enable the Mixer Buffer otherwise mixer output goes to sink buffer.
1101 bool mMixerBufferEnabled;
1102
1103 // Storage, 32 byte aligned (may make this alignment a requirement later).
1104 // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
1105 void* mMixerBuffer;
1106
1107 // Size of mMixerBuffer in bytes: mNormalFrameCount * #channels * sampsize.
1108 size_t mMixerBufferSize;
1109
1110 // The audio format of mMixerBuffer. Set to AUDIO_FORMAT_PCM_(FLOAT|16_BIT) only.
1111 audio_format_t mMixerBufferFormat;
1112
1113 // An internal flag set to true by MixerThread::prepareTracks_l()
1114 // when mMixerBuffer contains valid data after mixing.
1115 bool mMixerBufferValid;
1116
Andy Hung98ef9782014-03-04 14:46:50 -08001117 // Effects Buffer (mEffectsBuffer*)
1118 //
1119 // In the case of effects data, which is not in the sink format,
1120 // it is required to accumulate in a different buffer before data conversion
1121 // to the sink buffer.
1122
1123 // Set to "true" to enable the Effects Buffer otherwise effects output goes to sink buffer.
1124 bool mEffectBufferEnabled;
1125
1126 // Storage, 32 byte aligned (may make this alignment a requirement later).
1127 // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
1128 void* mEffectBuffer;
1129
1130 // Size of mEffectsBuffer in bytes: mNormalFrameCount * #channels * sampsize.
1131 size_t mEffectBufferSize;
1132
1133 // The audio format of mEffectsBuffer. Set to AUDIO_FORMAT_PCM_16_BIT only.
1134 audio_format_t mEffectBufferFormat;
1135
1136 // An internal flag set to true by MixerThread::prepareTracks_l()
1137 // when mEffectsBuffer contains valid data after mixing.
1138 //
1139 // When this is set, all mixer data is routed into the effects buffer
1140 // for any processing (including output processing).
1141 bool mEffectBufferValid;
1142
jiabinc658e452022-10-21 20:52:21 +00001143 // Set to "true" to enable when data has already copied to sink
1144 bool mHasDataCopiedToSinkBuffer = false;
1145
Eric Laurentb62d0362021-10-26 17:40:18 +02001146 // Frame size aligned buffer used as input and output to all post processing effects
1147 // except the Spatializer in a SPATIALIZER thread. Non spatialized tracks are mixed into
1148 // this buffer so that post processing effects can be applied.
1149 void* mPostSpatializerBuffer = nullptr;
1150
1151 // Size of mPostSpatializerBuffer in bytes
1152 size_t mPostSpatializerBufferSize;
Eric Laurent39095982021-08-24 18:29:27 +02001153
1154
Eric Laurent81784c32012-11-19 14:55:58 -08001155 // suspend count, > 0 means suspended. While suspended, the thread continues to pull from
1156 // tracks and mix, but doesn't write to HAL. A2DP and SCO HAL implementations can't handle
1157 // concurrent use of both of them, so Audio Policy Service suspends one of the threads to
1158 // workaround that restriction.
1159 // 'volatile' means accessed via atomic operations and no lock.
1160 volatile int32_t mSuspended;
1161
Andy Hung818e7a32016-02-16 18:08:07 -08001162 int64_t mBytesWritten;
yucliu6cfb5932022-07-20 17:40:39 -07001163 std::atomic<int64_t> mFramesWritten; // not reset on standby
Dean Wheatley12473e92021-03-18 23:00:55 +11001164 int64_t mLastFramesWritten = -1; // track changes in timestamp
1165 // server frames written.
Andy Hung238fa3d2016-07-28 10:53:22 -07001166 int64_t mSuspendedFrames; // not reset on standby
jiabin245cdd92018-12-07 17:55:15 -08001167
1168 // mHapticChannelMask and mHapticChannelCount will only be valid when the thread support
1169 // haptic playback.
1170 audio_channel_mask_t mHapticChannelMask = AUDIO_CHANNEL_NONE;
1171 uint32_t mHapticChannelCount = 0;
Eric Laurentf1f22e72021-07-13 14:04:14 +02001172
1173 audio_channel_mask_t mMixerChannelMask = AUDIO_CHANNEL_NONE;
1174
Eric Laurent81784c32012-11-19 14:55:58 -08001175 // mMasterMute is in both PlaybackThread and in AudioFlinger. When a
1176 // PlaybackThread needs to find out if master-muted, it checks it's local
1177 // copy rather than the one in AudioFlinger. This optimization saves a lock.
1178 bool mMasterMute;
1179 void setMasterMute_l(bool muted) { mMasterMute = muted; }
Dean Wheatley12473e92021-03-18 23:00:55 +11001180
1181 auto discontinuityForStandbyOrFlush() const { // call on threadLoop or with lock.
1182 return ((mType == DIRECT && !audio_is_linear_pcm(mFormat))
1183 || mType == OFFLOAD)
1184 ? mTimestampVerifier.DISCONTINUITY_MODE_ZERO
1185 : mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS;
1186 }
1187
Andy Hung8d31fd22023-06-26 19:20:57 -07001188 ActiveTracks<IAfTrack> mActiveTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08001189
Eric Laurent81784c32012-11-19 14:55:58 -08001190 // Time to sleep between cycles when:
1191 virtual uint32_t activeSleepTimeUs() const; // mixer state MIXER_TRACKS_ENABLED
1192 virtual uint32_t idleSleepTimeUs() const = 0; // mixer state MIXER_IDLE
1193 virtual uint32_t suspendSleepTimeUs() const = 0; // audio policy manager suspended us
1194 // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write()
1195 // No sleep in standby mode; waits on a condition
1196
1197 // Code snippets that are temporarily lifted up out of threadLoop() until the merge
Andy Hung440901d2023-06-29 21:19:25 -07001198 virtual void checkSilentMode_l() final; // consider unification with MMapThread
Eric Laurent81784c32012-11-19 14:55:58 -08001199
1200 // Non-trivial for DUPLICATING only
1201 virtual void saveOutputTracks() { }
1202 virtual void clearOutputTracks() { }
1203
1204 // Cache various calculated values, at threadLoop() entry and after a parameter change
1205 virtual void cacheParameters_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02001206 void setCheckOutputStageEffects() override {
1207 mCheckOutputStageEffects.store(true);
1208 }
Eric Laurent81784c32012-11-19 14:55:58 -08001209
1210 virtual uint32_t correctLatency_l(uint32_t latency) const;
1211
Eric Laurent1c333e22014-05-20 10:48:17 -07001212 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
1213 audio_patch_handle_t *handle);
1214 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle);
1215
Andy Hung87c693c2023-07-06 20:56:16 -07001216 bool usesHwAvSync() const final { return mType == DIRECT && mOutput != nullptr
Phil Burk6fc2a7c2015-04-30 16:08:10 -07001217 && mHwSupportsPause
1218 && (mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC); }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08001219
Andy Hung1bc088a2018-02-09 15:57:31 -08001220 uint32_t trackCountForUid_l(uid_t uid) const;
Eric Laurentad7dd962016-09-22 12:38:37 -07001221
jiabineb3bda02020-06-30 14:07:03 -07001222 void invalidateTracksForAudioSession_l(
Andy Hung440901d2023-06-29 21:19:25 -07001223 audio_session_t sessionId) const override {
jiabineb3bda02020-06-30 14:07:03 -07001224 ThreadBase::invalidateTracksForAudioSession_l(sessionId, mTracks);
1225 }
1226
Mikhail Naganovbf493082017-04-17 17:37:12 -07001227 DISALLOW_COPY_AND_ASSIGN(PlaybackThread);
Eric Laurent81784c32012-11-19 14:55:58 -08001228
Andy Hung87c693c2023-07-06 20:56:16 -07001229 status_t addTrack_l(const sp<IAfTrack>& track) final;
1230 bool destroyTrack_l(const sp<IAfTrack>& track) final;
1231
Andy Hung8d31fd22023-06-26 19:20:57 -07001232 void removeTrack_l(const sp<IAfTrack>& track);
Eric Laurent81784c32012-11-19 14:55:58 -08001233
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001234 void readOutputParameters_l();
Vlad Popa7e81cea2023-01-19 16:34:16 +01001235 MetadataUpdate updateMetadata_l() final;
Kevin Rocardc86a7f72018-04-03 09:00:09 -07001236 virtual void sendMetadataToBackend_l(const StreamOutHalInterface::SourceMetadata& metadata);
Eric Laurent81784c32012-11-19 14:55:58 -08001237
Dean Wheatley12473e92021-03-18 23:00:55 +11001238 void collectTimestamps_l();
1239
Andy Hungc0691382018-09-12 18:01:57 -07001240 // The Tracks class manages tracks added and removed from the Thread.
Andy Hung1bc088a2018-02-09 15:57:31 -08001241 template <typename T>
1242 class Tracks {
1243 public:
Andy Hung920f6572022-10-06 12:09:49 -07001244 explicit Tracks(bool saveDeletedTrackIds) :
Andy Hungc0691382018-09-12 18:01:57 -07001245 mSaveDeletedTrackIds(saveDeletedTrackIds) { }
Andy Hung1bc088a2018-02-09 15:57:31 -08001246
1247 // SortedVector methods
Andy Hungc0691382018-09-12 18:01:57 -07001248 ssize_t add(const sp<T> &track) {
1249 const ssize_t index = mTracks.add(track);
1250 LOG_ALWAYS_FATAL_IF(index < 0, "cannot add track");
1251 return index;
1252 }
Andy Hung1bc088a2018-02-09 15:57:31 -08001253 ssize_t remove(const sp<T> &track);
1254 size_t size() const {
1255 return mTracks.size();
1256 }
1257 bool isEmpty() const {
1258 return mTracks.isEmpty();
1259 }
1260 ssize_t indexOf(const sp<T> &item) {
1261 return mTracks.indexOf(item);
1262 }
1263 sp<T> operator[](size_t index) const {
1264 return mTracks[index];
1265 }
1266 typename SortedVector<sp<T>>::iterator begin() {
1267 return mTracks.begin();
1268 }
1269 typename SortedVector<sp<T>>::iterator end() {
1270 return mTracks.end();
1271 }
1272
Andy Hung920f6572022-10-06 12:09:49 -07001273 size_t processDeletedTrackIds(const std::function<void(int)>& f) {
Andy Hungc0691382018-09-12 18:01:57 -07001274 for (const int trackId : mDeletedTrackIds) {
1275 f(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08001276 }
Andy Hungc0691382018-09-12 18:01:57 -07001277 return mDeletedTrackIds.size();
Andy Hung1bc088a2018-02-09 15:57:31 -08001278 }
1279
Andy Hungc0691382018-09-12 18:01:57 -07001280 void clearDeletedTrackIds() { mDeletedTrackIds.clear(); }
Andy Hung1bc088a2018-02-09 15:57:31 -08001281
1282 private:
Andy Hungc0691382018-09-12 18:01:57 -07001283 // Tracks pending deletion for MIXER type threads
1284 const bool mSaveDeletedTrackIds; // true to enable tracking
1285 std::set<int> mDeletedTrackIds;
Andy Hung1bc088a2018-02-09 15:57:31 -08001286
1287 SortedVector<sp<T>> mTracks; // wrapped SortedVector.
1288 };
1289
Andy Hung8d31fd22023-06-26 19:20:57 -07001290 Tracks<IAfTrack> mTracks;
Andy Hung1bc088a2018-02-09 15:57:31 -08001291
Eric Laurent223fd5c2014-11-11 13:43:36 -08001292 stream_type_t mStreamTypes[AUDIO_STREAM_CNT];
Andy Hungee58e4a2023-07-07 13:47:37 -07001293
Eric Laurent81784c32012-11-19 14:55:58 -08001294 AudioStreamOut *mOutput;
1295
1296 float mMasterVolume;
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001297 std::atomic<float> mMasterBalance{};
1298 audio_utils::Balance mBalance;
Eric Laurent81784c32012-11-19 14:55:58 -08001299 int mNumWrites;
1300 int mNumDelayedWrites;
1301 bool mInWrite;
1302
1303 // FIXME rename these former local variables of threadLoop to standard "m" names
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001304 nsecs_t mStandbyTimeNs;
Andy Hung25c2dac2014-02-27 14:56:00 -08001305 size_t mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001306
1307 // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l()
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001308 uint32_t mActiveSleepTimeUs;
1309 uint32_t mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08001310
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001311 uint32_t mSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08001312
1313 // mixer status returned by prepareTracks_l()
1314 mixer_state mMixerStatus; // current cycle
1315 // previous cycle when in prepareTracks_l()
1316 mixer_state mMixerStatusIgnoringFastTracks;
1317 // FIXME or a separate ready state per track
1318
1319 // FIXME move these declarations into the specific sub-class that needs them
1320 // MIXER only
1321 uint32_t sleepTimeShift;
1322
1323 // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001324 nsecs_t mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08001325
1326 // MIXER only
1327 nsecs_t maxPeriod;
1328
1329 // DUPLICATING only
1330 uint32_t writeFrames;
1331
Eric Laurentbfb1b832013-01-07 09:53:42 -08001332 size_t mBytesRemaining;
1333 size_t mCurrentWriteLength;
1334 bool mUseAsyncWrite;
Eric Laurent3b4529e2013-09-05 18:09:19 -07001335 // mWriteAckSequence contains current write sequence on bits 31-1. The write sequence is
1336 // incremented each time a write(), a flush() or a standby() occurs.
1337 // Bit 0 is set when a write blocks and indicates a callback is expected.
1338 // Bit 0 is reset by the async callback thread calling resetWriteBlocked(). Out of sequence
1339 // callbacks are ignored.
1340 uint32_t mWriteAckSequence;
1341 // mDrainSequence contains current drain sequence on bits 31-1. The drain sequence is
1342 // incremented each time a drain is requested or a flush() or standby() occurs.
1343 // Bit 0 is set when the drain() command is called at the HAL and indicates a callback is
1344 // expected.
1345 // Bit 0 is reset by the async callback thread calling resetDraining(). Out of sequence
1346 // callbacks are ignored.
1347 uint32_t mDrainSequence;
Andy Hungee58e4a2023-07-07 13:47:37 -07001348
Eric Laurentbfb1b832013-01-07 09:53:42 -08001349 sp<AsyncCallbackThread> mCallbackThread;
1350
jiabinf6eb4c32020-02-25 14:06:25 -08001351 Mutex mAudioTrackCbLock;
1352 // Record of IAudioTrackCallback
Andy Hung8d31fd22023-06-26 19:20:57 -07001353 std::map<sp<IAfTrack>, sp<media::IAudioTrackCallback>> mAudioTrackCallbacks;
jiabinf6eb4c32020-02-25 14:06:25 -08001354
Eric Laurent81784c32012-11-19 14:55:58 -08001355 // The HAL output sink is treated as non-blocking, but current implementation is blocking
1356 sp<NBAIO_Sink> mOutputSink;
1357 // If a fast mixer is present, the blocking pipe sink, otherwise clear
1358 sp<NBAIO_Sink> mPipeSink;
1359 // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink
1360 sp<NBAIO_Sink> mNormalSink;
Andy Hungee58e4a2023-07-07 13:47:37 -07001361
Eric Laurent81784c32012-11-19 14:55:58 -08001362 uint32_t mScreenState; // cached copy of gScreenState
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07001363 // TODO: add comment and adjust size as needed
Glenn Kasteneef598c2017-04-03 14:41:13 -07001364 static const size_t kFastMixerLogSize = 8 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -08001365 sp<NBLog::Writer> mFastMixerNBLogWriter;
Andy Hung2148bf02016-11-28 19:01:02 -08001366
Dean Wheatley30d28422018-11-06 10:27:40 +11001367 // Downstream patch latency, available if mDownstreamLatencyStatMs.getN() > 0.
1368 audio_utils::Statistics<double> mDownstreamLatencyStatMs{0.999};
Andy Hung2148bf02016-11-28 19:01:02 -08001369
Eric Laurent19952e12023-04-20 10:08:29 +02001370 // output stream start detection based on render position returned by the kernel
1371 // condition signalled when the output stream has started
1372 Condition mWaitHalStartCV;
1373 // true when the output stream render position has moved, reset to false in standby
1374 bool mHalStarted = false;
1375 // last kernel render position saved when entering standby
1376 int64_t mKernelPositionOnStandby = 0;
1377
Eric Laurent81784c32012-11-19 14:55:58 -08001378public:
Andy Hung440901d2023-06-29 21:19:25 -07001379 FastTrackUnderruns getFastTrackUnderruns(size_t /* fastIndex */) const override
1380 { return {}; }
1381 const std::atomic<int64_t>& framesWritten() const final { return mFramesWritten; }
Eric Laurent81784c32012-11-19 14:55:58 -08001382
1383protected:
1384 // accessed by both binder threads and within threadLoop(), lock on mutex needed
Andy Hung87c693c2023-07-06 20:56:16 -07001385 uint32_t& fastTrackAvailMask_l() final { return mFastTrackAvailMask; }
1386 uint32_t mFastTrackAvailMask; // bit i set if fast track [i] is available
Eric Laurentd1f69b02014-12-15 14:33:13 -08001387 bool mHwSupportsPause;
1388 bool mHwPaused;
1389 bool mFlushPending;
Eric Laurent7c29ec92017-09-20 17:54:22 -07001390 // volumes last sent to audio HAL with stream->setVolume()
1391 float mLeftVolFloat;
1392 float mRightVolFloat;
Eric Laurent74c38dc2020-12-23 18:19:44 +01001393
1394 // audio patch used by the downstream software patch.
1395 // Only used if ThreadBase::mIsMsdDevice is true.
1396 struct audio_patch mDownStreamPatch;
Eric Laurentb3f315a2021-07-13 15:09:05 +02001397
1398 std::atomic_bool mCheckOutputStageEffects{};
ziyangch8f194f12021-12-01 13:48:04 -08001399
ziyangch8f194f12021-12-01 13:48:04 -08001400
Brian Lindahl65e90012022-07-27 18:01:07 +02001401 // Provides periodic checking for timestamp advancement for underrun detection.
1402 class IsTimestampAdvancing {
1403 public:
1404 // The timestamp will not be checked any faster than the specified time.
Andy Hung920f6572022-10-06 12:09:49 -07001405 explicit IsTimestampAdvancing(nsecs_t minimumTimeBetweenChecksNs)
Brian Lindahl65e90012022-07-27 18:01:07 +02001406 : mMinimumTimeBetweenChecksNs(minimumTimeBetweenChecksNs)
1407 {
1408 clear();
1409 }
1410 // Check if the presentation position has advanced in the last periodic time.
1411 bool check(AudioStreamOut * output);
1412 // Clear the internal state when the playback state changes for the output
1413 // stream.
1414 void clear();
1415 private:
1416 // The minimum time between timestamp checks.
1417 const nsecs_t mMinimumTimeBetweenChecksNs;
1418 // Add differential check on the timestamps to see if there is a change in the
1419 // timestamp frame position between the last call to check.
1420 uint64_t mPreviousPosition;
1421 // The time at which the last check occurred, to ensure we don't check too
1422 // frequently, giving the Audio HAL enough time to update its timestamps.
1423 nsecs_t mPreviousNs;
1424 // The valued is latched so we don't check timestamps too frequently.
1425 bool mLatchedValue;
1426 };
1427 IsTimestampAdvancing mIsTimestampAdvancing;
ziyangch8f194f12021-12-01 13:48:04 -08001428
Brian Lindahl65e90012022-07-27 18:01:07 +02001429 virtual void flushHw_l() {
1430 mIsTimestampAdvancing.clear();
1431 }
Eric Laurent81784c32012-11-19 14:55:58 -08001432};
1433
Eric Laurentb0463942022-12-20 16:31:10 +01001434class MixerThread : public PlaybackThread,
1435 public StreamOutHalInterfaceLatencyModeCallback {
Eric Laurent81784c32012-11-19 14:55:58 -08001436public:
Andy Hung583043b2023-07-17 17:05:00 -07001437 MixerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08001438 AudioStreamOut* output,
1439 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001440 bool systemReady,
Eric Laurentf1f22e72021-07-13 14:04:14 +02001441 type_t type = MIXER,
1442 audio_config_base_t *mixerConfig = nullptr);
Andy Hung440901d2023-06-29 21:19:25 -07001443 ~MixerThread() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001444
Eric Laurentb0463942022-12-20 16:31:10 +01001445 // RefBase
Andy Hung440901d2023-06-29 21:19:25 -07001446 void onFirstRef() override;
Eric Laurentb0463942022-12-20 16:31:10 +01001447
1448 // StreamOutHalInterfaceLatencyModeCallback
1449 void onRecommendedLatencyModeChanged(
Andy Hung440901d2023-06-29 21:19:25 -07001450 std::vector<audio_latency_mode_t> modes) final;
Eric Laurentb0463942022-12-20 16:31:10 +01001451
Eric Laurent81784c32012-11-19 14:55:58 -08001452 // Thread virtuals
1453
Andy Hung440901d2023-06-29 21:19:25 -07001454 bool checkForNewParameter_l(const String8& keyValuePair, status_t& status) final;
Eric Laurent81784c32012-11-19 14:55:58 -08001455
Andy Hung440901d2023-06-29 21:19:25 -07001456 bool isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08001457 audio_channel_mask_t channelMask, audio_format_t format,
Andy Hung440901d2023-06-29 21:19:25 -07001458 audio_session_t sessionId, uid_t uid) const final;
Eric Laurent81784c32012-11-19 14:55:58 -08001459protected:
Andy Hung440901d2023-06-29 21:19:25 -07001460 mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove) override;
1461 uint32_t idleSleepTimeUs() const final;
1462 uint32_t suspendSleepTimeUs() const final;
1463 void cacheParameters_l() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001464
Andy Hung440901d2023-06-29 21:19:25 -07001465 void acquireWakeLock_l() final {
Andy Hungdae27702016-10-31 14:01:16 -07001466 PlaybackThread::acquireWakeLock_l();
Andy Hung818e7a32016-02-16 18:08:07 -08001467 if (hasFastMixer()) {
1468 mFastMixer->setBoottimeOffset(
1469 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME]);
1470 }
1471 }
1472
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001473 void dumpInternals_l(int fd, const Vector<String16>& args) override;
1474
Eric Laurent81784c32012-11-19 14:55:58 -08001475 // threadLoop snippets
Andy Hung440901d2023-06-29 21:19:25 -07001476 ssize_t threadLoop_write() override;
1477 void threadLoop_standby() override;
1478 void threadLoop_mix() override;
1479 void threadLoop_sleepTime() override;
1480 uint32_t correctLatency_l(uint32_t latency) const final;
Eric Laurent81784c32012-11-19 14:55:58 -08001481
Andy Hung440901d2023-06-29 21:19:25 -07001482 status_t createAudioPatch_l(
1483 const struct audio_patch* patch, audio_patch_handle_t* handle) final;
1484 status_t releaseAudioPatch_l(const audio_patch_handle_t handle) final;
Eric Laurent054d9d32015-04-24 08:48:48 -07001485
Eric Laurent81784c32012-11-19 14:55:58 -08001486 AudioMixer* mAudioMixer; // normal mixer
Eric Laurentb0463942022-12-20 16:31:10 +01001487
1488 // Support low latency mode by default as unless explicitly indicated by the audio HAL
1489 // we assume the audio path is compatible with the head tracking latency requirements
1490 std::vector<audio_latency_mode_t> mSupportedLatencyModes = {AUDIO_LATENCY_MODE_LOW};
1491 // default to invalid value to force first update to the audio HAL
1492 audio_latency_mode_t mSetLatencyMode =
1493 (audio_latency_mode_t)AUDIO_LATENCY_MODE_INVALID;
1494
1495 // Bluetooth Variable latency control logic is enabled or disabled for this thread
1496 std::atomic_bool mBluetoothLatencyModesEnabled;
1497
Eric Laurent81784c32012-11-19 14:55:58 -08001498private:
1499 // one-time initialization, no locks required
Glenn Kasten4d23ca32014-05-13 10:39:51 -07001500 sp<FastMixer> mFastMixer; // non-0 if there is also a fast mixer
Eric Laurent81784c32012-11-19 14:55:58 -08001501 sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread
1502
1503 // contents are not guaranteed to be consistent, no locks required
1504 FastMixerDumpState mFastMixerDumpState;
1505#ifdef STATE_QUEUE_DUMP
1506 StateQueueObserverDump mStateQueueObserverDump;
1507 StateQueueMutatorDump mStateQueueMutatorDump;
1508#endif
1509 AudioWatchdogDump mAudioWatchdogDump;
1510
1511 // accessible only within the threadLoop(), no locks required
1512 // mFastMixer->sq() // for mutating and pushing state
1513 int32_t mFastMixerFutex; // for cold idle
1514
Andy Hung2ddee192015-12-18 17:34:44 -08001515 std::atomic_bool mMasterMono;
Eric Laurent81784c32012-11-19 14:55:58 -08001516public:
Glenn Kasten4d23ca32014-05-13 10:39:51 -07001517 virtual bool hasFastMixer() const { return mFastMixer != 0; }
Eric Laurent81784c32012-11-19 14:55:58 -08001518 virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const {
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001519 ALOG_ASSERT(fastIndex < FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08001520 return mFastMixerDumpState.mTracks[fastIndex].mUnderruns;
1521 }
Eric Laurent83b88082014-06-20 18:31:16 -07001522
Andy Hung1c86ebe2018-05-29 20:29:08 -07001523 status_t threadloop_getHalTimestamp_l(
1524 ExtendedTimestamp *timestamp) const override {
1525 if (mNormalSink.get() != nullptr) {
1526 return mNormalSink->getTimestamp(*timestamp);
1527 }
1528 return INVALID_OPERATION;
1529 }
1530
Eric Laurentb0463942022-12-20 16:31:10 +01001531 status_t getSupportedLatencyModes(
1532 std::vector<audio_latency_mode_t>* modes) override;
1533
1534 status_t setBluetoothVariableLatencyEnabled(bool enabled) override;
1535
Andy Hung2ddee192015-12-18 17:34:44 -08001536protected:
1537 virtual void setMasterMono_l(bool mono) {
1538 mMasterMono.store(mono);
1539 if (mFastMixer != nullptr) { /* hasFastMixer() */
1540 mFastMixer->setMasterMono(mMasterMono);
1541 }
1542 }
1543 // the FastMixer performs mono blend if it exists.
Glenn Kasten03c48d52016-01-27 17:25:17 -08001544 // Blending with limiter is not idempotent,
1545 // and blending without limiter is idempotent but inefficient to do twice.
Andy Hung2ddee192015-12-18 17:34:44 -08001546 virtual bool requireMonoBlend() { return mMasterMono.load() && !hasFastMixer(); }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001547
1548 void setMasterBalance(float balance) override {
1549 mMasterBalance.store(balance);
1550 if (hasFastMixer()) {
1551 mFastMixer->setMasterBalance(balance);
1552 }
1553 }
Eric Laurentb0463942022-12-20 16:31:10 +01001554
1555 void updateHalSupportedLatencyModes_l();
1556 void onHalLatencyModesChanged_l() override;
1557 void setHalLatencyMode_l() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001558};
1559
Andy Hung87c693c2023-07-06 20:56:16 -07001560class DirectOutputThread : public PlaybackThread, public virtual IAfDirectOutputThread {
Eric Laurent81784c32012-11-19 14:55:58 -08001561public:
1562
Andy Hung87c693c2023-07-06 20:56:16 -07001563 sp<IAfDirectOutputThread> asIAfDirectOutputThread() final {
1564 return sp<IAfDirectOutputThread>::fromExisting(this);
1565 }
1566
Andy Hung583043b2023-07-17 17:05:00 -07001567 DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Gareth Fennb18c1a32022-10-05 13:42:36 -07001568 audio_io_handle_t id, bool systemReady,
1569 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07001570 : DirectOutputThread(afThreadCallback, output, id, DIRECT, systemReady, offloadInfo) { }
Andy Hung48f59ed2019-01-28 15:06:59 -08001571
Eric Laurent81784c32012-11-19 14:55:58 -08001572 virtual ~DirectOutputThread();
1573
Andy Hung87c693c2023-07-06 20:56:16 -07001574 status_t selectPresentation(int presentationId, int programId) final;
Mikhail Naganovac917ac2018-11-28 14:03:52 -08001575
Eric Laurent81784c32012-11-19 14:55:58 -08001576 // Thread virtuals
1577
Eric Laurent10351942014-05-08 18:49:52 -07001578 virtual bool checkForNewParameter_l(const String8& keyValuePair,
1579 status_t& status);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001580
ziyangch8f194f12021-12-01 13:48:04 -08001581 void flushHw_l() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001582
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001583 void setMasterBalance(float balance) override;
1584
Eric Laurent81784c32012-11-19 14:55:58 -08001585protected:
Eric Laurent81784c32012-11-19 14:55:58 -08001586 virtual uint32_t activeSleepTimeUs() const;
1587 virtual uint32_t idleSleepTimeUs() const;
1588 virtual uint32_t suspendSleepTimeUs() const;
1589 virtual void cacheParameters_l();
1590
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001591 void dumpInternals_l(int fd, const Vector<String16>& args) override;
1592
Eric Laurent81784c32012-11-19 14:55:58 -08001593 // threadLoop snippets
Andy Hung8d31fd22023-06-26 19:20:57 -07001594 virtual mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08001595 virtual void threadLoop_mix();
1596 virtual void threadLoop_sleepTime();
Eric Laurentd1f69b02014-12-15 14:33:13 -08001597 virtual void threadLoop_exit();
1598 virtual bool shouldStandby_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001599
Phil Burk43b4dcc2015-06-09 16:53:44 -07001600 virtual void onAddNewTrack_l();
1601
Gareth Fennb18c1a32022-10-05 13:42:36 -07001602 const audio_offload_info_t mOffloadInfo;
Andy Hung398ffa22022-12-13 19:19:53 -08001603
1604 audioflinger::MonotonicFrameCounter mMonotonicFrameCounter; // for VolumeShaper
Andy Hung48f59ed2019-01-28 15:06:59 -08001605 bool mVolumeShaperActive = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001606
Andy Hung583043b2023-07-17 17:05:00 -07001607 DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Gareth Fennb18c1a32022-10-05 13:42:36 -07001608 audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
1609 const audio_offload_info_t& offloadInfo);
Andy Hung8d31fd22023-06-26 19:20:57 -07001610 void processVolume_l(IAfTrack *track, bool lastTrack);
Gareth Fennb18c1a32022-10-05 13:42:36 -07001611 bool isTunerStream() const { return (mOffloadInfo.content_id > 0); }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001612
Eric Laurent81784c32012-11-19 14:55:58 -08001613 // prepareTracks_l() tells threadLoop_mix() the name of the single active track
Andy Hung8d31fd22023-06-26 19:20:57 -07001614 sp<IAfTrack> mActiveTrack;
Phil Burk43b4dcc2015-06-09 16:53:44 -07001615
Andy Hung8d31fd22023-06-26 19:20:57 -07001616 wp<IAfTrack> mPreviousTrack; // used to detect track switch
Phil Burk43b4dcc2015-06-09 16:53:44 -07001617
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001618 // This must be initialized for initial condition of mMasterBalance = 0 (disabled).
1619 float mMasterBalanceLeft = 1.f;
1620 float mMasterBalanceRight = 1.f;
1621
Eric Laurent81784c32012-11-19 14:55:58 -08001622public:
1623 virtual bool hasFastMixer() const { return false; }
Andy Hung10cbff12017-02-21 17:30:14 -08001624
1625 virtual int64_t computeWaitTimeNs_l() const override;
Andy Hungf3234512018-07-03 14:51:47 -07001626
1627 status_t threadloop_getHalTimestamp_l(ExtendedTimestamp *timestamp) const override {
1628 // For DIRECT and OFFLOAD threads, query the output sink directly.
1629 if (mOutput != nullptr) {
1630 uint64_t uposition64;
1631 struct timespec time;
1632 if (mOutput->getPresentationPosition(
1633 &uposition64, &time) == OK) {
1634 timestamp->mPosition[ExtendedTimestamp::LOCATION_KERNEL]
1635 = (int64_t)uposition64;
1636 timestamp->mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
1637 = audio_utils_ns_from_timespec(&time);
1638 return NO_ERROR;
1639 }
1640 }
1641 return INVALID_OPERATION;
1642 }
Eric Laurent81784c32012-11-19 14:55:58 -08001643};
1644
Eric Laurentbfb1b832013-01-07 09:53:42 -08001645class OffloadThread : public DirectOutputThread {
1646public:
1647
Andy Hung583043b2023-07-17 17:05:00 -07001648 OffloadThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Gareth Fennb18c1a32022-10-05 13:42:36 -07001649 audio_io_handle_t id, bool systemReady,
1650 const audio_offload_info_t& offloadInfo);
Eric Laurent6a51d7e2013-10-17 18:59:26 -07001651 virtual ~OffloadThread() {};
ziyangch8f194f12021-12-01 13:48:04 -08001652 void flushHw_l() override;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001653
1654protected:
1655 // threadLoop snippets
Andy Hung8d31fd22023-06-26 19:20:57 -07001656 virtual mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001657 virtual void threadLoop_exit();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001658
1659 virtual bool waitingAsyncCallback();
1660 virtual bool waitingAsyncCallback_l();
Haynes Mathew George05317d22016-05-03 16:34:26 -07001661 virtual void invalidateTracks(audio_stream_type_t streamType);
jiabinc44b3462022-12-08 12:52:31 -08001662 void invalidateTracks(std::set<audio_port_handle_t>& portIds) override;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001663
Eric Laurentde0613d2016-07-22 18:19:11 -07001664 virtual bool keepWakeLock() const { return (mKeepWakeLock || (mDrainSequence & 1)); }
Eric Laurent64667972016-03-30 18:19:46 -07001665
Eric Laurentbfb1b832013-01-07 09:53:42 -08001666private:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001667 size_t mPausedWriteLength; // length in bytes of write interrupted by pause
1668 size_t mPausedBytesRemaining; // bytes still waiting in mixbuffer after resume
Eric Laurent64667972016-03-30 18:19:46 -07001669 bool mKeepWakeLock; // keep wake lock while waiting for write callback
Eric Laurentbfb1b832013-01-07 09:53:42 -08001670};
1671
1672class AsyncCallbackThread : public Thread {
1673public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001674 explicit AsyncCallbackThread(const wp<PlaybackThread>& playbackThread);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001675
Eric Laurentbfb1b832013-01-07 09:53:42 -08001676 // Thread virtuals
1677 virtual bool threadLoop();
1678
1679 // RefBase
1680 virtual void onFirstRef();
1681
1682 void exit();
Eric Laurent3b4529e2013-09-05 18:09:19 -07001683 void setWriteBlocked(uint32_t sequence);
1684 void resetWriteBlocked();
1685 void setDraining(uint32_t sequence);
1686 void resetDraining();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07001687 void setAsyncError();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001688
1689private:
Eric Laurent4de95592013-09-26 15:28:21 -07001690 const wp<PlaybackThread> mPlaybackThread;
Eric Laurent3b4529e2013-09-05 18:09:19 -07001691 // mWriteAckSequence corresponds to the last write sequence passed by the offload thread via
1692 // setWriteBlocked(). The sequence is shifted one bit to the left and the lsb is used
1693 // to indicate that the callback has been received via resetWriteBlocked()
Eric Laurent4de95592013-09-26 15:28:21 -07001694 uint32_t mWriteAckSequence;
Eric Laurent3b4529e2013-09-05 18:09:19 -07001695 // mDrainSequence corresponds to the last drain sequence passed by the offload thread via
1696 // setDraining(). The sequence is shifted one bit to the left and the lsb is used
1697 // to indicate that the callback has been received via resetDraining()
Eric Laurent4de95592013-09-26 15:28:21 -07001698 uint32_t mDrainSequence;
1699 Condition mWaitWorkCV;
1700 Mutex mLock;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07001701 bool mAsyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001702};
1703
Andy Hung87c693c2023-07-06 20:56:16 -07001704class DuplicatingThread : public MixerThread, public IAfDuplicatingThread {
Eric Laurent81784c32012-11-19 14:55:58 -08001705public:
Andy Hung583043b2023-07-17 17:05:00 -07001706 DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
1707 IAfPlaybackThread* mainThread,
Eric Laurent72e3f392015-05-20 14:43:50 -07001708 audio_io_handle_t id, bool systemReady);
Andy Hung87c693c2023-07-06 20:56:16 -07001709 ~DuplicatingThread() override;
1710
1711 sp<IAfDuplicatingThread> asIAfDuplicatingThread() final {
1712 return sp<IAfDuplicatingThread>::fromExisting(this);
1713 }
Eric Laurent81784c32012-11-19 14:55:58 -08001714
1715 // Thread virtuals
Andy Hung87c693c2023-07-06 20:56:16 -07001716 void addOutputTrack(IAfPlaybackThread* thread) final;
1717 void removeOutputTrack(IAfPlaybackThread* thread) final;
1718 uint32_t waitTimeMs() const final { return mWaitTimeMs; }
Kevin Rocard069c2712018-03-29 19:09:14 -07001719
Kevin Rocardc86a7f72018-04-03 09:00:09 -07001720 void sendMetadataToBackend_l(
1721 const StreamOutHalInterface::SourceMetadata& metadata) override;
Eric Laurent81784c32012-11-19 14:55:58 -08001722protected:
1723 virtual uint32_t activeSleepTimeUs() const;
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001724 void dumpInternals_l(int fd, const Vector<String16>& args) override;
Eric Laurent81784c32012-11-19 14:55:58 -08001725
1726private:
Andy Hung920f6572022-10-06 12:09:49 -07001727 bool outputsReady();
Eric Laurent81784c32012-11-19 14:55:58 -08001728protected:
1729 // threadLoop snippets
1730 virtual void threadLoop_mix();
1731 virtual void threadLoop_sleepTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001732 virtual ssize_t threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08001733 virtual void threadLoop_standby();
1734 virtual void cacheParameters_l();
1735
1736private:
1737 // called from threadLoop, addOutputTrack, removeOutputTrack
1738 virtual void updateWaitTime_l();
1739protected:
1740 virtual void saveOutputTracks();
1741 virtual void clearOutputTracks();
1742private:
1743
1744 uint32_t mWaitTimeMs;
Andy Hung8d31fd22023-06-26 19:20:57 -07001745 SortedVector <sp<IAfOutputTrack>> outputTracks;
1746 SortedVector <sp<IAfOutputTrack>> mOutputTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08001747public:
1748 virtual bool hasFastMixer() const { return false; }
Andy Hung1c86ebe2018-05-29 20:29:08 -07001749 status_t threadloop_getHalTimestamp_l(
1750 ExtendedTimestamp *timestamp) const override {
1751 if (mOutputTracks.size() > 0) {
1752 // forward the first OutputTrack's kernel information for timestamp.
1753 const ExtendedTimestamp trackTimestamp =
1754 mOutputTracks[0]->getClientProxyTimestamp();
1755 if (trackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] > 0) {
1756 timestamp->mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
1757 trackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
1758 timestamp->mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
1759 trackTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
1760 return OK; // discard server timestamp - that's ignored.
1761 }
1762 }
1763 return INVALID_OPERATION;
1764 }
Eric Laurent81784c32012-11-19 14:55:58 -08001765};
1766
Eric Laurentb0463942022-12-20 16:31:10 +01001767class SpatializerThread : public MixerThread {
Eric Laurentb3f315a2021-07-13 15:09:05 +02001768public:
Andy Hung583043b2023-07-17 17:05:00 -07001769 SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02001770 AudioStreamOut* output,
1771 audio_io_handle_t id,
1772 bool systemReady,
1773 audio_config_base_t *mixerConfig);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001774
Andy Hung440901d2023-06-29 21:19:25 -07001775 bool hasFastMixer() const final { return false; }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001776
Eric Laurent68a40a82022-05-03 18:15:04 +02001777 // RefBase
Andy Hung440901d2023-06-29 21:19:25 -07001778 void onFirstRef() final;
Eric Laurent68a40a82022-05-03 18:15:04 +02001779
Andy Hung440901d2023-06-29 21:19:25 -07001780 status_t setRequestedLatencyMode(audio_latency_mode_t mode) final;
Eric Laurent68a40a82022-05-03 18:15:04 +02001781
Eric Laurentb3f315a2021-07-13 15:09:05 +02001782protected:
Andy Hung440901d2023-06-29 21:19:25 -07001783 void checkOutputStageEffects() final;
1784 void setHalLatencyMode_l() final;
Eric Laurentb3f315a2021-07-13 15:09:05 +02001785
1786private:
Eric Laurent68a40a82022-05-03 18:15:04 +02001787 // Do not request a specific mode by default
1788 audio_latency_mode_t mRequestedLatencyMode = AUDIO_LATENCY_MODE_FREE;
1789
Andy Hung116bc262023-06-20 18:56:17 -07001790 sp<IAfEffectHandle> mFinalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02001791};
1792
Eric Laurent81784c32012-11-19 14:55:58 -08001793// record thread
Andy Hung87c693c2023-07-06 20:56:16 -07001794class RecordThread : public IAfRecordThread, public ThreadBase
Eric Laurent81784c32012-11-19 14:55:58 -08001795{
Andy Hung8d31fd22023-06-26 19:20:57 -07001796 friend class ResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08001797public:
Andy Hung87c693c2023-07-06 20:56:16 -07001798 sp<IAfRecordThread> asIAfRecordThread() final {
1799 return sp<IAfRecordThread>::fromExisting(this);
1800 }
Eric Laurent81784c32012-11-19 14:55:58 -08001801
Andy Hung583043b2023-07-17 17:05:00 -07001802 RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08001803 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08001804 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001805 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08001806 );
Andy Hung440901d2023-06-29 21:19:25 -07001807 ~RecordThread() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001808
1809 // no addTrack_l ?
Andy Hung87c693c2023-07-06 20:56:16 -07001810 void destroyTrack_l(const sp<IAfRecordTrack>& track) final;
1811 void removeTrack_l(const sp<IAfRecordTrack>& track) final;
Eric Laurent81784c32012-11-19 14:55:58 -08001812
Eric Laurent81784c32012-11-19 14:55:58 -08001813 // Thread virtuals
Andy Hung440901d2023-06-29 21:19:25 -07001814 bool threadLoop() final;
1815 void preExit() final;
Eric Laurent81784c32012-11-19 14:55:58 -08001816
1817 // RefBase
Andy Hung440901d2023-06-29 21:19:25 -07001818 void onFirstRef() final;
Eric Laurent81784c32012-11-19 14:55:58 -08001819
Andy Hung440901d2023-06-29 21:19:25 -07001820 status_t initCheck() const final { return mInput == nullptr ? NO_INIT : NO_ERROR; }
Glenn Kastene198c362013-08-13 09:13:36 -07001821
Andy Hung440901d2023-06-29 21:19:25 -07001822 sp<MemoryDealer> readOnlyHeap() const final { return mReadOnlyHeap; }
Glenn Kastenb880f5e2014-05-07 08:43:45 -07001823
Andy Hung440901d2023-06-29 21:19:25 -07001824 sp<IMemory> pipeMemory() const final { return mPipeMemory; }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001825
Andy Hung87c693c2023-07-06 20:56:16 -07001826 sp<IAfRecordTrack> createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001827 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001828 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001829 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001830 audio_format_t format,
1831 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001832 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08001833 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001834 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07001835 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00001836 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07001837 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001838 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001839 status_t *status /*non-NULL*/,
Eric Laurentec376dc2021-04-08 20:41:22 +02001840 audio_port_handle_t portId,
Andy Hung87c693c2023-07-06 20:56:16 -07001841 int32_t maxSharedAudioHistoryMs) final;
Eric Laurent81784c32012-11-19 14:55:58 -08001842
Andy Hung8d31fd22023-06-26 19:20:57 -07001843 status_t start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08001844 AudioSystem::sync_event_t event,
Andy Hung87c693c2023-07-06 20:56:16 -07001845 audio_session_t triggerSession) final;
Eric Laurent81784c32012-11-19 14:55:58 -08001846
1847 // ask the thread to stop the specified track, and
1848 // return true if the caller should then do it's part of the stopping process
Andy Hung87c693c2023-07-06 20:56:16 -07001849 bool stop(IAfRecordTrack* recordTrack) final;
1850 AudioStreamIn* getInput() const final { return mInput; }
1851 AudioStreamIn* clearInput() final;
Eric Laurent81784c32012-11-19 14:55:58 -08001852
Andy Hung99b1ba62023-07-14 11:00:08 -07001853 // TODO(b/291317898) Unify with IAfThreadBase
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001854 virtual sp<StreamHalInterface> stream() const;
Eric Laurent81784c32012-11-19 14:55:58 -08001855
Eric Laurent81784c32012-11-19 14:55:58 -08001856
Eric Laurent10351942014-05-08 18:49:52 -07001857 virtual bool checkForNewParameter_l(const String8& keyValuePair,
1858 status_t& status);
1859 virtual void cacheParameters_l() {}
Eric Laurent81784c32012-11-19 14:55:58 -08001860 virtual String8 getParameters(const String8& keys);
Andy Hung87c693c2023-07-06 20:56:16 -07001861 void ioConfigChanged(audio_io_config_event_t event, pid_t pid = 0,
1862 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final;
Eric Laurent1c333e22014-05-20 10:48:17 -07001863 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
1864 audio_patch_handle_t *handle);
1865 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle);
jiabinc52b1ff2019-10-31 17:20:42 -07001866 void updateOutDevices(const DeviceDescriptorBaseVector& outDevices) override;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02001867 void resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs) override;
Eric Laurent83b88082014-06-20 18:31:16 -07001868
Andy Hung87c693c2023-07-06 20:56:16 -07001869 void addPatchTrack(const sp<IAfPatchRecord>& record) final;
1870 void deletePatchTrack(const sp<IAfPatchRecord>& record) final;
Eric Laurent83b88082014-06-20 18:31:16 -07001871
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001872 void readInputParameters_l();
Andy Hung87c693c2023-07-06 20:56:16 -07001873 uint32_t getInputFramesLost() const final;
Eric Laurent81784c32012-11-19 14:55:58 -08001874
Andy Hung116bc262023-06-20 18:56:17 -07001875 virtual status_t addEffectChain_l(const sp<IAfEffectChain>& chain);
1876 virtual size_t removeEffectChain_l(const sp<IAfEffectChain>& chain);
Andy Hungc3d62f92019-03-14 13:38:51 -07001877 uint32_t hasAudioSession_l(audio_session_t sessionId) const override {
1878 return ThreadBase::hasAudioSession_l(sessionId, mTracks);
1879 }
Eric Laurent81784c32012-11-19 14:55:58 -08001880
1881 // Return the set of unique session IDs across all tracks.
1882 // The keys are the session IDs, and the associated values are meaningless.
1883 // FIXME replace by Set [and implement Bag/Multiset for other uses].
Glenn Kastend848eb42016-03-08 13:42:11 -08001884 KeyedVector<audio_session_t, bool> sessionIds() const;
Eric Laurent81784c32012-11-19 14:55:58 -08001885
Andy Hung068e08e2023-05-15 19:02:55 -07001886 status_t setSyncEvent(const sp<audioflinger::SyncEvent>& event) override;
1887 bool isValidSyncEvent(const sp<audioflinger::SyncEvent>& event) const override;
Eric Laurent81784c32012-11-19 14:55:58 -08001888
Andy Hung068e08e2023-05-15 19:02:55 -07001889 static void syncStartEventCallback(const wp<audioflinger::SyncEvent>& event);
Eric Laurent81784c32012-11-19 14:55:58 -08001890
Glenn Kasten9b58f632013-07-16 11:37:48 -07001891 virtual size_t frameCount() const { return mFrameCount; }
Andy Hung87c693c2023-07-06 20:56:16 -07001892 bool hasFastCapture() const final { return mFastCapture != 0; }
Mikhail Naganovdc769682018-05-04 15:34:08 -07001893 virtual void toAudioPortConfig(struct audio_port_config *config);
Glenn Kasten9b58f632013-07-16 11:37:48 -07001894
Eric Laurent4c415062016-06-17 16:14:16 -07001895 virtual status_t checkEffectCompatibility_l(const effect_descriptor_t *desc,
1896 audio_session_t sessionId);
1897
Andy Hungdae27702016-10-31 14:01:16 -07001898 virtual void acquireWakeLock_l() {
1899 ThreadBase::acquireWakeLock_l();
1900 mActiveTracks.updatePowerState(this, true /* force */);
1901 }
1902
Andy Hung87c693c2023-07-06 20:56:16 -07001903 void checkBtNrec() final;
Eric Laurentd8365c52017-07-16 15:27:05 -07001904
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001905 // Sets the UID records silence
Andy Hung87c693c2023-07-06 20:56:16 -07001906 void setRecordSilenced(audio_port_handle_t portId, bool silenced) final;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001907
Andy Hung87c693c2023-07-06 20:56:16 -07001908 status_t getActiveMicrophones(
1909 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const final;
1910 status_t setPreferredMicrophoneDirection(audio_microphone_direction_t direction) final;
1911 status_t setPreferredMicrophoneFieldDimension(float zoom) final;
Paul McLean03a6e6a2018-12-04 10:54:13 -07001912
Vlad Popa7e81cea2023-01-19 16:34:16 +01001913 MetadataUpdate updateMetadata_l() override;
Kevin Rocard069c2712018-03-29 19:09:14 -07001914
Andy Hung87c693c2023-07-06 20:56:16 -07001915 bool fastTrackAvailable() const final { return mFastTrackAvail; }
1916 void setFastTrackAvailable(bool available) final { mFastTrackAvail = available; }
jiabin01c8f562018-07-19 17:47:28 -07001917
Andy Hungc8fddf32018-08-08 18:32:37 -07001918 bool isTimestampCorrectionEnabled() const override {
1919 // checks popcount for exactly one device.
Atneya Nair497fff12022-01-18 16:23:04 -05001920 // Is currently disabled. Before enabling,
1921 // verify compressed record timestamps.
jiabinc52b1ff2019-10-31 17:20:42 -07001922 return audio_is_input_device(mTimestampCorrectedDevice)
1923 && inDeviceType() == mTimestampCorrectedDevice;
Andy Hungc8fddf32018-08-08 18:32:37 -07001924 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001925
Andy Hung87c693c2023-07-06 20:56:16 -07001926 status_t shareAudioHistory(const std::string& sharedAudioPackageName,
Eric Laurentec376dc2021-04-08 20:41:22 +02001927 audio_session_t sharedSessionId = AUDIO_SESSION_NONE,
Andy Hung87c693c2023-07-06 20:56:16 -07001928 int64_t sharedAudioStartMs = -1) final;
Eric Laurentec376dc2021-04-08 20:41:22 +02001929 status_t shareAudioHistory_l(const std::string& sharedAudioPackageName,
1930 audio_session_t sharedSessionId = AUDIO_SESSION_NONE,
1931 int64_t sharedAudioStartMs = -1);
Andy Hung87c693c2023-07-06 20:56:16 -07001932 void resetAudioHistory_l() final;
Eric Laurentec376dc2021-04-08 20:41:22 +02001933
Andy Hung440901d2023-06-29 21:19:25 -07001934 bool isStreamInitialized() const final {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001935 return !(mInput == nullptr || mInput->stream == nullptr);
1936 }
1937
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001938protected:
1939 void dumpInternals_l(int fd, const Vector<String16>& args) override;
1940 void dumpTracks_l(int fd, const Vector<String16>& args) override;
1941
Eric Laurent81784c32012-11-19 14:55:58 -08001942private:
Eric Laurent81784c32012-11-19 14:55:58 -08001943 // Enter standby if not already in standby, and set mStandby flag
Glenn Kasten93e471f2013-08-19 08:40:07 -07001944 void standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08001945
1946 // Call the HAL standby method unconditionally, and don't change mStandby flag
Glenn Kastene198c362013-08-13 09:13:36 -07001947 void inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08001948
Eric Laurentd8365c52017-07-16 15:27:05 -07001949 void checkBtNrec_l();
1950
Eric Laurentec376dc2021-04-08 20:41:22 +02001951 int32_t getOldestFront_l();
1952 void updateFronts_l(int32_t offset);
1953
Eric Laurent81784c32012-11-19 14:55:58 -08001954 AudioStreamIn *mInput;
Mikhail Naganov2534b382019-09-25 13:05:02 -07001955 Source *mSource;
Andy Hung8d31fd22023-06-26 19:20:57 -07001956 SortedVector <sp<IAfRecordTrack>> mTracks;
Glenn Kasten2b806402013-11-20 16:37:38 -08001957 // mActiveTracks has dual roles: it indicates the current active track(s), and
Eric Laurent81784c32012-11-19 14:55:58 -08001958 // is used together with mStartStopCond to indicate start()/stop() progress
Andy Hung8d31fd22023-06-26 19:20:57 -07001959 ActiveTracks<IAfRecordTrack> mActiveTracks;
Andy Hungdae27702016-10-31 14:01:16 -07001960
Eric Laurent81784c32012-11-19 14:55:58 -08001961 Condition mStartStopCond;
Glenn Kasten9b58f632013-07-16 11:37:48 -07001962
Glenn Kasten85948432013-08-19 12:09:05 -07001963 // resampler converts input at HAL Hz to output at AudioRecord client Hz
Glenn Kasten1b291842016-07-18 14:55:21 -07001964 void *mRsmpInBuffer; // size = mRsmpInFramesOA
Glenn Kasten85948432013-08-19 12:09:05 -07001965 size_t mRsmpInFrames; // size of resampler input in frames
1966 size_t mRsmpInFramesP2;// size rounded up to a power-of-2
Glenn Kasten1b291842016-07-18 14:55:21 -07001967 size_t mRsmpInFramesOA;// mRsmpInFramesP2 + over-allocation
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001968
1969 // rolling index that is never cleared
Glenn Kasten85948432013-08-19 12:09:05 -07001970 int32_t mRsmpInRear; // last filled frame + 1
Glenn Kasten85948432013-08-19 12:09:05 -07001971
Eric Laurent81784c32012-11-19 14:55:58 -08001972 // For dumpsys
Glenn Kastenb880f5e2014-05-07 08:43:45 -07001973 const sp<MemoryDealer> mReadOnlyHeap;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001974
1975 // one-time initialization, no locks required
Glenn Kastenb187de12014-12-30 08:18:15 -08001976 sp<FastCapture> mFastCapture; // non-0 if there is also
1977 // a fast capture
Eric Laurent72e3f392015-05-20 14:43:50 -07001978
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001979 // FIXME audio watchdog thread
1980
1981 // contents are not guaranteed to be consistent, no locks required
1982 FastCaptureDumpState mFastCaptureDumpState;
1983#ifdef STATE_QUEUE_DUMP
1984 // FIXME StateQueue observer and mutator dump fields
1985#endif
1986 // FIXME audio watchdog dump
1987
1988 // accessible only within the threadLoop(), no locks required
1989 // mFastCapture->sq() // for mutating and pushing state
1990 int32_t mFastCaptureFutex; // for cold idle
1991
1992 // The HAL input source is treated as non-blocking,
1993 // but current implementation is blocking
1994 sp<NBAIO_Source> mInputSource;
1995 // The source for the normal capture thread to read from: mInputSource or mPipeSource
1996 sp<NBAIO_Source> mNormalSource;
1997 // If a fast capture is present, the non-blocking pipe sink written to by fast capture,
1998 // otherwise clear
1999 sp<NBAIO_Sink> mPipeSink;
2000 // If a fast capture is present, the non-blocking pipe source read by normal thread,
2001 // otherwise clear
2002 sp<NBAIO_Source> mPipeSource;
2003 // Depth of pipe from fast capture to normal thread and fast clients, always power of 2
2004 size_t mPipeFramesP2;
2005 // If a fast capture is present, the Pipe as IMemory, otherwise clear
2006 sp<IMemory> mPipeMemory;
2007
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002008 // TODO: add comment and adjust size as needed
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07002009 static const size_t kFastCaptureLogSize = 4 * 1024;
2010 sp<NBLog::Writer> mFastCaptureNBLogWriter;
2011
2012 bool mFastTrackAvail; // true if fast track available
Eric Laurentd8365c52017-07-16 15:27:05 -07002013 // common state to all record threads
2014 std::atomic_bool mBtNrecSuspended;
Andy Hung6427e442018-08-09 12:51:02 -07002015
2016 int64_t mFramesRead = 0; // continuous running counter.
jiabinc52b1ff2019-10-31 17:20:42 -07002017
2018 DeviceDescriptorBaseVector mOutDevices;
Eric Laurentec376dc2021-04-08 20:41:22 +02002019
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02002020 int32_t mMaxSharedAudioHistoryMs = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02002021 std::string mSharedAudioPackageName = {};
Eric Laurent2407ce32021-04-26 14:56:03 +02002022 int32_t mSharedAudioStartFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02002023 audio_session_t mSharedAudioSessionId = AUDIO_SESSION_NONE;
Eric Laurent81784c32012-11-19 14:55:58 -08002024};
Eric Laurent6acd1d42017-01-04 14:23:29 -08002025
Andy Hung7aa7d102023-07-07 15:58:48 -07002026class MmapThread : public ThreadBase, public virtual IAfMmapThread
Eric Laurent6acd1d42017-01-04 14:23:29 -08002027{
2028 public:
Andy Hung583043b2023-07-17 17:05:00 -07002029 MmapThread(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -07002030 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady,
Andy Hungcf10d742020-04-28 15:38:24 -07002031 bool isOut);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002032
Andy Hung7aa7d102023-07-07 15:58:48 -07002033 void configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08002034 audio_stream_type_t streamType,
2035 audio_session_t sessionId,
2036 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07002037 audio_port_handle_t deviceId,
Andy Hung7aa7d102023-07-07 15:58:48 -07002038 audio_port_handle_t portId) override;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002039
Andy Hung7aa7d102023-07-07 15:58:48 -07002040 void disconnect() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002041
Andy Hung440901d2023-06-29 21:19:25 -07002042 // MmapStreamInterface for adapter.
Andy Hung7aa7d102023-07-07 15:58:48 -07002043 status_t createMmapBuffer(int32_t minSizeFrames, struct audio_mmap_buffer_info* info) final;
2044 status_t getMmapPosition(struct audio_mmap_position* position) const override;
2045 status_t start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07002046 const audio_attributes_t *attr,
Andy Hung7aa7d102023-07-07 15:58:48 -07002047 audio_port_handle_t* handle) final;
2048 status_t stop(audio_port_handle_t handle) final;
2049 status_t standby() final;
2050 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) const = 0;
2051 status_t reportData(const void* buffer, size_t frameCount) override;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002052
2053 // RefBase
Andy Hung440901d2023-06-29 21:19:25 -07002054 void onFirstRef() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002055
2056 // Thread virtuals
Andy Hung440901d2023-06-29 21:19:25 -07002057 bool threadLoop() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002058
Andy Hung440901d2023-06-29 21:19:25 -07002059 // Not in ThreadBase
2060 virtual void threadLoop_exit() final;
2061 virtual void threadLoop_standby() final;
2062 virtual bool shouldStandby_l() final { return false; }
2063 virtual status_t exitStandby_l() REQUIRES(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002064
Andy Hung440901d2023-06-29 21:19:25 -07002065 status_t initCheck() const final { return mHalStream == nullptr ? NO_INIT : NO_ERROR; }
2066 size_t frameCount() const final { return mFrameCount; }
2067 bool checkForNewParameter_l(const String8& keyValuePair, status_t& status) final;
2068 String8 getParameters(const String8& keys) final;
2069 void ioConfigChanged(audio_io_config_event_t event, pid_t pid = 0,
2070 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002071 void readHalParameters_l();
Andy Hung440901d2023-06-29 21:19:25 -07002072 void cacheParameters_l() final {}
2073 status_t createAudioPatch_l(
2074 const struct audio_patch* patch, audio_patch_handle_t* handle) final;
2075 status_t releaseAudioPatch_l(const audio_patch_handle_t handle) final;
2076 void toAudioPortConfig(struct audio_port_config* config) override;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002077
Andy Hung440901d2023-06-29 21:19:25 -07002078 sp<StreamHalInterface> stream() const final { return mHalStream; }
2079 status_t addEffectChain_l(const sp<IAfEffectChain>& chain) final;
2080 size_t removeEffectChain_l(const sp<IAfEffectChain>& chain) final;
2081 status_t checkEffectCompatibility_l(
2082 const effect_descriptor_t *desc, audio_session_t sessionId) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002083
Andy Hung440901d2023-06-29 21:19:25 -07002084 uint32_t hasAudioSession_l(audio_session_t sessionId) const override {
Andy Hungc3d62f92019-03-14 13:38:51 -07002085 // Note: using mActiveTracks as no mTracks here.
2086 return ThreadBase::hasAudioSession_l(sessionId, mActiveTracks);
2087 }
Andy Hung440901d2023-06-29 21:19:25 -07002088 status_t setSyncEvent(const sp<audioflinger::SyncEvent>& event) final;
2089 bool isValidSyncEvent(const sp<audioflinger::SyncEvent>& event) const final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002090
Andy Hung440901d2023-06-29 21:19:25 -07002091 virtual void checkSilentMode_l() {} // cannot be const (RecordThread)
2092 virtual void processVolume_l() {}
Eric Laurent6acd1d42017-01-04 14:23:29 -08002093 void checkInvalidTracks_l();
2094
Andy Hung440901d2023-06-29 21:19:25 -07002095 // Not in ThreadBase
2096 virtual audio_stream_type_t streamType() const { return AUDIO_STREAM_DEFAULT; }
2097 virtual void invalidateTracks(audio_stream_type_t /* streamType */) {}
Andy Hung7aa7d102023-07-07 15:58:48 -07002098 void invalidateTracks(std::set<audio_port_handle_t>& /* portIds */) override {}
Eric Laurent6acd1d42017-01-04 14:23:29 -08002099
Eric Laurent331679c2018-04-16 17:03:16 -07002100 // Sets the UID records silence
Andy Hung7aa7d102023-07-07 15:58:48 -07002101 void setRecordSilenced(
2102 audio_port_handle_t /* portId */, bool /* silenced */) override {}
Eric Laurent331679c2018-04-16 17:03:16 -07002103
Andy Hung440901d2023-06-29 21:19:25 -07002104 bool isStreamInitialized() const override { return false; }
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002105
jiabin09609032022-06-15 19:26:01 +00002106 void setClientSilencedState_l(audio_port_handle_t portId, bool silenced) {
2107 mClientSilencedStates[portId] = silenced;
2108 }
2109
2110 size_t eraseClientSilencedState_l(audio_port_handle_t portId) {
2111 return mClientSilencedStates.erase(portId);
2112 }
2113
2114 bool isClientSilenced_l(audio_port_handle_t portId) const {
2115 const auto it = mClientSilencedStates.find(portId);
2116 return it != mClientSilencedStates.end() ? it->second : false;
2117 }
2118
2119 void setClientSilencedIfExists_l(audio_port_handle_t portId, bool silenced) {
2120 const auto it = mClientSilencedStates.find(portId);
2121 if (it != mClientSilencedStates.end()) {
2122 it->second = silenced;
2123 }
2124 }
2125
Eric Laurent6acd1d42017-01-04 14:23:29 -08002126 protected:
Andy Hung440901d2023-06-29 21:19:25 -07002127 void dumpInternals_l(int fd, const Vector<String16>& args) override;
2128 void dumpTracks_l(int fd, const Vector<String16>& args) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002129
jiabinc52b1ff2019-10-31 17:20:42 -07002130 /**
2131 * @brief mDeviceId current device port unique identifier
2132 */
2133 audio_port_handle_t mDeviceId = AUDIO_PORT_HANDLE_NONE;
2134
Eric Laurent6acd1d42017-01-04 14:23:29 -08002135 audio_attributes_t mAttr;
2136 audio_session_t mSessionId;
2137 audio_port_handle_t mPortId;
2138
Phil Burk7f6b40d2017-02-09 13:18:38 -08002139 wp<MmapStreamCallback> mCallback;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002140 sp<StreamHalInterface> mHalStream;
2141 sp<DeviceHalInterface> mHalDevice;
2142 AudioHwDevice* const mAudioHwDev;
Andy Hung8d31fd22023-06-26 19:20:57 -07002143 ActiveTracks<IAfMmapTrack> mActiveTracks;
Eric Laurent67f97292018-04-20 18:05:41 -07002144 float mHalVolFloat;
jiabin09609032022-06-15 19:26:01 +00002145 std::map<audio_port_handle_t, bool> mClientSilencedStates;
Eric Laurent331679c2018-04-16 17:03:16 -07002146
2147 int32_t mNoCallbackWarningCount;
2148 static constexpr int32_t kMaxNoCallbackWarnings = 5;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002149};
2150
Andy Hung7aa7d102023-07-07 15:58:48 -07002151class MmapPlaybackThread : public MmapThread, public IAfMmapPlaybackThread,
2152 public virtual VolumeInterface {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002153public:
Andy Hung583043b2023-07-17 17:05:00 -07002154 MmapPlaybackThread(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07002155 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002156
Andy Hung7aa7d102023-07-07 15:58:48 -07002157 sp<IAfMmapPlaybackThread> asIAfMmapPlaybackThread() final {
2158 return sp<IAfMmapPlaybackThread>::fromExisting(this);
2159 }
2160
Andy Hung440901d2023-06-29 21:19:25 -07002161 void configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08002162 audio_stream_type_t streamType,
2163 audio_session_t sessionId,
2164 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07002165 audio_port_handle_t deviceId,
Andy Hung440901d2023-06-29 21:19:25 -07002166 audio_port_handle_t portId) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002167
Andy Hung7aa7d102023-07-07 15:58:48 -07002168 AudioStreamOut* clearOutput() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002169
2170 // VolumeInterface
Andy Hung440901d2023-06-29 21:19:25 -07002171 void setMasterVolume(float value) final;
2172 void setMasterBalance(float /* value */) final {} // Needs implementation?
2173 void setMasterMute(bool muted) final;
2174 void setStreamVolume(audio_stream_type_t stream, float value) final;
2175 void setStreamMute(audio_stream_type_t stream, bool muted) final;
2176 float streamVolume(audio_stream_type_t stream) const final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002177
2178 void setMasterMute_l(bool muted) { mMasterMute = muted; }
2179
Andy Hung440901d2023-06-29 21:19:25 -07002180 void invalidateTracks(audio_stream_type_t streamType) final;
2181 void invalidateTracks(std::set<audio_port_handle_t>& portIds) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002182
Andy Hung440901d2023-06-29 21:19:25 -07002183 audio_stream_type_t streamType() const final { return mStreamType; }
2184 void checkSilentMode_l() final;
2185 void processVolume_l() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002186
Andy Hung440901d2023-06-29 21:19:25 -07002187 MetadataUpdate updateMetadata_l() final;
Kevin Rocard069c2712018-03-29 19:09:14 -07002188
Andy Hung440901d2023-06-29 21:19:25 -07002189 void toAudioPortConfig(struct audio_port_config* config) final;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07002190
Andy Hung440901d2023-06-29 21:19:25 -07002191 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) const final;
jiabinb7d8c5a2020-08-26 17:24:52 -07002192
Andy Hung440901d2023-06-29 21:19:25 -07002193 bool isStreamInitialized() const final {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002194 return !(mOutput == nullptr || mOutput->stream == nullptr);
2195 }
2196
Andy Hung440901d2023-06-29 21:19:25 -07002197 status_t reportData(const void* buffer, size_t frameCount) final;
jiabinfc791ee2023-02-15 19:43:40 +00002198
Andy Hung440901d2023-06-29 21:19:25 -07002199 void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) final;
2200 void stopMelComputation_l() final;
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002201
Eric Laurent6acd1d42017-01-04 14:23:29 -08002202protected:
Andy Hung440901d2023-06-29 21:19:25 -07002203 void dumpInternals_l(int fd, const Vector<String16>& args) final;
Eric Laurent1f9b5e62023-07-03 18:14:07 +02002204 float streamVolume_l() const {
2205 return mStreamTypes[mStreamType].volume;
2206 }
2207 bool streamMuted_l() const {
2208 return mStreamTypes[mStreamType].mute;
2209 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002210
Eric Laurent1f9b5e62023-07-03 18:14:07 +02002211 stream_type_t mStreamTypes[AUDIO_STREAM_CNT];
Eric Laurent6acd1d42017-01-04 14:23:29 -08002212 audio_stream_type_t mStreamType;
2213 float mMasterVolume;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002214 bool mMasterMute;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002215 AudioStreamOut* mOutput;
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002216
2217 mediautils::atomic_sp<audio_utils::MelProcessor> mMelProcessor;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002218};
2219
Andy Hung7aa7d102023-07-07 15:58:48 -07002220class MmapCaptureThread : public MmapThread, public IAfMmapCaptureThread
Eric Laurent6acd1d42017-01-04 14:23:29 -08002221{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002222public:
Andy Hung583043b2023-07-17 17:05:00 -07002223 MmapCaptureThread(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07002224 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002225
Andy Hung7aa7d102023-07-07 15:58:48 -07002226 sp<IAfMmapCaptureThread> asIAfMmapCaptureThread() final {
2227 return sp<IAfMmapCaptureThread>::fromExisting(this);
2228 }
2229
2230 AudioStreamIn* clearInput() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002231
Andy Hung440901d2023-06-29 21:19:25 -07002232 status_t exitStandby_l() REQUIRES(mLock) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002233
Andy Hung440901d2023-06-29 21:19:25 -07002234 MetadataUpdate updateMetadata_l() final;
2235 void processVolume_l() final;
2236 void setRecordSilenced(audio_port_handle_t portId, bool silenced) final;
Kevin Rocard069c2712018-03-29 19:09:14 -07002237
Andy Hung440901d2023-06-29 21:19:25 -07002238 void toAudioPortConfig(struct audio_port_config* config) final;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07002239
Andy Hung440901d2023-06-29 21:19:25 -07002240 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) const final;
jiabinb7d8c5a2020-08-26 17:24:52 -07002241
Andy Hung440901d2023-06-29 21:19:25 -07002242 bool isStreamInitialized() const final {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002243 return !(mInput == nullptr || mInput->stream == nullptr);
2244 }
2245
Eric Laurent6acd1d42017-01-04 14:23:29 -08002246protected:
2247
2248 AudioStreamIn* mInput;
2249};
jiabinc658e452022-10-21 20:52:21 +00002250
2251class BitPerfectThread : public MixerThread {
2252public:
Andy Hung583043b2023-07-17 17:05:00 -07002253 BitPerfectThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut *output,
jiabinc658e452022-10-21 20:52:21 +00002254 audio_io_handle_t id, bool systemReady);
2255
2256protected:
Andy Hung440901d2023-06-29 21:19:25 -07002257 mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove) final;
2258 void threadLoop_mix() final;
jiabinc658e452022-10-21 20:52:21 +00002259
2260private:
2261 bool mIsBitPerfect;
jiabin76d94692022-12-15 21:51:21 +00002262 float mVolumeLeft = 0.f;
2263 float mVolumeRight = 0.f;
jiabinc658e452022-10-21 20:52:21 +00002264};
Andy Hunga5a7fc92023-06-23 19:27:19 -07002265
Andy Hungee58e4a2023-07-07 13:47:37 -07002266} // namespace android