blob: eba8a40cefdfce1936c4f0e01ba195f9a93a5d80 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
Andy Hung4b17e882023-07-07 13:47:37 -070018#pragma once
Eric Laurent81784c32012-11-19 14:55:58 -080019
Andy Hung4b17e882023-07-07 13:47:37 -070020namespace android {
Andy Hung3e4c8742023-06-29 21:19:25 -070021
22class AsyncCallbackThread;
23
24class ThreadBase : public virtual IAfThreadBase, public Thread {
Andy Hung11e74242023-06-26 19:20:57 -070025 // TODO(b/288339104) remove friends
26 friend class RecordTrack;
27 friend class Track;
28 friend class TrackBase;
Eric Laurent81784c32012-11-19 14:55:58 -080029public:
Glenn Kasten97b7b752014-09-28 13:04:24 -070030 static const char *threadTypeToString(type_t type);
31
Andy Hung0c1e11e2023-07-06 20:56:16 -070032 AudioFlinger* audioFlinger() const final { return mAudioFlinger.get(); }
33
Eric Laurent81784c32012-11-19 14:55:58 -080034 ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -070035 type_t type, bool systemReady, bool isOut);
Andy Hung3e4c8742023-06-29 21:19:25 -070036 ~ThreadBase() override;
Eric Laurent81784c32012-11-19 14:55:58 -080037
Andy Hung3e4c8742023-06-29 21:19:25 -070038 status_t readyToRun() final;
39 void clearPowerManager() final;
Eric Laurent81784c32012-11-19 14:55:58 -080040
41 // base for record and playback
42 enum {
43 CFG_EVENT_IO,
Eric Laurent10351942014-05-08 18:49:52 -070044 CFG_EVENT_PRIO,
45 CFG_EVENT_SET_PARAMETER,
Eric Laurent1c333e22014-05-20 10:48:17 -070046 CFG_EVENT_CREATE_AUDIO_PATCH,
47 CFG_EVENT_RELEASE_AUDIO_PATCH,
jiabinc52b1ff2019-10-31 17:20:42 -070048 CFG_EVENT_UPDATE_OUT_DEVICE,
Eric Laurentb3f315a2021-07-13 15:09:05 +020049 CFG_EVENT_RESIZE_BUFFER,
Eric Laurent68a40a82022-05-03 18:15:04 +020050 CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS,
51 CFG_EVENT_HAL_LATENCY_MODES_CHANGED,
Eric Laurent81784c32012-11-19 14:55:58 -080052 };
53
Eric Laurent10351942014-05-08 18:49:52 -070054 class ConfigEventData: public RefBase {
Eric Laurent81784c32012-11-19 14:55:58 -080055 public:
Eric Laurent10351942014-05-08 18:49:52 -070056 virtual ~ConfigEventData() {}
Eric Laurent81784c32012-11-19 14:55:58 -080057
58 virtual void dump(char *buffer, size_t size) = 0;
Eric Laurent10351942014-05-08 18:49:52 -070059 protected:
60 ConfigEventData() {}
Eric Laurent81784c32012-11-19 14:55:58 -080061 };
62
Eric Laurent10351942014-05-08 18:49:52 -070063 // Config event sequence by client if status needed (e.g binder thread calling setParameters()):
64 // 1. create SetParameterConfigEvent. This sets mWaitStatus in config event
65 // 2. Lock mLock
66 // 3. Call sendConfigEvent_l(): Append to mConfigEvents and mWaitWorkCV.signal
67 // 4. sendConfigEvent_l() reads status from event->mStatus;
68 // 5. sendConfigEvent_l() returns status
69 // 6. Unlock
70 //
71 // Parameter sequence by server: threadLoop calling processConfigEvents_l():
72 // 1. Lock mLock
73 // 2. If there is an entry in mConfigEvents proceed ...
74 // 3. Read first entry in mConfigEvents
75 // 4. Remove first entry from mConfigEvents
76 // 5. Process
77 // 6. Set event->mStatus
78 // 7. event->mCond.signal
79 // 8. Unlock
Eric Laurent81784c32012-11-19 14:55:58 -080080
Eric Laurent10351942014-05-08 18:49:52 -070081 class ConfigEvent: public RefBase {
82 public:
Eric Laurentb3f315a2021-07-13 15:09:05 +020083 void dump(char *buffer, size_t size) {
84 snprintf(buffer, size, "Event type: %d\n", mType);
85 if (mData != nullptr) {
86 snprintf(buffer, size, "Data:\n");
87 mData->dump(buffer, size);
88 }
89 }
Eric Laurent10351942014-05-08 18:49:52 -070090
91 const int mType; // event type e.g. CFG_EVENT_IO
92 Mutex mLock; // mutex associated with mCond
93 Condition mCond; // condition for status return
94 status_t mStatus; // status communicated to sender
95 bool mWaitStatus; // true if sender is waiting for status
Eric Laurent72e3f392015-05-20 14:43:50 -070096 bool mRequiresSystemReady; // true if must wait for system ready to enter event queue
Eric Laurent10351942014-05-08 18:49:52 -070097 sp<ConfigEventData> mData; // event specific parameter data
98
99 protected:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700100 explicit ConfigEvent(int type, bool requiresSystemReady = false) :
Eric Laurent72e3f392015-05-20 14:43:50 -0700101 mType(type), mStatus(NO_ERROR), mWaitStatus(false),
102 mRequiresSystemReady(requiresSystemReady), mData(NULL) {}
Eric Laurent10351942014-05-08 18:49:52 -0700103 };
104
105 class IoConfigEventData : public ConfigEventData {
106 public:
Mikhail Naganov88536df2021-07-26 17:30:29 -0700107 IoConfigEventData(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700108 audio_port_handle_t portId) :
109 mEvent(event), mPid(pid), mPortId(portId) {}
Eric Laurent81784c32012-11-19 14:55:58 -0800110
111 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200112 snprintf(buffer, size, "- IO event: event %d\n", mEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800113 }
114
Mikhail Naganov88536df2021-07-26 17:30:29 -0700115 const audio_io_config_event_t mEvent;
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700116 const pid_t mPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -0700117 const audio_port_handle_t mPortId;
Eric Laurent81784c32012-11-19 14:55:58 -0800118 };
119
Eric Laurent10351942014-05-08 18:49:52 -0700120 class IoConfigEvent : public ConfigEvent {
Eric Laurent81784c32012-11-19 14:55:58 -0800121 public:
Mikhail Naganov88536df2021-07-26 17:30:29 -0700122 IoConfigEvent(audio_io_config_event_t event, pid_t pid, audio_port_handle_t portId) :
Eric Laurent10351942014-05-08 18:49:52 -0700123 ConfigEvent(CFG_EVENT_IO) {
Eric Laurent09f1ed22019-04-24 17:45:17 -0700124 mData = new IoConfigEventData(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700125 }
Eric Laurent10351942014-05-08 18:49:52 -0700126 };
Eric Laurent81784c32012-11-19 14:55:58 -0800127
Eric Laurent10351942014-05-08 18:49:52 -0700128 class PrioConfigEventData : public ConfigEventData {
129 public:
Mikhail Naganov83f04272017-02-07 10:45:09 -0800130 PrioConfigEventData(pid_t pid, pid_t tid, int32_t prio, bool forApp) :
131 mPid(pid), mTid(tid), mPrio(prio), mForApp(forApp) {}
Eric Laurent81784c32012-11-19 14:55:58 -0800132
133 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200134 snprintf(buffer, size, "- Prio event: pid %d, tid %d, prio %d, for app? %d\n",
Mikhail Naganov83f04272017-02-07 10:45:09 -0800135 mPid, mTid, mPrio, mForApp);
Eric Laurent81784c32012-11-19 14:55:58 -0800136 }
137
Eric Laurent81784c32012-11-19 14:55:58 -0800138 const pid_t mPid;
139 const pid_t mTid;
140 const int32_t mPrio;
Mikhail Naganov83f04272017-02-07 10:45:09 -0800141 const bool mForApp;
Eric Laurent81784c32012-11-19 14:55:58 -0800142 };
143
Eric Laurent10351942014-05-08 18:49:52 -0700144 class PrioConfigEvent : public ConfigEvent {
145 public:
Mikhail Naganov83f04272017-02-07 10:45:09 -0800146 PrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp) :
Eric Laurent72e3f392015-05-20 14:43:50 -0700147 ConfigEvent(CFG_EVENT_PRIO, true) {
Mikhail Naganov83f04272017-02-07 10:45:09 -0800148 mData = new PrioConfigEventData(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700149 }
Eric Laurent10351942014-05-08 18:49:52 -0700150 };
151
152 class SetParameterConfigEventData : public ConfigEventData {
153 public:
Andy Hung920f6572022-10-06 12:09:49 -0700154 explicit SetParameterConfigEventData(const String8& keyValuePairs) :
Eric Laurent10351942014-05-08 18:49:52 -0700155 mKeyValuePairs(keyValuePairs) {}
156
157 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200158 snprintf(buffer, size, "- KeyValue: %s\n", mKeyValuePairs.string());
Eric Laurent10351942014-05-08 18:49:52 -0700159 }
160
161 const String8 mKeyValuePairs;
162 };
163
164 class SetParameterConfigEvent : public ConfigEvent {
165 public:
Andy Hung920f6572022-10-06 12:09:49 -0700166 explicit SetParameterConfigEvent(const String8& keyValuePairs) :
Eric Laurent10351942014-05-08 18:49:52 -0700167 ConfigEvent(CFG_EVENT_SET_PARAMETER) {
168 mData = new SetParameterConfigEventData(keyValuePairs);
169 mWaitStatus = true;
170 }
Eric Laurent10351942014-05-08 18:49:52 -0700171 };
172
Eric Laurent1c333e22014-05-20 10:48:17 -0700173 class CreateAudioPatchConfigEventData : public ConfigEventData {
174 public:
175 CreateAudioPatchConfigEventData(const struct audio_patch patch,
176 audio_patch_handle_t handle) :
177 mPatch(patch), mHandle(handle) {}
178
179 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200180 snprintf(buffer, size, "- Patch handle: %u\n", mHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -0700181 }
182
183 const struct audio_patch mPatch;
184 audio_patch_handle_t mHandle;
185 };
186
187 class CreateAudioPatchConfigEvent : public ConfigEvent {
188 public:
189 CreateAudioPatchConfigEvent(const struct audio_patch patch,
190 audio_patch_handle_t handle) :
191 ConfigEvent(CFG_EVENT_CREATE_AUDIO_PATCH) {
192 mData = new CreateAudioPatchConfigEventData(patch, handle);
193 mWaitStatus = true;
194 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700195 };
196
197 class ReleaseAudioPatchConfigEventData : public ConfigEventData {
198 public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700199 explicit ReleaseAudioPatchConfigEventData(const audio_patch_handle_t handle) :
Eric Laurent1c333e22014-05-20 10:48:17 -0700200 mHandle(handle) {}
201
202 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200203 snprintf(buffer, size, "- Patch handle: %u\n", mHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -0700204 }
205
206 audio_patch_handle_t mHandle;
207 };
208
209 class ReleaseAudioPatchConfigEvent : public ConfigEvent {
210 public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700211 explicit ReleaseAudioPatchConfigEvent(const audio_patch_handle_t handle) :
Eric Laurent1c333e22014-05-20 10:48:17 -0700212 ConfigEvent(CFG_EVENT_RELEASE_AUDIO_PATCH) {
213 mData = new ReleaseAudioPatchConfigEventData(handle);
214 mWaitStatus = true;
215 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700216 };
Eric Laurent81784c32012-11-19 14:55:58 -0800217
jiabinc52b1ff2019-10-31 17:20:42 -0700218 class UpdateOutDevicesConfigEventData : public ConfigEventData {
219 public:
220 explicit UpdateOutDevicesConfigEventData(const DeviceDescriptorBaseVector& outDevices) :
221 mOutDevices(outDevices) {}
222
223 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200224 snprintf(buffer, size, "- Devices: %s", android::toString(mOutDevices).c_str());
jiabinc52b1ff2019-10-31 17:20:42 -0700225 }
226
227 DeviceDescriptorBaseVector mOutDevices;
228 };
229
230 class UpdateOutDevicesConfigEvent : public ConfigEvent {
231 public:
232 explicit UpdateOutDevicesConfigEvent(const DeviceDescriptorBaseVector& outDevices) :
233 ConfigEvent(CFG_EVENT_UPDATE_OUT_DEVICE) {
234 mData = new UpdateOutDevicesConfigEventData(outDevices);
235 }
jiabinc52b1ff2019-10-31 17:20:42 -0700236 };
237
Eric Laurentec376dc2021-04-08 20:41:22 +0200238 class ResizeBufferConfigEventData : public ConfigEventData {
239 public:
240 explicit ResizeBufferConfigEventData(int32_t maxSharedAudioHistoryMs) :
241 mMaxSharedAudioHistoryMs(maxSharedAudioHistoryMs) {}
242
243 virtual void dump(char *buffer, size_t size) {
Eric Laurentb3f315a2021-07-13 15:09:05 +0200244 snprintf(buffer, size, "- mMaxSharedAudioHistoryMs: %d", mMaxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +0200245 }
246
247 int32_t mMaxSharedAudioHistoryMs;
248 };
249
250 class ResizeBufferConfigEvent : public ConfigEvent {
251 public:
252 explicit ResizeBufferConfigEvent(int32_t maxSharedAudioHistoryMs) :
253 ConfigEvent(CFG_EVENT_RESIZE_BUFFER) {
254 mData = new ResizeBufferConfigEventData(maxSharedAudioHistoryMs);
255 }
Eric Laurentec376dc2021-04-08 20:41:22 +0200256 };
257
Eric Laurentb3f315a2021-07-13 15:09:05 +0200258 class CheckOutputStageEffectsEvent : public ConfigEvent {
259 public:
260 CheckOutputStageEffectsEvent() :
261 ConfigEvent(CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS) {
262 }
Eric Laurentb3f315a2021-07-13 15:09:05 +0200263 };
264
Eric Laurent68a40a82022-05-03 18:15:04 +0200265 class HalLatencyModesChangedEvent : public ConfigEvent {
266 public:
267 HalLatencyModesChangedEvent() :
268 ConfigEvent(CFG_EVENT_HAL_LATENCY_MODES_CHANGED) {
269 }
Eric Laurent68a40a82022-05-03 18:15:04 +0200270 };
271
Eric Laurentb3f315a2021-07-13 15:09:05 +0200272
Eric Laurent81784c32012-11-19 14:55:58 -0800273 class PMDeathRecipient : public IBinder::DeathRecipient {
274 public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700275 explicit PMDeathRecipient(const wp<ThreadBase>& thread) : mThread(thread) {}
Eric Laurent81784c32012-11-19 14:55:58 -0800276 virtual ~PMDeathRecipient() {}
277
278 // IBinder::DeathRecipient
279 virtual void binderDied(const wp<IBinder>& who);
280
281 private:
Mikhail Naganovbf493082017-04-17 17:37:12 -0700282 DISALLOW_COPY_AND_ASSIGN(PMDeathRecipient);
Eric Laurent81784c32012-11-19 14:55:58 -0800283
284 wp<ThreadBase> mThread;
285 };
286
Andy Hung3e4c8742023-06-29 21:19:25 -0700287 type_t type() const final { return mType; }
288 bool isDuplicating() const final { return (mType == DUPLICATING); }
289 audio_io_handle_t id() const final { return mId;}
Eric Laurent81784c32012-11-19 14:55:58 -0800290
Andy Hung3e4c8742023-06-29 21:19:25 -0700291 uint32_t sampleRate() const final { return mSampleRate; }
292 audio_channel_mask_t channelMask() const final { return mChannelMask; }
293 audio_channel_mask_t mixerChannelMask() const override { return mChannelMask; }
294 audio_format_t format() const final { return mHALFormat; }
295 uint32_t channelCount() const final { return mChannelCount; }
296 audio_channel_mask_t hapticChannelMask() const override { return AUDIO_CHANNEL_NONE; }
Andy Hung0c1e11e2023-07-06 20:56:16 -0700297 uint32_t hapticChannelCount() const override { return 0; }
Andy Hung3e4c8742023-06-29 21:19:25 -0700298 uint32_t latency_l() const override { return 0; }
299 void setVolumeForOutput_l(float /* left */, float /* right */) const override {}
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700300
301 // Return's the HAL's frame count i.e. fast mixer buffer size.
Andy Hung3e4c8742023-06-29 21:19:25 -0700302 size_t frameCountHAL() const final { return mFrameCount; }
303 size_t frameSize() const final { return mFrameSize; }
Eric Laurent81784c32012-11-19 14:55:58 -0800304
305 // Should be "virtual status_t requestExitAndWait()" and override same
306 // method in Thread, but Thread::requestExitAndWait() is not yet virtual.
Andy Hung3e4c8742023-06-29 21:19:25 -0700307 void exit() final;
308 status_t setParameters(const String8& keyValuePairs) final;
309
Eric Laurent10351942014-05-08 18:49:52 -0700310 // sendConfigEvent_l() must be called with ThreadBase::mLock held
311 // Can temporarily release the lock if waiting for a reply from
312 // processConfigEvents_l().
Andy Hung3e4c8742023-06-29 21:19:25 -0700313 status_t sendConfigEvent_l(sp<ConfigEvent>& event);
314 void sendIoConfigEvent(audio_io_config_event_t event, pid_t pid = 0,
315 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final;
316 void sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid = 0,
317 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final;
318 void sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp) final;
319 void sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio, bool forApp) final;
320 status_t sendSetParameterConfigEvent_l(const String8& keyValuePair) final;
321 status_t sendCreateAudioPatchConfigEvent(const struct audio_patch* patch,
322 audio_patch_handle_t* handle) final;
323 status_t sendReleaseAudioPatchConfigEvent(audio_patch_handle_t handle) final;
324 status_t sendUpdateOutDeviceConfigEvent(
325 const DeviceDescriptorBaseVector& outDevices) final;
326 void sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs) final;
327 void sendCheckOutputStageEffectsEvent() final;
328 void sendCheckOutputStageEffectsEvent_l() final;
329 void sendHalLatencyModesChangedEvent_l() final;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200330
Andy Hung3e4c8742023-06-29 21:19:25 -0700331 void processConfigEvents_l() final;
332 void setCheckOutputStageEffects() override {}
333 void updateOutDevices(const DeviceDescriptorBaseVector& outDevices) override;
334 void toAudioPortConfig(struct audio_port_config* config) override;
335 void resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs) override;
Eric Laurent1c333e22014-05-20 10:48:17 -0700336
Andy Hung3e4c8742023-06-29 21:19:25 -0700337 // see note at declaration of mStandby, mOutDevice and mInDevice
338 bool inStandby() const override { return mStandby; }
339 const DeviceTypeSet outDeviceTypes() const final {
340 return getAudioDeviceTypes(mOutDeviceTypeAddrs);
341 }
342 audio_devices_t inDeviceType() const final { return mInDeviceTypeAddr.mType; }
343 DeviceTypeSet getDeviceTypes() const final {
344 return isOutput() ? outDeviceTypes() : DeviceTypeSet({inDeviceType()});
345 }
Eric Laurent81784c32012-11-19 14:55:58 -0800346
Andy Hung3e4c8742023-06-29 21:19:25 -0700347 const AudioDeviceTypeAddrVector& outDeviceTypeAddrs() const final {
348 return mOutDeviceTypeAddrs;
349 }
350 const AudioDeviceTypeAddr& inDeviceTypeAddr() const final {
351 return mInDeviceTypeAddr;
352 }
Andy Hung293558a2017-03-21 12:19:20 -0700353
Andy Hung3e4c8742023-06-29 21:19:25 -0700354 bool isOutput() const final { return mIsOut; }
jiabin8f278ee2019-11-11 12:16:27 -0800355
Andy Hung3e4c8742023-06-29 21:19:25 -0700356 bool isOffloadOrMmap() const final {
357 switch (mType) {
358 case OFFLOAD:
359 case MMAP_PLAYBACK:
360 case MMAP_CAPTURE:
361 return true;
362 default:
363 return false;
364 }
365 }
Eric Laurent81784c32012-11-19 14:55:58 -0800366
Andy Hung3e4c8742023-06-29 21:19:25 -0700367 sp<IAfEffectHandle> createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -0700368 const sp<Client>& client,
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700369 const sp<media::IEffectClient>& effectClient,
Eric Laurent81784c32012-11-19 14:55:58 -0800370 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -0800371 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800372 effect_descriptor_t *desc,
373 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -0800374 status_t *status /*non-NULL*/,
Eric Laurent2fe0acd2020-03-13 14:30:46 -0700375 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +0200376 bool probe,
Andy Hung3e4c8742023-06-29 21:19:25 -0700377 bool notifyFramesProcessed) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800378
379 // return values for hasAudioSession (bit field)
380 enum effect_state {
381 EFFECT_SESSION = 0x1, // the audio session corresponds to at least one
382 // effect
Eric Laurent4c415062016-06-17 16:14:16 -0700383 TRACK_SESSION = 0x2, // the audio session corresponds to at least one
Eric Laurent81784c32012-11-19 14:55:58 -0800384 // track
Eric Laurentb62d0362021-10-26 17:40:18 +0200385 FAST_SESSION = 0x4, // the audio session corresponds to at least one
Eric Laurent4c415062016-06-17 16:14:16 -0700386 // fast track
jiabinc658e452022-10-21 20:52:21 +0000387 SPATIALIZED_SESSION = 0x8, // the audio session corresponds to at least one
388 // spatialized track
389 BIT_PERFECT_SESSION = 0x10 // the audio session corresponds to at least one
390 // bit-perfect track
Eric Laurent81784c32012-11-19 14:55:58 -0800391 };
392
Andy Hung3e4c8742023-06-29 21:19:25 -0700393 // get effect chain corresponding to session Id.
394 sp<IAfEffectChain> getEffectChain(audio_session_t sessionId) const final;
395 // same as getEffectChain() but must be called with ThreadBase mutex locked
396 sp<IAfEffectChain> getEffectChain_l(audio_session_t sessionId) const final;
397 std::vector<int> getEffectIds_l(audio_session_t sessionId) const final;
398
Eric Laurent81784c32012-11-19 14:55:58 -0800399 // lock all effect chains Mutexes. Must be called before releasing the
400 // ThreadBase mutex before processing the mixer and effects. This guarantees the
401 // integrity of the chains during the process.
402 // Also sets the parameter 'effectChains' to current value of mEffectChains.
Andy Hung3e4c8742023-06-29 21:19:25 -0700403 void lockEffectChains_l(Vector<sp<IAfEffectChain>>& effectChains) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800404 // unlock effect chains after process
Andy Hung3e4c8742023-06-29 21:19:25 -0700405 void unlockEffectChains(const Vector<sp<IAfEffectChain>>& effectChains) final;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800406 // get a copy of mEffectChains vector
Andy Hung3e4c8742023-06-29 21:19:25 -0700407 Vector<sp<IAfEffectChain>> getEffectChains_l() const final { return mEffectChains; };
Eric Laurent81784c32012-11-19 14:55:58 -0800408 // set audio mode to all effect chains
Andy Hung3e4c8742023-06-29 21:19:25 -0700409 void setMode(audio_mode_t mode) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800410 // get effect module with corresponding ID on specified audio session
Andy Hung3e4c8742023-06-29 21:19:25 -0700411 sp<IAfEffectModule> getEffect(audio_session_t sessionId, int effectId) const final;
412 sp<IAfEffectModule> getEffect_l(audio_session_t sessionId, int effectId) const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800413 // add and effect module. Also creates the effect chain is none exists for
Eric Laurent6c796322019-04-09 14:13:17 -0700414 // the effects audio session. Only called in a context of moving an effect
415 // from one thread to another
Andy Hung3e4c8742023-06-29 21:19:25 -0700416 status_t addEffect_l(const sp<IAfEffectModule>& effect) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800417 // remove and effect module. Also removes the effect chain is this was the last
418 // effect
Andy Hung3e4c8742023-06-29 21:19:25 -0700419 void removeEffect_l(const sp<IAfEffectModule>& effect, bool release = false) final;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -0800420 // disconnect an effect handle from module and destroy module if last handle
Andy Hung3e4c8742023-06-29 21:19:25 -0700421 void disconnectEffectHandle(IAfEffectHandle* handle, bool unpinIfLast) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800422 // detach all tracks connected to an auxiliary effect
Andy Hung3e4c8742023-06-29 21:19:25 -0700423 void detachAuxEffect_l(int /* effectId */) override {}
424 // TODO(b/288339104) - remove hasAudioSession_l below.
425 uint32_t hasAudioSession_l(audio_session_t sessionId) const override = 0;
426 uint32_t hasAudioSession(audio_session_t sessionId) const final {
Eric Laurent4c415062016-06-17 16:14:16 -0700427 Mutex::Autolock _l(mLock);
428 return hasAudioSession_l(sessionId);
429 }
430
Andy Hungc3d62f92019-03-14 13:38:51 -0700431 template <typename T>
432 uint32_t hasAudioSession_l(audio_session_t sessionId, const T& tracks) const {
433 uint32_t result = 0;
434 if (getEffectChain_l(sessionId) != 0) {
435 result = EFFECT_SESSION;
436 }
437 for (size_t i = 0; i < tracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -0700438 const sp<IAfTrackBase>& track = tracks[i];
Andy Hungc3d62f92019-03-14 13:38:51 -0700439 if (sessionId == track->sessionId()
440 && !track->isInvalid() // not yet removed from tracks.
441 && !track->isTerminated()) {
442 result |= TRACK_SESSION;
443 if (track->isFastTrack()) {
444 result |= FAST_SESSION; // caution, only represents first track.
445 }
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200446 if (track->isSpatialized()) {
Eric Laurentb62d0362021-10-26 17:40:18 +0200447 result |= SPATIALIZED_SESSION; // caution, only first track.
448 }
jiabinc658e452022-10-21 20:52:21 +0000449 if (track->isBitPerfect()) {
450 result |= BIT_PERFECT_SESSION;
451 }
Andy Hungc3d62f92019-03-14 13:38:51 -0700452 break;
453 }
454 }
455 return result;
456 }
457
Eric Laurent81784c32012-11-19 14:55:58 -0800458 // the value returned by default implementation is not important as the
459 // strategy is only meaningful for PlaybackThread which implements this method
Andy Hung3e4c8742023-06-29 21:19:25 -0700460 product_strategy_t getStrategyForSession_l(
461 audio_session_t /* sessionId */) const override {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800462 return static_cast<product_strategy_t>(0);
463 }
Eric Laurent81784c32012-11-19 14:55:58 -0800464
Eric Laurent81784c32012-11-19 14:55:58 -0800465 // check if some effects must be suspended/restored when an effect is enabled
466 // or disabled
Andy Hung3e4c8742023-06-29 21:19:25 -0700467 void checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -0800468 audio_session_t sessionId,
Andy Hung3e4c8742023-06-29 21:19:25 -0700469 bool threadLocked) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800470
Eric Laurent81784c32012-11-19 14:55:58 -0800471
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700472 // Return a reference to a per-thread heap which can be used to allocate IMemory
473 // objects that will be read-only to client processes, read/write to mediaserver,
474 // and shared by all client processes of the thread.
475 // The heap is per-thread rather than common across all threads, because
476 // clients can't be trusted not to modify the offset of the IMemory they receive.
477 // If a thread does not have such a heap, this method returns 0.
Andy Hung3e4c8742023-06-29 21:19:25 -0700478 sp<MemoryDealer> readOnlyHeap() const override { return nullptr; }
Eric Laurent81784c32012-11-19 14:55:58 -0800479
Andy Hung3e4c8742023-06-29 21:19:25 -0700480 sp<IMemory> pipeMemory() const override { return nullptr; }
Glenn Kasten6181ffd2014-05-13 10:41:52 -0700481
Andy Hung3e4c8742023-06-29 21:19:25 -0700482 void systemReady() final;
Eric Laurent72e3f392015-05-20 14:43:50 -0700483
Andy Hung3e4c8742023-06-29 21:19:25 -0700484 void broadcast_l() final;
Eric Laurent4c415062016-06-17 16:14:16 -0700485
Andy Hung3e4c8742023-06-29 21:19:25 -0700486 bool isTimestampCorrectionEnabled() const override { return false; }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800487
Andy Hung3e4c8742023-06-29 21:19:25 -0700488 bool isMsdDevice() const final { return mIsMsdDevice; }
Andy Hungc8fddf32018-08-08 18:32:37 -0700489
Andy Hung3e4c8742023-06-29 21:19:25 -0700490 void dump(int fd, const Vector<String16>& args) override;
Andy Hungdc099c22018-09-18 13:46:39 -0700491
Andy Hungd0979812019-02-21 15:51:44 -0800492 // deliver stats to mediametrics.
Andy Hung3e4c8742023-06-29 21:19:25 -0700493 void sendStatistics(bool force) final;
Andy Hungd0979812019-02-21 15:51:44 -0800494
Andy Hung3e4c8742023-06-29 21:19:25 -0700495 Mutex& mutex() const final {
496 return mLock;
497 }
Eric Laurent81784c32012-11-19 14:55:58 -0800498 mutable Mutex mLock;
499
Andy Hung3e4c8742023-06-29 21:19:25 -0700500 void onEffectEnable(const sp<IAfEffectModule>& effect) final;
501 void onEffectDisable() final;
Eric Laurent6b446ce2019-12-13 10:56:31 -0800502
jiabineb3bda02020-06-30 14:07:03 -0700503 // invalidateTracksForAudioSession_l must be called with holding mLock.
Andy Hung3e4c8742023-06-29 21:19:25 -0700504 void invalidateTracksForAudioSession_l(audio_session_t /* sessionId */) const override {}
jiabineb3bda02020-06-30 14:07:03 -0700505 // Invalidate all the tracks with the given audio session.
Andy Hung3e4c8742023-06-29 21:19:25 -0700506 void invalidateTracksForAudioSession(audio_session_t sessionId) const final {
jiabineb3bda02020-06-30 14:07:03 -0700507 Mutex::Autolock _l(mLock);
508 invalidateTracksForAudioSession_l(sessionId);
509 }
510
511 template <typename T>
512 void invalidateTracksForAudioSession_l(audio_session_t sessionId,
513 const T& tracks) const {
514 for (size_t i = 0; i < tracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -0700515 const sp<IAfTrackBase>& track = tracks[i];
jiabineb3bda02020-06-30 14:07:03 -0700516 if (sessionId == track->sessionId()) {
517 track->invalidate();
518 }
519 }
520 }
521
Andy Hung3e4c8742023-06-29 21:19:25 -0700522 void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) override;
523 void stopMelComputation_l() override;
Vlad Popa6fbbfbf2023-02-22 15:05:43 +0100524
Eric Laurent81784c32012-11-19 14:55:58 -0800525protected:
526
527 // entry describing an effect being suspended in mSuspendedSessions keyed vector
528 class SuspendedSessionDesc : public RefBase {
529 public:
530 SuspendedSessionDesc() : mRefCount(0) {}
531
532 int mRefCount; // number of active suspend requests
533 effect_uuid_t mType; // effect type UUID
534 };
535
Andy Hungdae27702016-10-31 14:01:16 -0700536 void acquireWakeLock();
537 virtual void acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800538 void releaseWakeLock();
539 void releaseWakeLock_l();
Andy Hungd01b0f12016-11-07 16:10:30 -0800540 void updateWakeLockUids_l(const SortedVector<uid_t> &uids);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800541 void getPowerManager_l();
Eric Laurentd8365c52017-07-16 15:27:05 -0700542 // suspend or restore effects of the specified type (or all if type is NULL)
543 // on a given session. The number of suspend requests is counted and restore
544 // occurs when all suspend requests are cancelled.
Eric Laurent81784c32012-11-19 14:55:58 -0800545 void setEffectSuspended_l(const effect_uuid_t *type,
546 bool suspend,
Andy Hung0c1e11e2023-07-06 20:56:16 -0700547 audio_session_t sessionId) final;
Eric Laurentd8365c52017-07-16 15:27:05 -0700548 // updated mSuspendedSessions when an effect is suspended or restored
Eric Laurent81784c32012-11-19 14:55:58 -0800549 void updateSuspendedSessions_l(const effect_uuid_t *type,
550 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -0800551 audio_session_t sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800552 // check if some effects must be suspended when an effect chain is added
Andy Hung116bc262023-06-20 18:56:17 -0700553 void checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain);
Eric Laurent81784c32012-11-19 14:55:58 -0800554
Kevin Rocard069c2712018-03-29 19:09:14 -0700555 // sends the metadata of the active tracks to the HAL
Vlad Popa7e81cea2023-01-19 16:34:16 +0100556 struct MetadataUpdate {
557 std::vector<playback_track_metadata_v7_t> playbackMetadataUpdate;
558 std::vector<record_track_metadata_v7_t> recordMetadataUpdate;
559 };
560 virtual MetadataUpdate updateMetadata_l() = 0;
Kevin Rocard069c2712018-03-29 19:09:14 -0700561
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100562 String16 getWakeLockTag();
563
Eric Laurent81784c32012-11-19 14:55:58 -0800564 virtual void preExit() { }
Andy Hung2ddee192015-12-18 17:34:44 -0800565 virtual void setMasterMono_l(bool mono __unused) { }
566 virtual bool requireMonoBlend() { return false; }
Eric Laurent81784c32012-11-19 14:55:58 -0800567
Andy Hung1c86ebe2018-05-29 20:29:08 -0700568 // called within the threadLoop to obtain timestamp from the HAL.
569 virtual status_t threadloop_getHalTimestamp_l(
570 ExtendedTimestamp *timestamp __unused) const {
571 return INVALID_OPERATION;
572 }
Andy Hung116bc262023-06-20 18:56:17 -0700573public:
574// TODO(b/288339104) organize with publics
Eric Laurentd66d7a12021-07-13 13:35:32 +0200575 product_strategy_t getStrategyForStream(audio_stream_type_t stream) const;
Andy Hung116bc262023-06-20 18:56:17 -0700576protected:
Eric Laurentd66d7a12021-07-13 13:35:32 +0200577
Eric Laurentb0463942022-12-20 16:31:10 +0100578 virtual void onHalLatencyModesChanged_l() {}
579
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700580 virtual void dumpInternals_l(int fd __unused, const Vector<String16>& args __unused)
581 { }
582 virtual void dumpTracks_l(int fd __unused, const Vector<String16>& args __unused) { }
583
584
Vlad Popae8d99472022-06-30 16:02:48 +0200585 friend class AudioFlinger; // for mEffectChains and mAudioManager
Eric Laurent81784c32012-11-19 14:55:58 -0800586
587 const type_t mType;
588
589 // Used by parameters, config events, addTrack_l, exit
590 Condition mWaitWorkCV;
591
592 const sp<AudioFlinger> mAudioFlinger;
Andy Hungcf10d742020-04-28 15:38:24 -0700593 ThreadMetrics mThreadMetrics;
594 const bool mIsOut;
Glenn Kasten9b58f632013-07-16 11:37:48 -0700595
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800596 // updated by PlaybackThread::readOutputParameters_l() or
597 // RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800598 uint32_t mSampleRate;
599 size_t mFrameCount; // output HAL, direct output, record
Eric Laurent81784c32012-11-19 14:55:58 -0800600 audio_channel_mask_t mChannelMask;
Glenn Kastenf6ed4232013-07-16 11:16:27 -0700601 uint32_t mChannelCount;
Eric Laurent81784c32012-11-19 14:55:58 -0800602 size_t mFrameSize;
Glenn Kasten97b7b752014-09-28 13:04:24 -0700603 // not HAL frame size, this is for output sink (to pipe to fast mixer)
Andy Hung463be252014-07-10 16:56:07 -0700604 audio_format_t mFormat; // Source format for Recording and
605 // Sink format for Playback.
606 // Sink format may be different than
607 // HAL format if Fastmixer is used.
608 audio_format_t mHALFormat;
Glenn Kasten70949c42013-08-06 07:40:12 -0700609 size_t mBufferSize; // HAL buffer size for read() or write()
jiabinc52b1ff2019-10-31 17:20:42 -0700610 AudioDeviceTypeAddrVector mOutDeviceTypeAddrs; // output device types and addresses
611 AudioDeviceTypeAddr mInDeviceTypeAddr; // input device type and address
Eric Laurent10351942014-05-08 18:49:52 -0700612 Vector< sp<ConfigEvent> > mConfigEvents;
Eric Laurent72e3f392015-05-20 14:43:50 -0700613 Vector< sp<ConfigEvent> > mPendingConfigEvents; // events awaiting system ready
Eric Laurent81784c32012-11-19 14:55:58 -0800614
615 // These fields are written and read by thread itself without lock or barrier,
jiabinc52b1ff2019-10-31 17:20:42 -0700616 // and read by other threads without lock or barrier via standby(), outDeviceTypes()
617 // and inDeviceType().
Eric Laurent81784c32012-11-19 14:55:58 -0800618 // Because of the absence of a lock or barrier, any other thread that reads
619 // these fields must use the information in isolation, or be prepared to deal
620 // with possibility that it might be inconsistent with other information.
Glenn Kasten4944acb2013-08-19 08:39:20 -0700621 bool mStandby; // Whether thread is currently in standby.
jiabinc52b1ff2019-10-31 17:20:42 -0700622
Eric Laurent296fb132015-05-01 11:38:42 -0700623 struct audio_patch mPatch;
jiabinc52b1ff2019-10-31 17:20:42 -0700624
Glenn Kastenf59497b2015-01-26 16:35:47 -0800625 audio_source_t mAudioSource;
Eric Laurent81784c32012-11-19 14:55:58 -0800626
627 const audio_io_handle_t mId;
Andy Hung116bc262023-06-20 18:56:17 -0700628 Vector<sp<IAfEffectChain>> mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -0800629
Glenn Kastend7dca052015-03-05 16:05:54 -0800630 static const int kThreadNameLength = 16; // prctl(PR_SET_NAME) limit
631 char mThreadName[kThreadNameLength]; // guaranteed NUL-terminated
Chris Ye6597d732020-02-28 22:38:25 -0800632 sp<os::IPowerManager> mPowerManager;
Eric Laurent81784c32012-11-19 14:55:58 -0800633 sp<IBinder> mWakeLockToken;
634 const sp<PMDeathRecipient> mDeathRecipient;
Glenn Kastend848eb42016-03-08 13:42:11 -0800635 // list of suspended effects per session and per type. The first (outer) vector is
636 // keyed by session ID, the second (inner) by type UUID timeLow field
Eric Laurentd8365c52017-07-16 15:27:05 -0700637 // Updated by updateSuspendedSessions_l() only.
Glenn Kastend848eb42016-03-08 13:42:11 -0800638 KeyedVector< audio_session_t, KeyedVector< int, sp<SuspendedSessionDesc> > >
Eric Laurent81784c32012-11-19 14:55:58 -0800639 mSuspendedSessions;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -0700640 // TODO: add comment and adjust size as needed
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800641 static const size_t kLogSize = 4 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -0800642 sp<NBLog::Writer> mNBLogWriter;
Eric Laurent72e3f392015-05-20 14:43:50 -0700643 bool mSystemReady;
Andy Hung818e7a32016-02-16 18:08:07 -0800644 ExtendedTimestamp mTimestamp;
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700645 TimestampVerifier< // For timestamp statistics.
646 int64_t /* frame count */, int64_t /* time ns */> mTimestampVerifier;
Dean Wheatley12473e92021-03-18 23:00:55 +1100647 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush
648 // TODO: add confirmation checks:
649 // 1) DIRECT threads and linear PCM format really resets to 0?
650 // 2) Is frame count really valid if not linear pcm?
651 // 3) Are all 64 bits of position returned, not just lowest 32 bits?
jiabinc52b1ff2019-10-31 17:20:42 -0700652 // Timestamp corrected device should be a single device.
653 audio_devices_t mTimestampCorrectedDevice = AUDIO_DEVICE_NONE;
Andy Hung446f4df2019-02-21 12:26:41 -0800654
655 // ThreadLoop statistics per iteration.
656 int64_t mLastIoBeginNs = -1;
657 int64_t mLastIoEndNs = -1;
658
Andy Hung44d648b2022-04-08 17:33:40 -0700659 // ThreadSnapshot is thread-safe (internally locked)
660 mediautils::ThreadSnapshot mThreadSnapshot;
661
Andy Hung446f4df2019-02-21 12:26:41 -0800662 // This should be read under ThreadBase lock (if not on the threadLoop thread).
663 audio_utils::Statistics<double> mIoJitterMs{0.995 /* alpha */};
664 audio_utils::Statistics<double> mProcessTimeMs{0.995 /* alpha */};
Andy Hunge6c37112019-02-26 17:38:10 -0800665 audio_utils::Statistics<double> mLatencyMs{0.995 /* alpha */};
Robert Wu06db0a32021-08-10 19:05:34 +0000666 audio_utils::Statistics<double> mMonopipePipeDepthStats{0.999 /* alpha */};
Andy Hung446f4df2019-02-21 12:26:41 -0800667
Andy Hungd0979812019-02-21 15:51:44 -0800668 // Save the last count when we delivered statistics to mediametrics.
669 int64_t mLastRecordedTimestampVerifierN = 0;
670 int64_t mLastRecordedTimeNs = 0; // BOOTTIME to include suspend.
671
Andy Hungc8fddf32018-08-08 18:32:37 -0700672 bool mIsMsdDevice = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800673 // A condition that must be evaluated by the thread loop has changed and
674 // we must not wait for async write callback in the thread loop before evaluating it
675 bool mSignalPending;
Andy Hungdae27702016-10-31 14:01:16 -0700676
Andy Hung8946a282018-04-19 20:04:56 -0700677#ifdef TEE_SINK
678 NBAIO_Tee mTee;
679#endif
Andy Hungdae27702016-10-31 14:01:16 -0700680 // ActiveTracks is a sorted vector of track type T representing the
681 // active tracks of threadLoop() to be considered by the locked prepare portion.
682 // ActiveTracks should be accessed with the ThreadBase lock held.
683 //
684 // During processing and I/O, the threadLoop does not hold the lock;
685 // hence it does not directly use ActiveTracks. Care should be taken
686 // to hold local strong references or defer removal of tracks
687 // if the threadLoop may still be accessing those tracks due to mix, etc.
688 //
689 // This class updates power information appropriately.
690 //
691
692 template <typename T>
693 class ActiveTracks {
694 public:
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700695 explicit ActiveTracks(SimpleLog *localLog = nullptr)
Andy Hungdae27702016-10-31 14:01:16 -0700696 : mActiveTracksGeneration(0)
697 , mLastActiveTracksGeneration(0)
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700698 , mLocalLog(localLog)
Andy Hungdae27702016-10-31 14:01:16 -0700699 { }
700
701 ~ActiveTracks() {
702 ALOGW_IF(!mActiveTracks.isEmpty(),
703 "ActiveTracks should be empty in destructor");
704 }
705 // returns the last track added (even though it may have been
706 // subsequently removed from ActiveTracks).
707 //
708 // Used for DirectOutputThread to ensure a flush is called when transitioning
709 // to a new track (even though it may be on the same session).
710 // Used for OffloadThread to ensure that volume and mixer state is
711 // taken from the latest track added.
712 //
713 // The latest track is saved with a weak pointer to prevent keeping an
714 // otherwise useless track alive. Thus the function will return nullptr
715 // if the latest track has subsequently been removed and destroyed.
716 sp<T> getLatest() {
717 return mLatestActiveTrack.promote();
718 }
719
720 // SortedVector methods
721 ssize_t add(const sp<T> &track);
722 ssize_t remove(const sp<T> &track);
723 size_t size() const {
724 return mActiveTracks.size();
725 }
Eric Tan39ec8d62018-07-24 09:49:29 -0700726 bool isEmpty() const {
727 return mActiveTracks.isEmpty();
728 }
Andy Hung0c1e11e2023-07-06 20:56:16 -0700729 ssize_t indexOf(const sp<T>& item) const {
Andy Hungdae27702016-10-31 14:01:16 -0700730 return mActiveTracks.indexOf(item);
731 }
732 sp<T> operator[](size_t index) const {
733 return mActiveTracks[index];
734 }
735 typename SortedVector<sp<T>>::iterator begin() {
736 return mActiveTracks.begin();
737 }
738 typename SortedVector<sp<T>>::iterator end() {
739 return mActiveTracks.end();
740 }
741
742 // Due to Binder recursion optimization, clear() and updatePowerState()
743 // cannot be called from a Binder thread because they may call back into
744 // the original calling process (system server) for BatteryNotifier
745 // (which requires a Java environment that may not be present).
746 // Hence, call clear() and updatePowerState() only from the
747 // ThreadBase thread.
748 void clear();
749 // periodically called in the threadLoop() to update power state uids.
Andy Hung920f6572022-10-06 12:09:49 -0700750 void updatePowerState(const sp<ThreadBase>& thread, bool force = false);
Andy Hungdae27702016-10-31 14:01:16 -0700751
Kevin Rocardc86a7f72018-04-03 09:00:09 -0700752 /** @return true if one or move active tracks was added or removed since the
Jasmine Chaeaa10e42021-05-11 10:11:14 +0800753 * last time this function was called or the vector was created.
754 * true if volume of one of active tracks was changed.
755 */
Kevin Rocard069c2712018-03-29 19:09:14 -0700756 bool readAndClearHasChanged();
757
Eric Laurentdda206a2022-07-08 17:28:35 +0200758 /** Force updating track metadata to audio HAL stream next time
759 * readAndClearHasChanged() is called.
760 */
761 void setHasChanged() { mHasChanged = true; }
762
Andy Hungdae27702016-10-31 14:01:16 -0700763 private:
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700764 void logTrack(const char *funcName, const sp<T> &track) const;
765
Andy Hungd01b0f12016-11-07 16:10:30 -0800766 SortedVector<uid_t> getWakeLockUids() {
767 SortedVector<uid_t> wakeLockUids;
Andy Hungdae27702016-10-31 14:01:16 -0700768 for (const sp<T> &track : mActiveTracks) {
769 wakeLockUids.add(track->uid());
770 }
771 return wakeLockUids; // moved by underlying SharedBuffer
772 }
773
Andy Hungdae27702016-10-31 14:01:16 -0700774 SortedVector<sp<T>> mActiveTracks;
775 int mActiveTracksGeneration;
776 int mLastActiveTracksGeneration;
777 wp<T> mLatestActiveTrack; // latest track added to ActiveTracks
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700778 SimpleLog * const mLocalLog;
Kevin Rocardc86a7f72018-04-03 09:00:09 -0700779 // If the vector has changed since last call to readAndClearHasChanged
Kevin Rocard069c2712018-03-29 19:09:14 -0700780 bool mHasChanged = false;
Andy Hungdae27702016-10-31 14:01:16 -0700781 };
Andy Hung293558a2017-03-21 12:19:20 -0700782
783 SimpleLog mLocalLog;
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700784
785private:
786 void dumpBase_l(int fd, const Vector<String16>& args);
787 void dumpEffectChains_l(int fd, const Vector<String16>& args);
Eric Laurent81784c32012-11-19 14:55:58 -0800788};
789
790// --- PlaybackThread ---
Andy Hung3e4c8742023-06-29 21:19:25 -0700791class PlaybackThread : public ThreadBase, public virtual IAfPlaybackThread,
792 public StreamOutHalInterfaceCallback,
Andy Hung0c1e11e2023-07-06 20:56:16 -0700793 public virtual VolumeInterface, public StreamOutHalInterfaceEventCallback {
Andy Hung11e74242023-06-26 19:20:57 -0700794 // TODO(b/288339104) remove friends
795 friend class OutputTrack;
796 friend class Track;
Eric Laurent81784c32012-11-19 14:55:58 -0800797public:
Andy Hung0c1e11e2023-07-06 20:56:16 -0700798 sp<IAfPlaybackThread> asIAfPlaybackThread() final {
799 return sp<IAfPlaybackThread>::fromExisting(this);
800 }
Eric Laurent81784c32012-11-19 14:55:58 -0800801
Eric Laurente93cc032016-05-05 10:15:10 -0700802 // retry count before removing active track in case of underrun on offloaded thread:
803 // we need to make sure that AudioTrack client has enough time to send large buffers
804 //FIXME may be more appropriate if expressed in time units. Need to revise how underrun is
805 // handled for offloaded tracks
806 static const int8_t kMaxTrackRetriesOffload = 20;
807 static const int8_t kMaxTrackStartupRetriesOffload = 100;
Andy Hung8ed196a2018-01-05 13:21:11 -0800808 static constexpr uint32_t kMaxTracksPerUid = 40;
Andy Hung1bc088a2018-02-09 15:57:31 -0800809 static constexpr size_t kMaxTracks = 256;
Eric Laurente93cc032016-05-05 10:15:10 -0700810
rago1bb90822017-05-02 18:31:48 -0700811 // Maximum delay (in nanoseconds) for upcoming buffers in suspend mode, otherwise
812 // if delay is greater, the estimated time for timeLoopNextNs is reset.
813 // This allows for catch-up to be done for small delays, while resetting the estimate
814 // for initial conditions or large delays.
815 static const nsecs_t kMaxNextBufferDelayNs = 100000000;
816
Eric Laurent81784c32012-11-19 14:55:58 -0800817 PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +0200818 audio_io_handle_t id, type_t type, bool systemReady,
819 audio_config_base_t *mixerConfig = nullptr);
Andy Hung3e4c8742023-06-29 21:19:25 -0700820 ~PlaybackThread() override;
Eric Laurent81784c32012-11-19 14:55:58 -0800821
Eric Laurent81784c32012-11-19 14:55:58 -0800822 // Thread virtuals
Andy Hung3e4c8742023-06-29 21:19:25 -0700823 bool threadLoop() final;
Eric Laurent81784c32012-11-19 14:55:58 -0800824
825 // RefBase
Andy Hung3e4c8742023-06-29 21:19:25 -0700826 void onFirstRef() override;
Eric Laurent81784c32012-11-19 14:55:58 -0800827
Andy Hung3e4c8742023-06-29 21:19:25 -0700828 status_t checkEffectCompatibility_l(
829 const effect_descriptor_t* desc, audio_session_t sessionId) final;
Eric Laurent4c415062016-06-17 16:14:16 -0700830
Andy Hung0c1e11e2023-07-06 20:56:16 -0700831 void addOutputTrack_l(const sp<IAfTrack>& track) final {
832 mTracks.add(track);
833 }
834
Eric Laurent81784c32012-11-19 14:55:58 -0800835protected:
836 // Code snippets that were lifted up out of threadLoop()
837 virtual void threadLoop_mix() = 0;
838 virtual void threadLoop_sleepTime() = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800839 virtual ssize_t threadLoop_write();
840 virtual void threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -0800841 virtual void threadLoop_standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800842 virtual void threadLoop_exit();
Andy Hung11e74242023-06-26 19:20:57 -0700843 virtual void threadLoop_removeTracks(const Vector<sp<IAfTrack>>& tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -0800844
845 // prepareTracks_l reads and writes mActiveTracks, and returns
846 // the pending set of tracks to remove via Vector 'tracksToRemove'. The caller
847 // is responsible for clearing or destroying this Vector later on, when it
848 // is safe to do so. That will drop the final ref count and destroy the tracks.
Andy Hung11e74242023-06-26 19:20:57 -0700849 virtual mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove) = 0;
850 void removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove);
Eric Laurenteab90452019-06-24 15:17:46 -0700851 status_t handleVoipVolume_l(float *volume);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800852
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700853 // StreamOutHalInterfaceCallback implementation
854 virtual void onWriteReady();
855 virtual void onDrainReady();
856 virtual void onError();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800857
Andy Hung4b17e882023-07-07 13:47:37 -0700858public: // AsyncCallbackThread
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700859 void resetWriteBlocked(uint32_t sequence);
860 void resetDraining(uint32_t sequence);
Andy Hung4b17e882023-07-07 13:47:37 -0700861protected:
Eric Laurentbfb1b832013-01-07 09:53:42 -0800862
863 virtual bool waitingAsyncCallback();
864 virtual bool waitingAsyncCallback_l();
865 virtual bool shouldStandby_l();
Haynes Mathew George4c6a4332014-01-15 12:31:39 -0800866 virtual void onAddNewTrack_l();
Andy Hung4b17e882023-07-07 13:47:37 -0700867public: // AsyncCallbackThread
Haynes Mathew George4527b9e2016-07-07 19:54:17 -0700868 void onAsyncError(); // error reported by AsyncCallbackThread
Andy Hung4b17e882023-07-07 13:47:37 -0700869protected:
jiabinf6eb4c32020-02-25 14:06:25 -0800870 // StreamHalInterfaceCodecFormatCallback implementation
871 void onCodecFormatChanged(
Andy Hung3e4c8742023-06-29 21:19:25 -0700872 const std::basic_string<uint8_t>& metadataBs) final;
jiabinf6eb4c32020-02-25 14:06:25 -0800873
Eric Laurent81784c32012-11-19 14:55:58 -0800874 // ThreadBase virtuals
875 virtual void preExit();
876
Eric Laurent64667972016-03-30 18:19:46 -0700877 virtual bool keepWakeLock() const { return true; }
Andy Hungdae27702016-10-31 14:01:16 -0700878 virtual void acquireWakeLock_l() {
879 ThreadBase::acquireWakeLock_l();
880 mActiveTracks.updatePowerState(this, true /* force */);
881 }
Eric Laurent64667972016-03-30 18:19:46 -0700882
Eric Laurentb3f315a2021-07-13 15:09:05 +0200883 virtual void checkOutputStageEffects() {}
Eric Laurent68a40a82022-05-03 18:15:04 +0200884 virtual void setHalLatencyMode_l() {}
885
Eric Laurentb3f315a2021-07-13 15:09:05 +0200886
Andy Hung3e4c8742023-06-29 21:19:25 -0700887 void dumpInternals_l(int fd, const Vector<String16>& args) override;
888 void dumpTracks_l(int fd, const Vector<String16>& args) final;
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700889
Eric Laurent81784c32012-11-19 14:55:58 -0800890public:
891
Andy Hung3e4c8742023-06-29 21:19:25 -0700892 status_t initCheck() const final { return mOutput == nullptr ? NO_INIT : NO_ERROR; }
Eric Laurent81784c32012-11-19 14:55:58 -0800893
894 // return estimated latency in milliseconds, as reported by HAL
Andy Hung3e4c8742023-06-29 21:19:25 -0700895 uint32_t latency() const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800896 // same, but lock must already be held
Andy Hung3e4c8742023-06-29 21:19:25 -0700897 uint32_t latency_l() const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800898
Eric Laurent6acd1d42017-01-04 14:23:29 -0800899 // VolumeInterface
Andy Hung3e4c8742023-06-29 21:19:25 -0700900 void setMasterVolume(float value) final;
901 void setMasterBalance(float balance) override;
902 void setMasterMute(bool muted) final;
903 void setStreamVolume(audio_stream_type_t stream, float value) final;
904 void setStreamMute(audio_stream_type_t stream, bool muted) final;
905 float streamVolume(audio_stream_type_t stream) const final;
906 void setVolumeForOutput_l(float left, float right) const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800907
Andy Hung3e4c8742023-06-29 21:19:25 -0700908 sp<IAfTrack> createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -0700909 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -0800910 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700911 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -0800912 uint32_t *sampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -0800913 audio_format_t format,
914 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -0800915 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -0800916 size_t *pNotificationFrameCount,
917 uint32_t notificationsPerBuffer,
918 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -0800919 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -0800920 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -0700921 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700922 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +0000923 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -0800924 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800925 status_t *status /*non-NULL*/,
jiabinf6eb4c32020-02-25 14:06:25 -0800926 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200927 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +0000928 bool isSpatialized,
Andy Hung3e4c8742023-06-29 21:19:25 -0700929 bool isBitPerfect) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800930
Andy Hung0c1e11e2023-07-06 20:56:16 -0700931 bool isTrackActive(const sp<IAfTrack>& track) const final {
932 return mActiveTracks.indexOf(track) >= 0;
933 }
934
935 AudioStreamOut* getOutput_l() const final { return mOutput; }
Andy Hung3e4c8742023-06-29 21:19:25 -0700936 AudioStreamOut* getOutput() const final;
937 AudioStreamOut* clearOutput() final;
938 sp<StreamHalInterface> stream() const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800939
940 // a very large number of suspend() will eventually wraparound, but unlikely
Andy Hung3e4c8742023-06-29 21:19:25 -0700941 void suspend() final { (void) android_atomic_inc(&mSuspended); }
942 void restore() final
Eric Laurent81784c32012-11-19 14:55:58 -0800943 {
944 // if restore() is done without suspend(), get back into
945 // range so that the next suspend() will operate correctly
946 if (android_atomic_dec(&mSuspended) <= 0) {
947 android_atomic_release_store(0, &mSuspended);
948 }
949 }
Andy Hung3e4c8742023-06-29 21:19:25 -0700950 bool isSuspended() const final
Eric Laurent81784c32012-11-19 14:55:58 -0800951 { return android_atomic_acquire_load(&mSuspended) > 0; }
952
Andy Hung3e4c8742023-06-29 21:19:25 -0700953 String8 getParameters(const String8& keys);
954 void ioConfigChanged(audio_io_config_event_t event, pid_t pid = 0,
955 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final;
956 status_t getRenderPosition(uint32_t* halFrames, uint32_t* dspFrames) const final;
Andy Hung010a1a12014-03-13 13:57:33 -0700957 // Consider also removing and passing an explicit mMainBuffer initialization
Andy Hung11e74242023-06-26 19:20:57 -0700958 // parameter to AF::IAfTrack::Track().
Andy Hung3e4c8742023-06-29 21:19:25 -0700959 float* sinkBuffer() const final {
Andy Hung319587b2023-05-23 14:01:03 -0700960 return reinterpret_cast<float *>(mSinkBuffer); };
Eric Laurent81784c32012-11-19 14:55:58 -0800961
Andy Hung3e4c8742023-06-29 21:19:25 -0700962 void detachAuxEffect_l(int effectId) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800963
Andy Hung3e4c8742023-06-29 21:19:25 -0700964 status_t attachAuxEffect(const sp<IAfTrack>& track, int EffectId) final;
965 status_t attachAuxEffect_l(const sp<IAfTrack>& track, int EffectId) final;
966
967 status_t addEffectChain_l(const sp<IAfEffectChain>& chain) final;
968 size_t removeEffectChain_l(const sp<IAfEffectChain>& chain) final;
969 uint32_t hasAudioSession_l(audio_session_t sessionId) const final {
Andy Hungc3d62f92019-03-14 13:38:51 -0700970 return ThreadBase::hasAudioSession_l(sessionId, mTracks);
971 }
Andy Hung3e4c8742023-06-29 21:19:25 -0700972 product_strategy_t getStrategyForSession_l(audio_session_t sessionId) const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800973
974
Andy Hung3e4c8742023-06-29 21:19:25 -0700975 status_t setSyncEvent(const sp<audioflinger::SyncEvent>& event) final;
976 bool isValidSyncEvent(const sp<audioflinger::SyncEvent>& event) const final;
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700977
978 // called with AudioFlinger lock held
Andy Hung3e4c8742023-06-29 21:19:25 -0700979 bool invalidateTracks_l(audio_stream_type_t streamType) final;
980 bool invalidateTracks_l(std::set<audio_port_handle_t>& portIds) final;
981 void invalidateTracks(audio_stream_type_t streamType) override;
jiabinc44b3462022-12-08 12:52:31 -0800982 // Invalidate tracks by a set of port ids. The port id will be removed from
983 // the given set if the corresponding track is found and invalidated.
Andy Hung3e4c8742023-06-29 21:19:25 -0700984 void invalidateTracks(std::set<audio_port_handle_t>& portIds) override;
Eric Laurent81784c32012-11-19 14:55:58 -0800985
Andy Hung0c1e11e2023-07-06 20:56:16 -0700986 size_t frameCount() const final { return mNormalFrameCount; }
Glenn Kasten9b58f632013-07-16 11:37:48 -0700987
Andy Hung3e4c8742023-06-29 21:19:25 -0700988 audio_channel_mask_t mixerChannelMask() const final {
Eric Laurentf1f22e72021-07-13 14:04:14 +0200989 return mMixerChannelMask;
990 }
991
Andy Hung3e4c8742023-06-29 21:19:25 -0700992 status_t getTimestamp_l(AudioTimestamp& timestamp) final;
Eric Laurent83b88082014-06-20 18:31:16 -0700993
Andy Hung3e4c8742023-06-29 21:19:25 -0700994 void addPatchTrack(const sp<IAfPatchTrack>& track) final;
995 void deletePatchTrack(const sp<IAfPatchTrack>& track) final;
Eric Laurent83b88082014-06-20 18:31:16 -0700996
Andy Hung3e4c8742023-06-29 21:19:25 -0700997 void toAudioPortConfig(struct audio_port_config* config) final;
Eric Laurentaccc1472013-09-20 09:36:34 -0700998
Andy Hung10cbff12017-02-21 17:30:14 -0800999 // Return the asynchronous signal wait time.
Andy Hung3e4c8742023-06-29 21:19:25 -07001000 int64_t computeWaitTimeNs_l() const override { return INT64_MAX; }
Andy Hung1bc088a2018-02-09 15:57:31 -08001001 // returns true if the track is allowed to be added to the thread.
Andy Hung3e4c8742023-06-29 21:19:25 -07001002 bool isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08001003 audio_channel_mask_t channelMask __unused,
1004 audio_format_t format __unused,
1005 audio_session_t sessionId __unused,
Andy Hung3e4c8742023-06-29 21:19:25 -07001006 uid_t uid) const override {
Andy Hung1bc088a2018-02-09 15:57:31 -08001007 return trackCountForUid_l(uid) < PlaybackThread::kMaxTracksPerUid
1008 && mTracks.size() < PlaybackThread::kMaxTracks;
1009 }
1010
Andy Hung3e4c8742023-06-29 21:19:25 -07001011 bool isTimestampCorrectionEnabled() const final {
jiabinc52b1ff2019-10-31 17:20:42 -07001012 return audio_is_output_devices(mTimestampCorrectedDevice)
1013 && outDeviceTypes().count(mTimestampCorrectedDevice) != 0;
Andy Hungc8fddf32018-08-08 18:32:37 -07001014 }
jiabinc52b1ff2019-10-31 17:20:42 -07001015
Andy Hung3e4c8742023-06-29 21:19:25 -07001016 bool isStreamInitialized() const final {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001017 return !(mOutput == nullptr || mOutput->stream == nullptr);
1018 }
1019
Andy Hung3e4c8742023-06-29 21:19:25 -07001020 audio_channel_mask_t hapticChannelMask() const final {
jiabineb3bda02020-06-30 14:07:03 -07001021 return mHapticChannelMask;
1022 }
Andy Hung0c1e11e2023-07-06 20:56:16 -07001023
1024 uint32_t hapticChannelCount() const final {
1025 return mHapticChannelCount;
1026 }
1027
Andy Hung3e4c8742023-06-29 21:19:25 -07001028 bool supportsHapticPlayback() const final {
jiabineb3bda02020-06-30 14:07:03 -07001029 return (mHapticChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE;
1030 }
1031
Andy Hung3e4c8742023-06-29 21:19:25 -07001032 void setDownStreamPatch(const struct audio_patch* patch) final {
Eric Laurent74c38dc2020-12-23 18:19:44 +01001033 Mutex::Autolock _l(mLock);
1034 mDownStreamPatch = *patch;
1035 }
1036
Andy Hung3e4c8742023-06-29 21:19:25 -07001037 IAfTrack* getTrackById_l(audio_port_handle_t trackId) final;
jiabinf042b9b2021-05-07 23:46:28 +00001038
Andy Hung3e4c8742023-06-29 21:19:25 -07001039 bool hasMixer() const final {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001040 return mType == MIXER || mType == DUPLICATING || mType == SPATIALIZER;
Eric Laurentb3f315a2021-07-13 15:09:05 +02001041 }
Eric Laurent68a40a82022-05-03 18:15:04 +02001042
Andy Hung3e4c8742023-06-29 21:19:25 -07001043 status_t setRequestedLatencyMode(
1044 audio_latency_mode_t /* mode */) override { return INVALID_OPERATION; }
Eric Laurent68a40a82022-05-03 18:15:04 +02001045
Andy Hung3e4c8742023-06-29 21:19:25 -07001046 status_t getSupportedLatencyModes(
1047 std::vector<audio_latency_mode_t>* /* modes */) override {
Eric Laurent68a40a82022-05-03 18:15:04 +02001048 return INVALID_OPERATION;
1049 }
1050
Andy Hung3e4c8742023-06-29 21:19:25 -07001051 status_t setBluetoothVariableLatencyEnabled(bool /* enabled */) override{
Eric Laurentb0463942022-12-20 16:31:10 +01001052 return INVALID_OPERATION;
1053 }
Eric Laurent52057642022-12-16 11:45:07 +01001054
Andy Hung3e4c8742023-06-29 21:19:25 -07001055 void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) override;
1056 void stopMelComputation_l() override;
Vlad Popab042ee62022-10-20 18:05:00 +02001057
Andy Hung3e4c8742023-06-29 21:19:25 -07001058 void setStandby() final {
Eric Laurent19952e12023-04-20 10:08:29 +02001059 Mutex::Autolock _l(mLock);
1060 setStandby_l();
1061 }
1062
Andy Hung3e4c8742023-06-29 21:19:25 -07001063 void setStandby_l() final {
Eric Laurent19952e12023-04-20 10:08:29 +02001064 mStandby = true;
1065 mHalStarted = false;
1066 mKernelPositionOnStandby =
1067 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
1068 }
1069
Andy Hung3e4c8742023-06-29 21:19:25 -07001070 bool waitForHalStart() final {
Eric Laurent19952e12023-04-20 10:08:29 +02001071 Mutex::Autolock _l(mLock);
1072 static const nsecs_t kWaitHalTimeoutNs = seconds(2);
1073 nsecs_t endWaitTimetNs = systemTime() + kWaitHalTimeoutNs;
1074 while (!mHalStarted) {
1075 nsecs_t timeNs = systemTime();
1076 if (timeNs >= endWaitTimetNs) {
1077 break;
1078 }
1079 nsecs_t waitTimeLeftNs = endWaitTimetNs - timeNs;
1080 mWaitHalStartCV.waitRelative(mLock, waitTimeLeftNs);
1081 }
1082 return mHalStarted;
1083 }
Eric Laurent81784c32012-11-19 14:55:58 -08001084protected:
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001085 // updated by readOutputParameters_l()
Glenn Kasten9b58f632013-07-16 11:37:48 -07001086 size_t mNormalFrameCount; // normal mixer and effects
1087
Andy Hung08fb1742015-05-31 23:22:10 -07001088 bool mThreadThrottle; // throttle the thread processing
Andy Hung40eb1a12015-06-18 13:42:02 -07001089 uint32_t mThreadThrottleTimeMs; // throttle time for MIXER threads
1090 uint32_t mThreadThrottleEndMs; // notify once per throttling
Andy Hung08fb1742015-05-31 23:22:10 -07001091 uint32_t mHalfBufferMs; // half the buffer size in milliseconds
1092
Andy Hung010a1a12014-03-13 13:57:33 -07001093 void* mSinkBuffer; // frame size aligned sink buffer
Eric Laurent81784c32012-11-19 14:55:58 -08001094
Andy Hung98ef9782014-03-04 14:46:50 -08001095 // TODO:
1096 // Rearrange the buffer info into a struct/class with
1097 // clear, copy, construction, destruction methods.
1098 //
1099 // mSinkBuffer also has associated with it:
1100 //
1101 // mSinkBufferSize: Sink Buffer Size
1102 // mFormat: Sink Buffer Format
1103
Andy Hung69aed5f2014-02-25 17:24:40 -08001104 // Mixer Buffer (mMixerBuffer*)
1105 //
1106 // In the case of floating point or multichannel data, which is not in the
1107 // sink format, it is required to accumulate in a higher precision or greater channel count
1108 // buffer before downmixing or data conversion to the sink buffer.
1109
1110 // Set to "true" to enable the Mixer Buffer otherwise mixer output goes to sink buffer.
1111 bool mMixerBufferEnabled;
1112
1113 // Storage, 32 byte aligned (may make this alignment a requirement later).
1114 // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
1115 void* mMixerBuffer;
1116
1117 // Size of mMixerBuffer in bytes: mNormalFrameCount * #channels * sampsize.
1118 size_t mMixerBufferSize;
1119
1120 // The audio format of mMixerBuffer. Set to AUDIO_FORMAT_PCM_(FLOAT|16_BIT) only.
1121 audio_format_t mMixerBufferFormat;
1122
1123 // An internal flag set to true by MixerThread::prepareTracks_l()
1124 // when mMixerBuffer contains valid data after mixing.
1125 bool mMixerBufferValid;
1126
Andy Hung98ef9782014-03-04 14:46:50 -08001127 // Effects Buffer (mEffectsBuffer*)
1128 //
1129 // In the case of effects data, which is not in the sink format,
1130 // it is required to accumulate in a different buffer before data conversion
1131 // to the sink buffer.
1132
1133 // Set to "true" to enable the Effects Buffer otherwise effects output goes to sink buffer.
1134 bool mEffectBufferEnabled;
1135
1136 // Storage, 32 byte aligned (may make this alignment a requirement later).
1137 // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
1138 void* mEffectBuffer;
1139
1140 // Size of mEffectsBuffer in bytes: mNormalFrameCount * #channels * sampsize.
1141 size_t mEffectBufferSize;
1142
1143 // The audio format of mEffectsBuffer. Set to AUDIO_FORMAT_PCM_16_BIT only.
1144 audio_format_t mEffectBufferFormat;
1145
1146 // An internal flag set to true by MixerThread::prepareTracks_l()
1147 // when mEffectsBuffer contains valid data after mixing.
1148 //
1149 // When this is set, all mixer data is routed into the effects buffer
1150 // for any processing (including output processing).
1151 bool mEffectBufferValid;
1152
jiabinc658e452022-10-21 20:52:21 +00001153 // Set to "true" to enable when data has already copied to sink
1154 bool mHasDataCopiedToSinkBuffer = false;
1155
Eric Laurentb62d0362021-10-26 17:40:18 +02001156 // Frame size aligned buffer used as input and output to all post processing effects
1157 // except the Spatializer in a SPATIALIZER thread. Non spatialized tracks are mixed into
1158 // this buffer so that post processing effects can be applied.
1159 void* mPostSpatializerBuffer = nullptr;
1160
1161 // Size of mPostSpatializerBuffer in bytes
1162 size_t mPostSpatializerBufferSize;
Eric Laurent39095982021-08-24 18:29:27 +02001163
1164
Eric Laurent81784c32012-11-19 14:55:58 -08001165 // suspend count, > 0 means suspended. While suspended, the thread continues to pull from
1166 // tracks and mix, but doesn't write to HAL. A2DP and SCO HAL implementations can't handle
1167 // concurrent use of both of them, so Audio Policy Service suspends one of the threads to
1168 // workaround that restriction.
1169 // 'volatile' means accessed via atomic operations and no lock.
1170 volatile int32_t mSuspended;
1171
Andy Hung818e7a32016-02-16 18:08:07 -08001172 int64_t mBytesWritten;
yucliu6cfb5932022-07-20 17:40:39 -07001173 std::atomic<int64_t> mFramesWritten; // not reset on standby
Dean Wheatley12473e92021-03-18 23:00:55 +11001174 int64_t mLastFramesWritten = -1; // track changes in timestamp
1175 // server frames written.
Andy Hung238fa3d2016-07-28 10:53:22 -07001176 int64_t mSuspendedFrames; // not reset on standby
jiabin245cdd92018-12-07 17:55:15 -08001177
1178 // mHapticChannelMask and mHapticChannelCount will only be valid when the thread support
1179 // haptic playback.
1180 audio_channel_mask_t mHapticChannelMask = AUDIO_CHANNEL_NONE;
1181 uint32_t mHapticChannelCount = 0;
Eric Laurentf1f22e72021-07-13 14:04:14 +02001182
1183 audio_channel_mask_t mMixerChannelMask = AUDIO_CHANNEL_NONE;
1184
Eric Laurent81784c32012-11-19 14:55:58 -08001185 // mMasterMute is in both PlaybackThread and in AudioFlinger. When a
1186 // PlaybackThread needs to find out if master-muted, it checks it's local
1187 // copy rather than the one in AudioFlinger. This optimization saves a lock.
1188 bool mMasterMute;
1189 void setMasterMute_l(bool muted) { mMasterMute = muted; }
Dean Wheatley12473e92021-03-18 23:00:55 +11001190
1191 auto discontinuityForStandbyOrFlush() const { // call on threadLoop or with lock.
1192 return ((mType == DIRECT && !audio_is_linear_pcm(mFormat))
1193 || mType == OFFLOAD)
1194 ? mTimestampVerifier.DISCONTINUITY_MODE_ZERO
1195 : mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS;
1196 }
1197
Andy Hung11e74242023-06-26 19:20:57 -07001198 ActiveTracks<IAfTrack> mActiveTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08001199
Eric Laurent81784c32012-11-19 14:55:58 -08001200 // Time to sleep between cycles when:
1201 virtual uint32_t activeSleepTimeUs() const; // mixer state MIXER_TRACKS_ENABLED
1202 virtual uint32_t idleSleepTimeUs() const = 0; // mixer state MIXER_IDLE
1203 virtual uint32_t suspendSleepTimeUs() const = 0; // audio policy manager suspended us
1204 // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write()
1205 // No sleep in standby mode; waits on a condition
1206
1207 // Code snippets that are temporarily lifted up out of threadLoop() until the merge
Andy Hung3e4c8742023-06-29 21:19:25 -07001208 virtual void checkSilentMode_l() final; // consider unification with MMapThread
Eric Laurent81784c32012-11-19 14:55:58 -08001209
1210 // Non-trivial for DUPLICATING only
1211 virtual void saveOutputTracks() { }
1212 virtual void clearOutputTracks() { }
1213
1214 // Cache various calculated values, at threadLoop() entry and after a parameter change
1215 virtual void cacheParameters_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02001216 void setCheckOutputStageEffects() override {
1217 mCheckOutputStageEffects.store(true);
1218 }
Eric Laurent81784c32012-11-19 14:55:58 -08001219
1220 virtual uint32_t correctLatency_l(uint32_t latency) const;
1221
Eric Laurent1c333e22014-05-20 10:48:17 -07001222 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
1223 audio_patch_handle_t *handle);
1224 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle);
1225
Andy Hung0c1e11e2023-07-06 20:56:16 -07001226 bool usesHwAvSync() const final { return mType == DIRECT && mOutput != nullptr
Phil Burk6fc2a7c2015-04-30 16:08:10 -07001227 && mHwSupportsPause
1228 && (mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC); }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08001229
Andy Hung1bc088a2018-02-09 15:57:31 -08001230 uint32_t trackCountForUid_l(uid_t uid) const;
Eric Laurentad7dd962016-09-22 12:38:37 -07001231
jiabineb3bda02020-06-30 14:07:03 -07001232 void invalidateTracksForAudioSession_l(
Andy Hung3e4c8742023-06-29 21:19:25 -07001233 audio_session_t sessionId) const override {
jiabineb3bda02020-06-30 14:07:03 -07001234 ThreadBase::invalidateTracksForAudioSession_l(sessionId, mTracks);
1235 }
1236
Eric Laurent81784c32012-11-19 14:55:58 -08001237 friend class AudioFlinger; // for numerous
1238
Mikhail Naganovbf493082017-04-17 17:37:12 -07001239 DISALLOW_COPY_AND_ASSIGN(PlaybackThread);
Eric Laurent81784c32012-11-19 14:55:58 -08001240
Andy Hung0c1e11e2023-07-06 20:56:16 -07001241 status_t addTrack_l(const sp<IAfTrack>& track) final;
1242 bool destroyTrack_l(const sp<IAfTrack>& track) final;
1243
Andy Hung11e74242023-06-26 19:20:57 -07001244 void removeTrack_l(const sp<IAfTrack>& track);
Eric Laurent81784c32012-11-19 14:55:58 -08001245
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001246 void readOutputParameters_l();
Vlad Popa7e81cea2023-01-19 16:34:16 +01001247 MetadataUpdate updateMetadata_l() final;
Kevin Rocardc86a7f72018-04-03 09:00:09 -07001248 virtual void sendMetadataToBackend_l(const StreamOutHalInterface::SourceMetadata& metadata);
Eric Laurent81784c32012-11-19 14:55:58 -08001249
Dean Wheatley12473e92021-03-18 23:00:55 +11001250 void collectTimestamps_l();
1251
Andy Hungc0691382018-09-12 18:01:57 -07001252 // The Tracks class manages tracks added and removed from the Thread.
Andy Hung1bc088a2018-02-09 15:57:31 -08001253 template <typename T>
1254 class Tracks {
1255 public:
Andy Hung920f6572022-10-06 12:09:49 -07001256 explicit Tracks(bool saveDeletedTrackIds) :
Andy Hungc0691382018-09-12 18:01:57 -07001257 mSaveDeletedTrackIds(saveDeletedTrackIds) { }
Andy Hung1bc088a2018-02-09 15:57:31 -08001258
1259 // SortedVector methods
Andy Hungc0691382018-09-12 18:01:57 -07001260 ssize_t add(const sp<T> &track) {
1261 const ssize_t index = mTracks.add(track);
1262 LOG_ALWAYS_FATAL_IF(index < 0, "cannot add track");
1263 return index;
1264 }
Andy Hung1bc088a2018-02-09 15:57:31 -08001265 ssize_t remove(const sp<T> &track);
1266 size_t size() const {
1267 return mTracks.size();
1268 }
1269 bool isEmpty() const {
1270 return mTracks.isEmpty();
1271 }
1272 ssize_t indexOf(const sp<T> &item) {
1273 return mTracks.indexOf(item);
1274 }
1275 sp<T> operator[](size_t index) const {
1276 return mTracks[index];
1277 }
1278 typename SortedVector<sp<T>>::iterator begin() {
1279 return mTracks.begin();
1280 }
1281 typename SortedVector<sp<T>>::iterator end() {
1282 return mTracks.end();
1283 }
1284
Andy Hung920f6572022-10-06 12:09:49 -07001285 size_t processDeletedTrackIds(const std::function<void(int)>& f) {
Andy Hungc0691382018-09-12 18:01:57 -07001286 for (const int trackId : mDeletedTrackIds) {
1287 f(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08001288 }
Andy Hungc0691382018-09-12 18:01:57 -07001289 return mDeletedTrackIds.size();
Andy Hung1bc088a2018-02-09 15:57:31 -08001290 }
1291
Andy Hungc0691382018-09-12 18:01:57 -07001292 void clearDeletedTrackIds() { mDeletedTrackIds.clear(); }
Andy Hung1bc088a2018-02-09 15:57:31 -08001293
1294 private:
Andy Hungc0691382018-09-12 18:01:57 -07001295 // Tracks pending deletion for MIXER type threads
1296 const bool mSaveDeletedTrackIds; // true to enable tracking
1297 std::set<int> mDeletedTrackIds;
Andy Hung1bc088a2018-02-09 15:57:31 -08001298
1299 SortedVector<sp<T>> mTracks; // wrapped SortedVector.
1300 };
1301
Andy Hung11e74242023-06-26 19:20:57 -07001302 Tracks<IAfTrack> mTracks;
Andy Hung1bc088a2018-02-09 15:57:31 -08001303
Eric Laurent223fd5c2014-11-11 13:43:36 -08001304 stream_type_t mStreamTypes[AUDIO_STREAM_CNT];
Andy Hung4b17e882023-07-07 13:47:37 -07001305
Eric Laurent81784c32012-11-19 14:55:58 -08001306 AudioStreamOut *mOutput;
1307
1308 float mMasterVolume;
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001309 std::atomic<float> mMasterBalance{};
1310 audio_utils::Balance mBalance;
Eric Laurent81784c32012-11-19 14:55:58 -08001311 int mNumWrites;
1312 int mNumDelayedWrites;
1313 bool mInWrite;
1314
1315 // FIXME rename these former local variables of threadLoop to standard "m" names
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001316 nsecs_t mStandbyTimeNs;
Andy Hung25c2dac2014-02-27 14:56:00 -08001317 size_t mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001318
1319 // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l()
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001320 uint32_t mActiveSleepTimeUs;
1321 uint32_t mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08001322
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001323 uint32_t mSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08001324
1325 // mixer status returned by prepareTracks_l()
1326 mixer_state mMixerStatus; // current cycle
1327 // previous cycle when in prepareTracks_l()
1328 mixer_state mMixerStatusIgnoringFastTracks;
1329 // FIXME or a separate ready state per track
1330
1331 // FIXME move these declarations into the specific sub-class that needs them
1332 // MIXER only
1333 uint32_t sleepTimeShift;
1334
1335 // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001336 nsecs_t mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08001337
1338 // MIXER only
1339 nsecs_t maxPeriod;
1340
1341 // DUPLICATING only
1342 uint32_t writeFrames;
1343
Eric Laurentbfb1b832013-01-07 09:53:42 -08001344 size_t mBytesRemaining;
1345 size_t mCurrentWriteLength;
1346 bool mUseAsyncWrite;
Eric Laurent3b4529e2013-09-05 18:09:19 -07001347 // mWriteAckSequence contains current write sequence on bits 31-1. The write sequence is
1348 // incremented each time a write(), a flush() or a standby() occurs.
1349 // Bit 0 is set when a write blocks and indicates a callback is expected.
1350 // Bit 0 is reset by the async callback thread calling resetWriteBlocked(). Out of sequence
1351 // callbacks are ignored.
1352 uint32_t mWriteAckSequence;
1353 // mDrainSequence contains current drain sequence on bits 31-1. The drain sequence is
1354 // incremented each time a drain is requested or a flush() or standby() occurs.
1355 // Bit 0 is set when the drain() command is called at the HAL and indicates a callback is
1356 // expected.
1357 // Bit 0 is reset by the async callback thread calling resetDraining(). Out of sequence
1358 // callbacks are ignored.
1359 uint32_t mDrainSequence;
Andy Hung4b17e882023-07-07 13:47:37 -07001360
Eric Laurentbfb1b832013-01-07 09:53:42 -08001361 sp<AsyncCallbackThread> mCallbackThread;
1362
jiabinf6eb4c32020-02-25 14:06:25 -08001363 Mutex mAudioTrackCbLock;
1364 // Record of IAudioTrackCallback
Andy Hung11e74242023-06-26 19:20:57 -07001365 std::map<sp<IAfTrack>, sp<media::IAudioTrackCallback>> mAudioTrackCallbacks;
jiabinf6eb4c32020-02-25 14:06:25 -08001366
Eric Laurent81784c32012-11-19 14:55:58 -08001367 // The HAL output sink is treated as non-blocking, but current implementation is blocking
1368 sp<NBAIO_Sink> mOutputSink;
1369 // If a fast mixer is present, the blocking pipe sink, otherwise clear
1370 sp<NBAIO_Sink> mPipeSink;
1371 // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink
1372 sp<NBAIO_Sink> mNormalSink;
Andy Hung4b17e882023-07-07 13:47:37 -07001373
Eric Laurent81784c32012-11-19 14:55:58 -08001374 uint32_t mScreenState; // cached copy of gScreenState
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07001375 // TODO: add comment and adjust size as needed
Glenn Kasteneef598c2017-04-03 14:41:13 -07001376 static const size_t kFastMixerLogSize = 8 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -08001377 sp<NBLog::Writer> mFastMixerNBLogWriter;
Andy Hung2148bf02016-11-28 19:01:02 -08001378
Dean Wheatley30d28422018-11-06 10:27:40 +11001379 // Downstream patch latency, available if mDownstreamLatencyStatMs.getN() > 0.
1380 audio_utils::Statistics<double> mDownstreamLatencyStatMs{0.999};
Andy Hung2148bf02016-11-28 19:01:02 -08001381
Eric Laurent19952e12023-04-20 10:08:29 +02001382 // output stream start detection based on render position returned by the kernel
1383 // condition signalled when the output stream has started
1384 Condition mWaitHalStartCV;
1385 // true when the output stream render position has moved, reset to false in standby
1386 bool mHalStarted = false;
1387 // last kernel render position saved when entering standby
1388 int64_t mKernelPositionOnStandby = 0;
1389
Eric Laurent81784c32012-11-19 14:55:58 -08001390public:
Andy Hung3e4c8742023-06-29 21:19:25 -07001391 FastTrackUnderruns getFastTrackUnderruns(size_t /* fastIndex */) const override
1392 { return {}; }
1393 const std::atomic<int64_t>& framesWritten() const final { return mFramesWritten; }
Eric Laurent81784c32012-11-19 14:55:58 -08001394
1395protected:
1396 // accessed by both binder threads and within threadLoop(), lock on mutex needed
Andy Hung0c1e11e2023-07-06 20:56:16 -07001397 uint32_t& fastTrackAvailMask_l() final { return mFastTrackAvailMask; }
1398 uint32_t mFastTrackAvailMask; // bit i set if fast track [i] is available
Eric Laurentd1f69b02014-12-15 14:33:13 -08001399 bool mHwSupportsPause;
1400 bool mHwPaused;
1401 bool mFlushPending;
Eric Laurent7c29ec92017-09-20 17:54:22 -07001402 // volumes last sent to audio HAL with stream->setVolume()
1403 float mLeftVolFloat;
1404 float mRightVolFloat;
Eric Laurent74c38dc2020-12-23 18:19:44 +01001405
1406 // audio patch used by the downstream software patch.
1407 // Only used if ThreadBase::mIsMsdDevice is true.
1408 struct audio_patch mDownStreamPatch;
Eric Laurentb3f315a2021-07-13 15:09:05 +02001409
1410 std::atomic_bool mCheckOutputStageEffects{};
ziyangch8f194f12021-12-01 13:48:04 -08001411
ziyangch8f194f12021-12-01 13:48:04 -08001412
Brian Lindahl65e90012022-07-27 18:01:07 +02001413 // Provides periodic checking for timestamp advancement for underrun detection.
1414 class IsTimestampAdvancing {
1415 public:
1416 // The timestamp will not be checked any faster than the specified time.
Andy Hung920f6572022-10-06 12:09:49 -07001417 explicit IsTimestampAdvancing(nsecs_t minimumTimeBetweenChecksNs)
Brian Lindahl65e90012022-07-27 18:01:07 +02001418 : mMinimumTimeBetweenChecksNs(minimumTimeBetweenChecksNs)
1419 {
1420 clear();
1421 }
1422 // Check if the presentation position has advanced in the last periodic time.
1423 bool check(AudioStreamOut * output);
1424 // Clear the internal state when the playback state changes for the output
1425 // stream.
1426 void clear();
1427 private:
1428 // The minimum time between timestamp checks.
1429 const nsecs_t mMinimumTimeBetweenChecksNs;
1430 // Add differential check on the timestamps to see if there is a change in the
1431 // timestamp frame position between the last call to check.
1432 uint64_t mPreviousPosition;
1433 // The time at which the last check occurred, to ensure we don't check too
1434 // frequently, giving the Audio HAL enough time to update its timestamps.
1435 nsecs_t mPreviousNs;
1436 // The valued is latched so we don't check timestamps too frequently.
1437 bool mLatchedValue;
1438 };
1439 IsTimestampAdvancing mIsTimestampAdvancing;
ziyangch8f194f12021-12-01 13:48:04 -08001440
Brian Lindahl65e90012022-07-27 18:01:07 +02001441 virtual void flushHw_l() {
1442 mIsTimestampAdvancing.clear();
1443 }
Eric Laurent81784c32012-11-19 14:55:58 -08001444};
1445
Eric Laurentb0463942022-12-20 16:31:10 +01001446class MixerThread : public PlaybackThread,
1447 public StreamOutHalInterfaceLatencyModeCallback {
Eric Laurent81784c32012-11-19 14:55:58 -08001448public:
1449 MixerThread(const sp<AudioFlinger>& audioFlinger,
1450 AudioStreamOut* output,
1451 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001452 bool systemReady,
Eric Laurentf1f22e72021-07-13 14:04:14 +02001453 type_t type = MIXER,
1454 audio_config_base_t *mixerConfig = nullptr);
Andy Hung3e4c8742023-06-29 21:19:25 -07001455 ~MixerThread() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001456
Eric Laurentb0463942022-12-20 16:31:10 +01001457 // RefBase
Andy Hung3e4c8742023-06-29 21:19:25 -07001458 void onFirstRef() override;
Eric Laurentb0463942022-12-20 16:31:10 +01001459
1460 // StreamOutHalInterfaceLatencyModeCallback
1461 void onRecommendedLatencyModeChanged(
Andy Hung3e4c8742023-06-29 21:19:25 -07001462 std::vector<audio_latency_mode_t> modes) final;
Eric Laurentb0463942022-12-20 16:31:10 +01001463
Eric Laurent81784c32012-11-19 14:55:58 -08001464 // Thread virtuals
1465
Andy Hung3e4c8742023-06-29 21:19:25 -07001466 bool checkForNewParameter_l(const String8& keyValuePair, status_t& status) final;
Eric Laurent81784c32012-11-19 14:55:58 -08001467
Andy Hung3e4c8742023-06-29 21:19:25 -07001468 bool isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08001469 audio_channel_mask_t channelMask, audio_format_t format,
Andy Hung3e4c8742023-06-29 21:19:25 -07001470 audio_session_t sessionId, uid_t uid) const final;
Eric Laurent81784c32012-11-19 14:55:58 -08001471protected:
Andy Hung3e4c8742023-06-29 21:19:25 -07001472 mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove) override;
1473 uint32_t idleSleepTimeUs() const final;
1474 uint32_t suspendSleepTimeUs() const final;
1475 void cacheParameters_l() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001476
Andy Hung3e4c8742023-06-29 21:19:25 -07001477 void acquireWakeLock_l() final {
Andy Hungdae27702016-10-31 14:01:16 -07001478 PlaybackThread::acquireWakeLock_l();
Andy Hung818e7a32016-02-16 18:08:07 -08001479 if (hasFastMixer()) {
1480 mFastMixer->setBoottimeOffset(
1481 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME]);
1482 }
1483 }
1484
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001485 void dumpInternals_l(int fd, const Vector<String16>& args) override;
1486
Eric Laurent81784c32012-11-19 14:55:58 -08001487 // threadLoop snippets
Andy Hung3e4c8742023-06-29 21:19:25 -07001488 ssize_t threadLoop_write() override;
1489 void threadLoop_standby() override;
1490 void threadLoop_mix() override;
1491 void threadLoop_sleepTime() override;
1492 uint32_t correctLatency_l(uint32_t latency) const final;
Eric Laurent81784c32012-11-19 14:55:58 -08001493
Andy Hung3e4c8742023-06-29 21:19:25 -07001494 status_t createAudioPatch_l(
1495 const struct audio_patch* patch, audio_patch_handle_t* handle) final;
1496 status_t releaseAudioPatch_l(const audio_patch_handle_t handle) final;
Eric Laurent054d9d32015-04-24 08:48:48 -07001497
Eric Laurent81784c32012-11-19 14:55:58 -08001498 AudioMixer* mAudioMixer; // normal mixer
Eric Laurentb0463942022-12-20 16:31:10 +01001499
1500 // Support low latency mode by default as unless explicitly indicated by the audio HAL
1501 // we assume the audio path is compatible with the head tracking latency requirements
1502 std::vector<audio_latency_mode_t> mSupportedLatencyModes = {AUDIO_LATENCY_MODE_LOW};
1503 // default to invalid value to force first update to the audio HAL
1504 audio_latency_mode_t mSetLatencyMode =
1505 (audio_latency_mode_t)AUDIO_LATENCY_MODE_INVALID;
1506
1507 // Bluetooth Variable latency control logic is enabled or disabled for this thread
1508 std::atomic_bool mBluetoothLatencyModesEnabled;
1509
Eric Laurent81784c32012-11-19 14:55:58 -08001510private:
1511 // one-time initialization, no locks required
Glenn Kasten4d23ca32014-05-13 10:39:51 -07001512 sp<FastMixer> mFastMixer; // non-0 if there is also a fast mixer
Eric Laurent81784c32012-11-19 14:55:58 -08001513 sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread
1514
1515 // contents are not guaranteed to be consistent, no locks required
1516 FastMixerDumpState mFastMixerDumpState;
1517#ifdef STATE_QUEUE_DUMP
1518 StateQueueObserverDump mStateQueueObserverDump;
1519 StateQueueMutatorDump mStateQueueMutatorDump;
1520#endif
1521 AudioWatchdogDump mAudioWatchdogDump;
1522
1523 // accessible only within the threadLoop(), no locks required
1524 // mFastMixer->sq() // for mutating and pushing state
1525 int32_t mFastMixerFutex; // for cold idle
1526
Andy Hung2ddee192015-12-18 17:34:44 -08001527 std::atomic_bool mMasterMono;
Eric Laurent81784c32012-11-19 14:55:58 -08001528public:
Glenn Kasten4d23ca32014-05-13 10:39:51 -07001529 virtual bool hasFastMixer() const { return mFastMixer != 0; }
Eric Laurent81784c32012-11-19 14:55:58 -08001530 virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const {
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001531 ALOG_ASSERT(fastIndex < FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08001532 return mFastMixerDumpState.mTracks[fastIndex].mUnderruns;
1533 }
Eric Laurent83b88082014-06-20 18:31:16 -07001534
Andy Hung1c86ebe2018-05-29 20:29:08 -07001535 status_t threadloop_getHalTimestamp_l(
1536 ExtendedTimestamp *timestamp) const override {
1537 if (mNormalSink.get() != nullptr) {
1538 return mNormalSink->getTimestamp(*timestamp);
1539 }
1540 return INVALID_OPERATION;
1541 }
1542
Eric Laurentb0463942022-12-20 16:31:10 +01001543 status_t getSupportedLatencyModes(
1544 std::vector<audio_latency_mode_t>* modes) override;
1545
1546 status_t setBluetoothVariableLatencyEnabled(bool enabled) override;
1547
Andy Hung2ddee192015-12-18 17:34:44 -08001548protected:
1549 virtual void setMasterMono_l(bool mono) {
1550 mMasterMono.store(mono);
1551 if (mFastMixer != nullptr) { /* hasFastMixer() */
1552 mFastMixer->setMasterMono(mMasterMono);
1553 }
1554 }
1555 // the FastMixer performs mono blend if it exists.
Glenn Kasten03c48d52016-01-27 17:25:17 -08001556 // Blending with limiter is not idempotent,
1557 // and blending without limiter is idempotent but inefficient to do twice.
Andy Hung2ddee192015-12-18 17:34:44 -08001558 virtual bool requireMonoBlend() { return mMasterMono.load() && !hasFastMixer(); }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001559
1560 void setMasterBalance(float balance) override {
1561 mMasterBalance.store(balance);
1562 if (hasFastMixer()) {
1563 mFastMixer->setMasterBalance(balance);
1564 }
1565 }
Eric Laurentb0463942022-12-20 16:31:10 +01001566
1567 void updateHalSupportedLatencyModes_l();
1568 void onHalLatencyModesChanged_l() override;
1569 void setHalLatencyMode_l() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001570};
1571
Andy Hung0c1e11e2023-07-06 20:56:16 -07001572class DirectOutputThread : public PlaybackThread, public virtual IAfDirectOutputThread {
Eric Laurent81784c32012-11-19 14:55:58 -08001573public:
1574
Andy Hung0c1e11e2023-07-06 20:56:16 -07001575 sp<IAfDirectOutputThread> asIAfDirectOutputThread() final {
1576 return sp<IAfDirectOutputThread>::fromExisting(this);
1577 }
1578
Eric Laurent81784c32012-11-19 14:55:58 -08001579 DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Gareth Fennb18c1a32022-10-05 13:42:36 -07001580 audio_io_handle_t id, bool systemReady,
1581 const audio_offload_info_t& offloadInfo)
1582 : DirectOutputThread(audioFlinger, output, id, DIRECT, systemReady, offloadInfo) { }
Andy Hung48f59ed2019-01-28 15:06:59 -08001583
Eric Laurent81784c32012-11-19 14:55:58 -08001584 virtual ~DirectOutputThread();
1585
Andy Hung0c1e11e2023-07-06 20:56:16 -07001586 status_t selectPresentation(int presentationId, int programId) final;
Mikhail Naganovac917ac2018-11-28 14:03:52 -08001587
Eric Laurent81784c32012-11-19 14:55:58 -08001588 // Thread virtuals
1589
Eric Laurent10351942014-05-08 18:49:52 -07001590 virtual bool checkForNewParameter_l(const String8& keyValuePair,
1591 status_t& status);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001592
ziyangch8f194f12021-12-01 13:48:04 -08001593 void flushHw_l() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001594
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001595 void setMasterBalance(float balance) override;
1596
Eric Laurent81784c32012-11-19 14:55:58 -08001597protected:
Eric Laurent81784c32012-11-19 14:55:58 -08001598 virtual uint32_t activeSleepTimeUs() const;
1599 virtual uint32_t idleSleepTimeUs() const;
1600 virtual uint32_t suspendSleepTimeUs() const;
1601 virtual void cacheParameters_l();
1602
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001603 void dumpInternals_l(int fd, const Vector<String16>& args) override;
1604
Eric Laurent81784c32012-11-19 14:55:58 -08001605 // threadLoop snippets
Andy Hung11e74242023-06-26 19:20:57 -07001606 virtual mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08001607 virtual void threadLoop_mix();
1608 virtual void threadLoop_sleepTime();
Eric Laurentd1f69b02014-12-15 14:33:13 -08001609 virtual void threadLoop_exit();
1610 virtual bool shouldStandby_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001611
Phil Burk43b4dcc2015-06-09 16:53:44 -07001612 virtual void onAddNewTrack_l();
1613
Gareth Fennb18c1a32022-10-05 13:42:36 -07001614 const audio_offload_info_t mOffloadInfo;
Andy Hung398ffa22022-12-13 19:19:53 -08001615
1616 audioflinger::MonotonicFrameCounter mMonotonicFrameCounter; // for VolumeShaper
Andy Hung48f59ed2019-01-28 15:06:59 -08001617 bool mVolumeShaperActive = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001618
Eric Laurentbfb1b832013-01-07 09:53:42 -08001619 DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Gareth Fennb18c1a32022-10-05 13:42:36 -07001620 audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
1621 const audio_offload_info_t& offloadInfo);
Andy Hung11e74242023-06-26 19:20:57 -07001622 void processVolume_l(IAfTrack *track, bool lastTrack);
Gareth Fennb18c1a32022-10-05 13:42:36 -07001623 bool isTunerStream() const { return (mOffloadInfo.content_id > 0); }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001624
Eric Laurent81784c32012-11-19 14:55:58 -08001625 // prepareTracks_l() tells threadLoop_mix() the name of the single active track
Andy Hung11e74242023-06-26 19:20:57 -07001626 sp<IAfTrack> mActiveTrack;
Phil Burk43b4dcc2015-06-09 16:53:44 -07001627
Andy Hung11e74242023-06-26 19:20:57 -07001628 wp<IAfTrack> mPreviousTrack; // used to detect track switch
Phil Burk43b4dcc2015-06-09 16:53:44 -07001629
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001630 // This must be initialized for initial condition of mMasterBalance = 0 (disabled).
1631 float mMasterBalanceLeft = 1.f;
1632 float mMasterBalanceRight = 1.f;
1633
Eric Laurent81784c32012-11-19 14:55:58 -08001634public:
1635 virtual bool hasFastMixer() const { return false; }
Andy Hung10cbff12017-02-21 17:30:14 -08001636
1637 virtual int64_t computeWaitTimeNs_l() const override;
Andy Hungf3234512018-07-03 14:51:47 -07001638
1639 status_t threadloop_getHalTimestamp_l(ExtendedTimestamp *timestamp) const override {
1640 // For DIRECT and OFFLOAD threads, query the output sink directly.
1641 if (mOutput != nullptr) {
1642 uint64_t uposition64;
1643 struct timespec time;
1644 if (mOutput->getPresentationPosition(
1645 &uposition64, &time) == OK) {
1646 timestamp->mPosition[ExtendedTimestamp::LOCATION_KERNEL]
1647 = (int64_t)uposition64;
1648 timestamp->mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
1649 = audio_utils_ns_from_timespec(&time);
1650 return NO_ERROR;
1651 }
1652 }
1653 return INVALID_OPERATION;
1654 }
Eric Laurent81784c32012-11-19 14:55:58 -08001655};
1656
Eric Laurentbfb1b832013-01-07 09:53:42 -08001657class OffloadThread : public DirectOutputThread {
1658public:
1659
1660 OffloadThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Gareth Fennb18c1a32022-10-05 13:42:36 -07001661 audio_io_handle_t id, bool systemReady,
1662 const audio_offload_info_t& offloadInfo);
Eric Laurent6a51d7e2013-10-17 18:59:26 -07001663 virtual ~OffloadThread() {};
ziyangch8f194f12021-12-01 13:48:04 -08001664 void flushHw_l() override;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001665
1666protected:
1667 // threadLoop snippets
Andy Hung11e74242023-06-26 19:20:57 -07001668 virtual mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001669 virtual void threadLoop_exit();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001670
1671 virtual bool waitingAsyncCallback();
1672 virtual bool waitingAsyncCallback_l();
Haynes Mathew George05317d22016-05-03 16:34:26 -07001673 virtual void invalidateTracks(audio_stream_type_t streamType);
jiabinc44b3462022-12-08 12:52:31 -08001674 void invalidateTracks(std::set<audio_port_handle_t>& portIds) override;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001675
Eric Laurentde0613d2016-07-22 18:19:11 -07001676 virtual bool keepWakeLock() const { return (mKeepWakeLock || (mDrainSequence & 1)); }
Eric Laurent64667972016-03-30 18:19:46 -07001677
Eric Laurentbfb1b832013-01-07 09:53:42 -08001678private:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001679 size_t mPausedWriteLength; // length in bytes of write interrupted by pause
1680 size_t mPausedBytesRemaining; // bytes still waiting in mixbuffer after resume
Eric Laurent64667972016-03-30 18:19:46 -07001681 bool mKeepWakeLock; // keep wake lock while waiting for write callback
Eric Laurentbfb1b832013-01-07 09:53:42 -08001682};
1683
1684class AsyncCallbackThread : public Thread {
1685public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001686 explicit AsyncCallbackThread(const wp<PlaybackThread>& playbackThread);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001687
Eric Laurentbfb1b832013-01-07 09:53:42 -08001688 // Thread virtuals
1689 virtual bool threadLoop();
1690
1691 // RefBase
1692 virtual void onFirstRef();
1693
1694 void exit();
Eric Laurent3b4529e2013-09-05 18:09:19 -07001695 void setWriteBlocked(uint32_t sequence);
1696 void resetWriteBlocked();
1697 void setDraining(uint32_t sequence);
1698 void resetDraining();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07001699 void setAsyncError();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001700
1701private:
Eric Laurent4de95592013-09-26 15:28:21 -07001702 const wp<PlaybackThread> mPlaybackThread;
Eric Laurent3b4529e2013-09-05 18:09:19 -07001703 // mWriteAckSequence corresponds to the last write sequence passed by the offload thread via
1704 // setWriteBlocked(). The sequence is shifted one bit to the left and the lsb is used
1705 // to indicate that the callback has been received via resetWriteBlocked()
Eric Laurent4de95592013-09-26 15:28:21 -07001706 uint32_t mWriteAckSequence;
Eric Laurent3b4529e2013-09-05 18:09:19 -07001707 // mDrainSequence corresponds to the last drain sequence passed by the offload thread via
1708 // setDraining(). The sequence is shifted one bit to the left and the lsb is used
1709 // to indicate that the callback has been received via resetDraining()
Eric Laurent4de95592013-09-26 15:28:21 -07001710 uint32_t mDrainSequence;
1711 Condition mWaitWorkCV;
1712 Mutex mLock;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07001713 bool mAsyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001714};
1715
Andy Hung0c1e11e2023-07-06 20:56:16 -07001716class DuplicatingThread : public MixerThread, public IAfDuplicatingThread {
Eric Laurent81784c32012-11-19 14:55:58 -08001717public:
Andy Hung0c1e11e2023-07-06 20:56:16 -07001718 DuplicatingThread(const sp<AudioFlinger>& audioFlinger, IAfPlaybackThread* mainThread,
Eric Laurent72e3f392015-05-20 14:43:50 -07001719 audio_io_handle_t id, bool systemReady);
Andy Hung0c1e11e2023-07-06 20:56:16 -07001720 ~DuplicatingThread() override;
1721
1722 sp<IAfDuplicatingThread> asIAfDuplicatingThread() final {
1723 return sp<IAfDuplicatingThread>::fromExisting(this);
1724 }
Eric Laurent81784c32012-11-19 14:55:58 -08001725
1726 // Thread virtuals
Andy Hung0c1e11e2023-07-06 20:56:16 -07001727 void addOutputTrack(IAfPlaybackThread* thread) final;
1728 void removeOutputTrack(IAfPlaybackThread* thread) final;
1729 uint32_t waitTimeMs() const final { return mWaitTimeMs; }
Kevin Rocard069c2712018-03-29 19:09:14 -07001730
Kevin Rocardc86a7f72018-04-03 09:00:09 -07001731 void sendMetadataToBackend_l(
1732 const StreamOutHalInterface::SourceMetadata& metadata) override;
Eric Laurent81784c32012-11-19 14:55:58 -08001733protected:
1734 virtual uint32_t activeSleepTimeUs() const;
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001735 void dumpInternals_l(int fd, const Vector<String16>& args) override;
Eric Laurent81784c32012-11-19 14:55:58 -08001736
1737private:
Andy Hung920f6572022-10-06 12:09:49 -07001738 bool outputsReady();
Eric Laurent81784c32012-11-19 14:55:58 -08001739protected:
1740 // threadLoop snippets
1741 virtual void threadLoop_mix();
1742 virtual void threadLoop_sleepTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001743 virtual ssize_t threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08001744 virtual void threadLoop_standby();
1745 virtual void cacheParameters_l();
1746
1747private:
1748 // called from threadLoop, addOutputTrack, removeOutputTrack
1749 virtual void updateWaitTime_l();
1750protected:
1751 virtual void saveOutputTracks();
1752 virtual void clearOutputTracks();
1753private:
1754
1755 uint32_t mWaitTimeMs;
Andy Hung11e74242023-06-26 19:20:57 -07001756 SortedVector <sp<IAfOutputTrack>> outputTracks;
1757 SortedVector <sp<IAfOutputTrack>> mOutputTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08001758public:
1759 virtual bool hasFastMixer() const { return false; }
Andy Hung1c86ebe2018-05-29 20:29:08 -07001760 status_t threadloop_getHalTimestamp_l(
1761 ExtendedTimestamp *timestamp) const override {
1762 if (mOutputTracks.size() > 0) {
1763 // forward the first OutputTrack's kernel information for timestamp.
1764 const ExtendedTimestamp trackTimestamp =
1765 mOutputTracks[0]->getClientProxyTimestamp();
1766 if (trackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] > 0) {
1767 timestamp->mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
1768 trackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
1769 timestamp->mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
1770 trackTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
1771 return OK; // discard server timestamp - that's ignored.
1772 }
1773 }
1774 return INVALID_OPERATION;
1775 }
Eric Laurent81784c32012-11-19 14:55:58 -08001776};
1777
Eric Laurentb0463942022-12-20 16:31:10 +01001778class SpatializerThread : public MixerThread {
Eric Laurentb3f315a2021-07-13 15:09:05 +02001779public:
Eric Laurentfa0f6742021-08-17 18:39:44 +02001780 SpatializerThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurentb3f315a2021-07-13 15:09:05 +02001781 AudioStreamOut* output,
1782 audio_io_handle_t id,
1783 bool systemReady,
1784 audio_config_base_t *mixerConfig);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001785
Andy Hung3e4c8742023-06-29 21:19:25 -07001786 bool hasFastMixer() const final { return false; }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001787
Eric Laurent68a40a82022-05-03 18:15:04 +02001788 // RefBase
Andy Hung3e4c8742023-06-29 21:19:25 -07001789 void onFirstRef() final;
Eric Laurent68a40a82022-05-03 18:15:04 +02001790
Andy Hung3e4c8742023-06-29 21:19:25 -07001791 status_t setRequestedLatencyMode(audio_latency_mode_t mode) final;
Eric Laurent68a40a82022-05-03 18:15:04 +02001792
Eric Laurentb3f315a2021-07-13 15:09:05 +02001793protected:
Andy Hung3e4c8742023-06-29 21:19:25 -07001794 void checkOutputStageEffects() final;
1795 void setHalLatencyMode_l() final;
Eric Laurentb3f315a2021-07-13 15:09:05 +02001796
1797private:
Eric Laurent68a40a82022-05-03 18:15:04 +02001798 // Do not request a specific mode by default
1799 audio_latency_mode_t mRequestedLatencyMode = AUDIO_LATENCY_MODE_FREE;
1800
Andy Hung116bc262023-06-20 18:56:17 -07001801 sp<IAfEffectHandle> mFinalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02001802};
1803
Eric Laurent81784c32012-11-19 14:55:58 -08001804// record thread
Andy Hung0c1e11e2023-07-06 20:56:16 -07001805class RecordThread : public IAfRecordThread, public ThreadBase
Eric Laurent81784c32012-11-19 14:55:58 -08001806{
Andy Hung11e74242023-06-26 19:20:57 -07001807 // TODO(b/288339104) remove friends
1808 friend class PassthruPatchRecord;
1809 friend class RecordTrack;
1810 friend class ResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08001811public:
Andy Hung0c1e11e2023-07-06 20:56:16 -07001812 sp<IAfRecordThread> asIAfRecordThread() final {
1813 return sp<IAfRecordThread>::fromExisting(this);
1814 }
Eric Laurent81784c32012-11-19 14:55:58 -08001815
1816 RecordThread(const sp<AudioFlinger>& audioFlinger,
1817 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08001818 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001819 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08001820 );
Andy Hung3e4c8742023-06-29 21:19:25 -07001821 ~RecordThread() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001822
1823 // no addTrack_l ?
Andy Hung0c1e11e2023-07-06 20:56:16 -07001824 void destroyTrack_l(const sp<IAfRecordTrack>& track) final;
1825 void removeTrack_l(const sp<IAfRecordTrack>& track) final;
Eric Laurent81784c32012-11-19 14:55:58 -08001826
Eric Laurent81784c32012-11-19 14:55:58 -08001827 // Thread virtuals
Andy Hung3e4c8742023-06-29 21:19:25 -07001828 bool threadLoop() final;
1829 void preExit() final;
Eric Laurent81784c32012-11-19 14:55:58 -08001830
1831 // RefBase
Andy Hung3e4c8742023-06-29 21:19:25 -07001832 void onFirstRef() final;
Eric Laurent81784c32012-11-19 14:55:58 -08001833
Andy Hung3e4c8742023-06-29 21:19:25 -07001834 status_t initCheck() const final { return mInput == nullptr ? NO_INIT : NO_ERROR; }
Glenn Kastene198c362013-08-13 09:13:36 -07001835
Andy Hung3e4c8742023-06-29 21:19:25 -07001836 sp<MemoryDealer> readOnlyHeap() const final { return mReadOnlyHeap; }
Glenn Kastenb880f5e2014-05-07 08:43:45 -07001837
Andy Hung3e4c8742023-06-29 21:19:25 -07001838 sp<IMemory> pipeMemory() const final { return mPipeMemory; }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001839
Andy Hung0c1e11e2023-07-06 20:56:16 -07001840 sp<IAfRecordTrack> createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001841 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001842 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001843 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001844 audio_format_t format,
1845 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001846 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08001847 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001848 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07001849 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00001850 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07001851 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001852 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001853 status_t *status /*non-NULL*/,
Eric Laurentec376dc2021-04-08 20:41:22 +02001854 audio_port_handle_t portId,
Andy Hung0c1e11e2023-07-06 20:56:16 -07001855 int32_t maxSharedAudioHistoryMs) final;
Eric Laurent81784c32012-11-19 14:55:58 -08001856
Andy Hung11e74242023-06-26 19:20:57 -07001857 status_t start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08001858 AudioSystem::sync_event_t event,
Andy Hung0c1e11e2023-07-06 20:56:16 -07001859 audio_session_t triggerSession) final;
Eric Laurent81784c32012-11-19 14:55:58 -08001860
1861 // ask the thread to stop the specified track, and
1862 // return true if the caller should then do it's part of the stopping process
Andy Hung0c1e11e2023-07-06 20:56:16 -07001863 bool stop(IAfRecordTrack* recordTrack) final;
1864 AudioStreamIn* getInput() const final { return mInput; }
1865 AudioStreamIn* clearInput() final;
Eric Laurent81784c32012-11-19 14:55:58 -08001866
Andy Hung0c1e11e2023-07-06 20:56:16 -07001867 // TODO(b/288339104) Unify with IAfThreadBase
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001868 virtual sp<StreamHalInterface> stream() const;
Eric Laurent81784c32012-11-19 14:55:58 -08001869
Eric Laurent81784c32012-11-19 14:55:58 -08001870
Eric Laurent10351942014-05-08 18:49:52 -07001871 virtual bool checkForNewParameter_l(const String8& keyValuePair,
1872 status_t& status);
1873 virtual void cacheParameters_l() {}
Eric Laurent81784c32012-11-19 14:55:58 -08001874 virtual String8 getParameters(const String8& keys);
Andy Hung0c1e11e2023-07-06 20:56:16 -07001875 void ioConfigChanged(audio_io_config_event_t event, pid_t pid = 0,
1876 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final;
Eric Laurent1c333e22014-05-20 10:48:17 -07001877 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
1878 audio_patch_handle_t *handle);
1879 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle);
jiabinc52b1ff2019-10-31 17:20:42 -07001880 void updateOutDevices(const DeviceDescriptorBaseVector& outDevices) override;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02001881 void resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs) override;
Eric Laurent83b88082014-06-20 18:31:16 -07001882
Andy Hung0c1e11e2023-07-06 20:56:16 -07001883 void addPatchTrack(const sp<IAfPatchRecord>& record) final;
1884 void deletePatchTrack(const sp<IAfPatchRecord>& record) final;
Eric Laurent83b88082014-06-20 18:31:16 -07001885
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001886 void readInputParameters_l();
Andy Hung0c1e11e2023-07-06 20:56:16 -07001887 uint32_t getInputFramesLost() const final;
Eric Laurent81784c32012-11-19 14:55:58 -08001888
Andy Hung116bc262023-06-20 18:56:17 -07001889 virtual status_t addEffectChain_l(const sp<IAfEffectChain>& chain);
1890 virtual size_t removeEffectChain_l(const sp<IAfEffectChain>& chain);
Andy Hungc3d62f92019-03-14 13:38:51 -07001891 uint32_t hasAudioSession_l(audio_session_t sessionId) const override {
1892 return ThreadBase::hasAudioSession_l(sessionId, mTracks);
1893 }
Eric Laurent81784c32012-11-19 14:55:58 -08001894
1895 // Return the set of unique session IDs across all tracks.
1896 // The keys are the session IDs, and the associated values are meaningless.
1897 // FIXME replace by Set [and implement Bag/Multiset for other uses].
Glenn Kastend848eb42016-03-08 13:42:11 -08001898 KeyedVector<audio_session_t, bool> sessionIds() const;
Eric Laurent81784c32012-11-19 14:55:58 -08001899
Andy Hung068e08e2023-05-15 19:02:55 -07001900 status_t setSyncEvent(const sp<audioflinger::SyncEvent>& event) override;
1901 bool isValidSyncEvent(const sp<audioflinger::SyncEvent>& event) const override;
Eric Laurent81784c32012-11-19 14:55:58 -08001902
Andy Hung068e08e2023-05-15 19:02:55 -07001903 static void syncStartEventCallback(const wp<audioflinger::SyncEvent>& event);
Eric Laurent81784c32012-11-19 14:55:58 -08001904
Glenn Kasten9b58f632013-07-16 11:37:48 -07001905 virtual size_t frameCount() const { return mFrameCount; }
Andy Hung0c1e11e2023-07-06 20:56:16 -07001906 bool hasFastCapture() const final { return mFastCapture != 0; }
Mikhail Naganovdc769682018-05-04 15:34:08 -07001907 virtual void toAudioPortConfig(struct audio_port_config *config);
Glenn Kasten9b58f632013-07-16 11:37:48 -07001908
Eric Laurent4c415062016-06-17 16:14:16 -07001909 virtual status_t checkEffectCompatibility_l(const effect_descriptor_t *desc,
1910 audio_session_t sessionId);
1911
Andy Hungdae27702016-10-31 14:01:16 -07001912 virtual void acquireWakeLock_l() {
1913 ThreadBase::acquireWakeLock_l();
1914 mActiveTracks.updatePowerState(this, true /* force */);
1915 }
1916
Andy Hung0c1e11e2023-07-06 20:56:16 -07001917 void checkBtNrec() final;
Eric Laurentd8365c52017-07-16 15:27:05 -07001918
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001919 // Sets the UID records silence
Andy Hung0c1e11e2023-07-06 20:56:16 -07001920 void setRecordSilenced(audio_port_handle_t portId, bool silenced) final;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001921
Andy Hung0c1e11e2023-07-06 20:56:16 -07001922 status_t getActiveMicrophones(
1923 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const final;
1924 status_t setPreferredMicrophoneDirection(audio_microphone_direction_t direction) final;
1925 status_t setPreferredMicrophoneFieldDimension(float zoom) final;
Paul McLean03a6e6a2018-12-04 10:54:13 -07001926
Vlad Popa7e81cea2023-01-19 16:34:16 +01001927 MetadataUpdate updateMetadata_l() override;
Kevin Rocard069c2712018-03-29 19:09:14 -07001928
Andy Hung0c1e11e2023-07-06 20:56:16 -07001929 bool fastTrackAvailable() const final { return mFastTrackAvail; }
1930 void setFastTrackAvailable(bool available) final { mFastTrackAvail = available; }
jiabin01c8f562018-07-19 17:47:28 -07001931
Andy Hungc8fddf32018-08-08 18:32:37 -07001932 bool isTimestampCorrectionEnabled() const override {
1933 // checks popcount for exactly one device.
Atneya Nair497fff12022-01-18 16:23:04 -05001934 // Is currently disabled. Before enabling,
1935 // verify compressed record timestamps.
jiabinc52b1ff2019-10-31 17:20:42 -07001936 return audio_is_input_device(mTimestampCorrectedDevice)
1937 && inDeviceType() == mTimestampCorrectedDevice;
Andy Hungc8fddf32018-08-08 18:32:37 -07001938 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001939
Andy Hung0c1e11e2023-07-06 20:56:16 -07001940 status_t shareAudioHistory(const std::string& sharedAudioPackageName,
Eric Laurentec376dc2021-04-08 20:41:22 +02001941 audio_session_t sharedSessionId = AUDIO_SESSION_NONE,
Andy Hung0c1e11e2023-07-06 20:56:16 -07001942 int64_t sharedAudioStartMs = -1) final;
Eric Laurentec376dc2021-04-08 20:41:22 +02001943 status_t shareAudioHistory_l(const std::string& sharedAudioPackageName,
1944 audio_session_t sharedSessionId = AUDIO_SESSION_NONE,
1945 int64_t sharedAudioStartMs = -1);
Andy Hung0c1e11e2023-07-06 20:56:16 -07001946 void resetAudioHistory_l() final;
Eric Laurentec376dc2021-04-08 20:41:22 +02001947
Andy Hung3e4c8742023-06-29 21:19:25 -07001948 bool isStreamInitialized() const final {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001949 return !(mInput == nullptr || mInput->stream == nullptr);
1950 }
1951
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001952protected:
1953 void dumpInternals_l(int fd, const Vector<String16>& args) override;
1954 void dumpTracks_l(int fd, const Vector<String16>& args) override;
1955
Eric Laurent81784c32012-11-19 14:55:58 -08001956private:
Eric Laurent81784c32012-11-19 14:55:58 -08001957 // Enter standby if not already in standby, and set mStandby flag
Glenn Kasten93e471f2013-08-19 08:40:07 -07001958 void standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08001959
1960 // Call the HAL standby method unconditionally, and don't change mStandby flag
Glenn Kastene198c362013-08-13 09:13:36 -07001961 void inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08001962
Eric Laurentd8365c52017-07-16 15:27:05 -07001963 void checkBtNrec_l();
1964
Eric Laurentec376dc2021-04-08 20:41:22 +02001965 int32_t getOldestFront_l();
1966 void updateFronts_l(int32_t offset);
1967
Eric Laurent81784c32012-11-19 14:55:58 -08001968 AudioStreamIn *mInput;
Mikhail Naganov2534b382019-09-25 13:05:02 -07001969 Source *mSource;
Andy Hung11e74242023-06-26 19:20:57 -07001970 SortedVector <sp<IAfRecordTrack>> mTracks;
Glenn Kasten2b806402013-11-20 16:37:38 -08001971 // mActiveTracks has dual roles: it indicates the current active track(s), and
Eric Laurent81784c32012-11-19 14:55:58 -08001972 // is used together with mStartStopCond to indicate start()/stop() progress
Andy Hung11e74242023-06-26 19:20:57 -07001973 ActiveTracks<IAfRecordTrack> mActiveTracks;
Andy Hungdae27702016-10-31 14:01:16 -07001974
Eric Laurent81784c32012-11-19 14:55:58 -08001975 Condition mStartStopCond;
Glenn Kasten9b58f632013-07-16 11:37:48 -07001976
Glenn Kasten85948432013-08-19 12:09:05 -07001977 // resampler converts input at HAL Hz to output at AudioRecord client Hz
Glenn Kasten1b291842016-07-18 14:55:21 -07001978 void *mRsmpInBuffer; // size = mRsmpInFramesOA
Glenn Kasten85948432013-08-19 12:09:05 -07001979 size_t mRsmpInFrames; // size of resampler input in frames
1980 size_t mRsmpInFramesP2;// size rounded up to a power-of-2
Glenn Kasten1b291842016-07-18 14:55:21 -07001981 size_t mRsmpInFramesOA;// mRsmpInFramesP2 + over-allocation
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001982
1983 // rolling index that is never cleared
Glenn Kasten85948432013-08-19 12:09:05 -07001984 int32_t mRsmpInRear; // last filled frame + 1
Glenn Kasten85948432013-08-19 12:09:05 -07001985
Eric Laurent81784c32012-11-19 14:55:58 -08001986 // For dumpsys
Glenn Kastenb880f5e2014-05-07 08:43:45 -07001987 const sp<MemoryDealer> mReadOnlyHeap;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001988
1989 // one-time initialization, no locks required
Glenn Kastenb187de12014-12-30 08:18:15 -08001990 sp<FastCapture> mFastCapture; // non-0 if there is also
1991 // a fast capture
Eric Laurent72e3f392015-05-20 14:43:50 -07001992
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001993 // FIXME audio watchdog thread
1994
1995 // contents are not guaranteed to be consistent, no locks required
1996 FastCaptureDumpState mFastCaptureDumpState;
1997#ifdef STATE_QUEUE_DUMP
1998 // FIXME StateQueue observer and mutator dump fields
1999#endif
2000 // FIXME audio watchdog dump
2001
2002 // accessible only within the threadLoop(), no locks required
2003 // mFastCapture->sq() // for mutating and pushing state
2004 int32_t mFastCaptureFutex; // for cold idle
2005
2006 // The HAL input source is treated as non-blocking,
2007 // but current implementation is blocking
2008 sp<NBAIO_Source> mInputSource;
2009 // The source for the normal capture thread to read from: mInputSource or mPipeSource
2010 sp<NBAIO_Source> mNormalSource;
2011 // If a fast capture is present, the non-blocking pipe sink written to by fast capture,
2012 // otherwise clear
2013 sp<NBAIO_Sink> mPipeSink;
2014 // If a fast capture is present, the non-blocking pipe source read by normal thread,
2015 // otherwise clear
2016 sp<NBAIO_Source> mPipeSource;
2017 // Depth of pipe from fast capture to normal thread and fast clients, always power of 2
2018 size_t mPipeFramesP2;
2019 // If a fast capture is present, the Pipe as IMemory, otherwise clear
2020 sp<IMemory> mPipeMemory;
2021
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002022 // TODO: add comment and adjust size as needed
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07002023 static const size_t kFastCaptureLogSize = 4 * 1024;
2024 sp<NBLog::Writer> mFastCaptureNBLogWriter;
2025
2026 bool mFastTrackAvail; // true if fast track available
Eric Laurentd8365c52017-07-16 15:27:05 -07002027 // common state to all record threads
2028 std::atomic_bool mBtNrecSuspended;
Andy Hung6427e442018-08-09 12:51:02 -07002029
2030 int64_t mFramesRead = 0; // continuous running counter.
jiabinc52b1ff2019-10-31 17:20:42 -07002031
2032 DeviceDescriptorBaseVector mOutDevices;
Eric Laurentec376dc2021-04-08 20:41:22 +02002033
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02002034 int32_t mMaxSharedAudioHistoryMs = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02002035 std::string mSharedAudioPackageName = {};
Eric Laurent2407ce32021-04-26 14:56:03 +02002036 int32_t mSharedAudioStartFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02002037 audio_session_t mSharedAudioSessionId = AUDIO_SESSION_NONE;
Eric Laurent81784c32012-11-19 14:55:58 -08002038};
Eric Laurent6acd1d42017-01-04 14:23:29 -08002039
Andy Hung765de282023-07-07 15:58:48 -07002040class MmapThread : public ThreadBase, public virtual IAfMmapThread
Eric Laurent6acd1d42017-01-04 14:23:29 -08002041{
2042 public:
Eric Laurent6acd1d42017-01-04 14:23:29 -08002043 MmapThread(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -07002044 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady,
Andy Hungcf10d742020-04-28 15:38:24 -07002045 bool isOut);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002046
Andy Hung765de282023-07-07 15:58:48 -07002047 void configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08002048 audio_stream_type_t streamType,
2049 audio_session_t sessionId,
2050 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07002051 audio_port_handle_t deviceId,
Andy Hung765de282023-07-07 15:58:48 -07002052 audio_port_handle_t portId) override;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002053
Andy Hung765de282023-07-07 15:58:48 -07002054 void disconnect() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002055
Andy Hung3e4c8742023-06-29 21:19:25 -07002056 // MmapStreamInterface for adapter.
Andy Hung765de282023-07-07 15:58:48 -07002057 status_t createMmapBuffer(int32_t minSizeFrames, struct audio_mmap_buffer_info* info) final;
2058 status_t getMmapPosition(struct audio_mmap_position* position) const override;
2059 status_t start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07002060 const audio_attributes_t *attr,
Andy Hung765de282023-07-07 15:58:48 -07002061 audio_port_handle_t* handle) final;
2062 status_t stop(audio_port_handle_t handle) final;
2063 status_t standby() final;
2064 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) const = 0;
2065 status_t reportData(const void* buffer, size_t frameCount) override;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002066
2067 // RefBase
Andy Hung3e4c8742023-06-29 21:19:25 -07002068 void onFirstRef() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002069
2070 // Thread virtuals
Andy Hung3e4c8742023-06-29 21:19:25 -07002071 bool threadLoop() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002072
Andy Hung3e4c8742023-06-29 21:19:25 -07002073 // Not in ThreadBase
2074 virtual void threadLoop_exit() final;
2075 virtual void threadLoop_standby() final;
2076 virtual bool shouldStandby_l() final { return false; }
2077 virtual status_t exitStandby_l() REQUIRES(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002078
Andy Hung3e4c8742023-06-29 21:19:25 -07002079 status_t initCheck() const final { return mHalStream == nullptr ? NO_INIT : NO_ERROR; }
2080 size_t frameCount() const final { return mFrameCount; }
2081 bool checkForNewParameter_l(const String8& keyValuePair, status_t& status) final;
2082 String8 getParameters(const String8& keys) final;
2083 void ioConfigChanged(audio_io_config_event_t event, pid_t pid = 0,
2084 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002085 void readHalParameters_l();
Andy Hung3e4c8742023-06-29 21:19:25 -07002086 void cacheParameters_l() final {}
2087 status_t createAudioPatch_l(
2088 const struct audio_patch* patch, audio_patch_handle_t* handle) final;
2089 status_t releaseAudioPatch_l(const audio_patch_handle_t handle) final;
2090 void toAudioPortConfig(struct audio_port_config* config) override;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002091
Andy Hung3e4c8742023-06-29 21:19:25 -07002092 sp<StreamHalInterface> stream() const final { return mHalStream; }
2093 status_t addEffectChain_l(const sp<IAfEffectChain>& chain) final;
2094 size_t removeEffectChain_l(const sp<IAfEffectChain>& chain) final;
2095 status_t checkEffectCompatibility_l(
2096 const effect_descriptor_t *desc, audio_session_t sessionId) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002097
Andy Hung3e4c8742023-06-29 21:19:25 -07002098 uint32_t hasAudioSession_l(audio_session_t sessionId) const override {
Andy Hungc3d62f92019-03-14 13:38:51 -07002099 // Note: using mActiveTracks as no mTracks here.
2100 return ThreadBase::hasAudioSession_l(sessionId, mActiveTracks);
2101 }
Andy Hung3e4c8742023-06-29 21:19:25 -07002102 status_t setSyncEvent(const sp<audioflinger::SyncEvent>& event) final;
2103 bool isValidSyncEvent(const sp<audioflinger::SyncEvent>& event) const final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002104
Andy Hung3e4c8742023-06-29 21:19:25 -07002105 virtual void checkSilentMode_l() {} // cannot be const (RecordThread)
2106 virtual void processVolume_l() {}
Eric Laurent6acd1d42017-01-04 14:23:29 -08002107 void checkInvalidTracks_l();
2108
Andy Hung3e4c8742023-06-29 21:19:25 -07002109 // Not in ThreadBase
2110 virtual audio_stream_type_t streamType() const { return AUDIO_STREAM_DEFAULT; }
2111 virtual void invalidateTracks(audio_stream_type_t /* streamType */) {}
Andy Hung765de282023-07-07 15:58:48 -07002112 void invalidateTracks(std::set<audio_port_handle_t>& /* portIds */) override {}
Eric Laurent6acd1d42017-01-04 14:23:29 -08002113
Eric Laurent331679c2018-04-16 17:03:16 -07002114 // Sets the UID records silence
Andy Hung765de282023-07-07 15:58:48 -07002115 void setRecordSilenced(
2116 audio_port_handle_t /* portId */, bool /* silenced */) override {}
Eric Laurent331679c2018-04-16 17:03:16 -07002117
Andy Hung3e4c8742023-06-29 21:19:25 -07002118 bool isStreamInitialized() const override { return false; }
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002119
jiabin09609032022-06-15 19:26:01 +00002120 void setClientSilencedState_l(audio_port_handle_t portId, bool silenced) {
2121 mClientSilencedStates[portId] = silenced;
2122 }
2123
2124 size_t eraseClientSilencedState_l(audio_port_handle_t portId) {
2125 return mClientSilencedStates.erase(portId);
2126 }
2127
2128 bool isClientSilenced_l(audio_port_handle_t portId) const {
2129 const auto it = mClientSilencedStates.find(portId);
2130 return it != mClientSilencedStates.end() ? it->second : false;
2131 }
2132
2133 void setClientSilencedIfExists_l(audio_port_handle_t portId, bool silenced) {
2134 const auto it = mClientSilencedStates.find(portId);
2135 if (it != mClientSilencedStates.end()) {
2136 it->second = silenced;
2137 }
2138 }
2139
Eric Laurent6acd1d42017-01-04 14:23:29 -08002140 protected:
Andy Hung3e4c8742023-06-29 21:19:25 -07002141 void dumpInternals_l(int fd, const Vector<String16>& args) override;
2142 void dumpTracks_l(int fd, const Vector<String16>& args) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002143
jiabinc52b1ff2019-10-31 17:20:42 -07002144 /**
2145 * @brief mDeviceId current device port unique identifier
2146 */
2147 audio_port_handle_t mDeviceId = AUDIO_PORT_HANDLE_NONE;
2148
Eric Laurent6acd1d42017-01-04 14:23:29 -08002149 audio_attributes_t mAttr;
2150 audio_session_t mSessionId;
2151 audio_port_handle_t mPortId;
2152
Phil Burk7f6b40d2017-02-09 13:18:38 -08002153 wp<MmapStreamCallback> mCallback;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002154 sp<StreamHalInterface> mHalStream;
2155 sp<DeviceHalInterface> mHalDevice;
2156 AudioHwDevice* const mAudioHwDev;
Andy Hung11e74242023-06-26 19:20:57 -07002157 ActiveTracks<IAfMmapTrack> mActiveTracks;
Eric Laurent67f97292018-04-20 18:05:41 -07002158 float mHalVolFloat;
jiabin09609032022-06-15 19:26:01 +00002159 std::map<audio_port_handle_t, bool> mClientSilencedStates;
Eric Laurent331679c2018-04-16 17:03:16 -07002160
2161 int32_t mNoCallbackWarningCount;
2162 static constexpr int32_t kMaxNoCallbackWarnings = 5;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002163};
2164
Andy Hung765de282023-07-07 15:58:48 -07002165class MmapPlaybackThread : public MmapThread, public IAfMmapPlaybackThread,
2166 public virtual VolumeInterface {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002167public:
2168 MmapPlaybackThread(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07002169 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002170
Andy Hung765de282023-07-07 15:58:48 -07002171 sp<IAfMmapPlaybackThread> asIAfMmapPlaybackThread() final {
2172 return sp<IAfMmapPlaybackThread>::fromExisting(this);
2173 }
2174
Andy Hung3e4c8742023-06-29 21:19:25 -07002175 void configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08002176 audio_stream_type_t streamType,
2177 audio_session_t sessionId,
2178 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07002179 audio_port_handle_t deviceId,
Andy Hung3e4c8742023-06-29 21:19:25 -07002180 audio_port_handle_t portId) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002181
Andy Hung765de282023-07-07 15:58:48 -07002182 AudioStreamOut* clearOutput() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002183
2184 // VolumeInterface
Andy Hung3e4c8742023-06-29 21:19:25 -07002185 void setMasterVolume(float value) final;
2186 void setMasterBalance(float /* value */) final {} // Needs implementation?
2187 void setMasterMute(bool muted) final;
2188 void setStreamVolume(audio_stream_type_t stream, float value) final;
2189 void setStreamMute(audio_stream_type_t stream, bool muted) final;
2190 float streamVolume(audio_stream_type_t stream) const final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002191
2192 void setMasterMute_l(bool muted) { mMasterMute = muted; }
2193
Andy Hung3e4c8742023-06-29 21:19:25 -07002194 void invalidateTracks(audio_stream_type_t streamType) final;
2195 void invalidateTracks(std::set<audio_port_handle_t>& portIds) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002196
Andy Hung3e4c8742023-06-29 21:19:25 -07002197 audio_stream_type_t streamType() const final { return mStreamType; }
2198 void checkSilentMode_l() final;
2199 void processVolume_l() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002200
Andy Hung3e4c8742023-06-29 21:19:25 -07002201 MetadataUpdate updateMetadata_l() final;
Kevin Rocard069c2712018-03-29 19:09:14 -07002202
Andy Hung3e4c8742023-06-29 21:19:25 -07002203 void toAudioPortConfig(struct audio_port_config* config) final;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07002204
Andy Hung3e4c8742023-06-29 21:19:25 -07002205 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) const final;
jiabinb7d8c5a2020-08-26 17:24:52 -07002206
Andy Hung3e4c8742023-06-29 21:19:25 -07002207 bool isStreamInitialized() const final {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002208 return !(mOutput == nullptr || mOutput->stream == nullptr);
2209 }
2210
Andy Hung3e4c8742023-06-29 21:19:25 -07002211 status_t reportData(const void* buffer, size_t frameCount) final;
jiabinfc791ee2023-02-15 19:43:40 +00002212
Andy Hung3e4c8742023-06-29 21:19:25 -07002213 void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) final;
2214 void stopMelComputation_l() final;
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002215
Eric Laurent6acd1d42017-01-04 14:23:29 -08002216protected:
Andy Hung3e4c8742023-06-29 21:19:25 -07002217 void dumpInternals_l(int fd, const Vector<String16>& args) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002218
2219 audio_stream_type_t mStreamType;
2220 float mMasterVolume;
2221 float mStreamVolume;
2222 bool mMasterMute;
2223 bool mStreamMute;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002224 AudioStreamOut* mOutput;
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002225
2226 mediautils::atomic_sp<audio_utils::MelProcessor> mMelProcessor;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002227};
2228
Andy Hung765de282023-07-07 15:58:48 -07002229class MmapCaptureThread : public MmapThread, public IAfMmapCaptureThread
Eric Laurent6acd1d42017-01-04 14:23:29 -08002230{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002231public:
2232 MmapCaptureThread(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07002233 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002234
Andy Hung765de282023-07-07 15:58:48 -07002235 sp<IAfMmapCaptureThread> asIAfMmapCaptureThread() final {
2236 return sp<IAfMmapCaptureThread>::fromExisting(this);
2237 }
2238
2239 AudioStreamIn* clearInput() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002240
Andy Hung3e4c8742023-06-29 21:19:25 -07002241 status_t exitStandby_l() REQUIRES(mLock) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002242
Andy Hung3e4c8742023-06-29 21:19:25 -07002243 MetadataUpdate updateMetadata_l() final;
2244 void processVolume_l() final;
2245 void setRecordSilenced(audio_port_handle_t portId, bool silenced) final;
Kevin Rocard069c2712018-03-29 19:09:14 -07002246
Andy Hung3e4c8742023-06-29 21:19:25 -07002247 void toAudioPortConfig(struct audio_port_config* config) final;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07002248
Andy Hung3e4c8742023-06-29 21:19:25 -07002249 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) const final;
jiabinb7d8c5a2020-08-26 17:24:52 -07002250
Andy Hung3e4c8742023-06-29 21:19:25 -07002251 bool isStreamInitialized() const final {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002252 return !(mInput == nullptr || mInput->stream == nullptr);
2253 }
2254
Eric Laurent6acd1d42017-01-04 14:23:29 -08002255protected:
2256
2257 AudioStreamIn* mInput;
2258};
jiabinc658e452022-10-21 20:52:21 +00002259
2260class BitPerfectThread : public MixerThread {
2261public:
2262 BitPerfectThread(const sp<AudioFlinger>& audioflinger, AudioStreamOut *output,
2263 audio_io_handle_t id, bool systemReady);
2264
2265protected:
Andy Hung3e4c8742023-06-29 21:19:25 -07002266 mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove) final;
2267 void threadLoop_mix() final;
jiabinc658e452022-10-21 20:52:21 +00002268
2269private:
2270 bool mIsBitPerfect;
jiabin76d94692022-12-15 21:51:21 +00002271 float mVolumeLeft = 0.f;
2272 float mVolumeRight = 0.f;
jiabinc658e452022-10-21 20:52:21 +00002273};
Andy Hunga6426302023-06-23 19:27:19 -07002274
Andy Hung4b17e882023-07-07 13:47:37 -07002275} // namespace android