blob: 1dfd7857076af3b4a06336d3d935950947da2a34 [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
18#ifndef INCLUDING_FROM_AUDIOFLINGER_H
19 #error This header file should only be included from AudioFlinger.h
20#endif
21
Andy Hung116bc262023-06-20 18:56:17 -070022public: // TODO(b/288339104) extract out of AudioFlinger class
Andy Hung440901d2023-06-29 21:19:25 -070023
24class AsyncCallbackThread;
25
26class ThreadBase : public virtual IAfThreadBase, public Thread {
Andy Hung8d31fd22023-06-26 19:20:57 -070027 // TODO(b/288339104) remove friends
28 friend class RecordTrack;
29 friend class Track;
30 friend class TrackBase;
Eric Laurent81784c32012-11-19 14:55:58 -080031public:
Glenn Kasten97b7b752014-09-28 13:04:24 -070032 static const char *threadTypeToString(type_t type);
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 Hung440901d2023-06-29 21:19:25 -070036 ~ThreadBase() override;
Eric Laurent81784c32012-11-19 14:55:58 -080037
Andy Hung440901d2023-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 Hung440901d2023-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 Hung440901d2023-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; }
297 uint32_t latency_l() const override { return 0; }
298 void setVolumeForOutput_l(float /* left */, float /* right */) const override {}
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700299
300 // Return's the HAL's frame count i.e. fast mixer buffer size.
Andy Hung440901d2023-06-29 21:19:25 -0700301 size_t frameCountHAL() const final { return mFrameCount; }
302 size_t frameSize() const final { return mFrameSize; }
Eric Laurent81784c32012-11-19 14:55:58 -0800303
304 // Should be "virtual status_t requestExitAndWait()" and override same
305 // method in Thread, but Thread::requestExitAndWait() is not yet virtual.
Andy Hung440901d2023-06-29 21:19:25 -0700306 void exit() final;
307 status_t setParameters(const String8& keyValuePairs) final;
308
Eric Laurent10351942014-05-08 18:49:52 -0700309 // sendConfigEvent_l() must be called with ThreadBase::mLock held
310 // Can temporarily release the lock if waiting for a reply from
311 // processConfigEvents_l().
Andy Hung440901d2023-06-29 21:19:25 -0700312 status_t sendConfigEvent_l(sp<ConfigEvent>& event);
313 void sendIoConfigEvent(audio_io_config_event_t event, pid_t pid = 0,
314 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final;
315 void sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid = 0,
316 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final;
317 void sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp) final;
318 void sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio, bool forApp) final;
319 status_t sendSetParameterConfigEvent_l(const String8& keyValuePair) final;
320 status_t sendCreateAudioPatchConfigEvent(const struct audio_patch* patch,
321 audio_patch_handle_t* handle) final;
322 status_t sendReleaseAudioPatchConfigEvent(audio_patch_handle_t handle) final;
323 status_t sendUpdateOutDeviceConfigEvent(
324 const DeviceDescriptorBaseVector& outDevices) final;
325 void sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs) final;
326 void sendCheckOutputStageEffectsEvent() final;
327 void sendCheckOutputStageEffectsEvent_l() final;
328 void sendHalLatencyModesChangedEvent_l() final;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200329
Andy Hung440901d2023-06-29 21:19:25 -0700330 void processConfigEvents_l() final;
331 void setCheckOutputStageEffects() override {}
332 void updateOutDevices(const DeviceDescriptorBaseVector& outDevices) override;
333 void toAudioPortConfig(struct audio_port_config* config) override;
334 void resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs) override;
Eric Laurent1c333e22014-05-20 10:48:17 -0700335
Andy Hung440901d2023-06-29 21:19:25 -0700336 // see note at declaration of mStandby, mOutDevice and mInDevice
337 bool inStandby() const override { return mStandby; }
338 const DeviceTypeSet outDeviceTypes() const final {
339 return getAudioDeviceTypes(mOutDeviceTypeAddrs);
340 }
341 audio_devices_t inDeviceType() const final { return mInDeviceTypeAddr.mType; }
342 DeviceTypeSet getDeviceTypes() const final {
343 return isOutput() ? outDeviceTypes() : DeviceTypeSet({inDeviceType()});
344 }
Eric Laurent81784c32012-11-19 14:55:58 -0800345
Andy Hung440901d2023-06-29 21:19:25 -0700346 const AudioDeviceTypeAddrVector& outDeviceTypeAddrs() const final {
347 return mOutDeviceTypeAddrs;
348 }
349 const AudioDeviceTypeAddr& inDeviceTypeAddr() const final {
350 return mInDeviceTypeAddr;
351 }
Andy Hung293558a2017-03-21 12:19:20 -0700352
Andy Hung440901d2023-06-29 21:19:25 -0700353 bool isOutput() const final { return mIsOut; }
jiabin8f278ee2019-11-11 12:16:27 -0800354
Andy Hung440901d2023-06-29 21:19:25 -0700355 bool isOffloadOrMmap() const final {
356 switch (mType) {
357 case OFFLOAD:
358 case MMAP_PLAYBACK:
359 case MMAP_CAPTURE:
360 return true;
361 default:
362 return false;
363 }
364 }
Eric Laurent81784c32012-11-19 14:55:58 -0800365
Andy Hung440901d2023-06-29 21:19:25 -0700366 sp<IAfEffectHandle> createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -0700367 const sp<Client>& client,
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700368 const sp<media::IEffectClient>& effectClient,
Eric Laurent81784c32012-11-19 14:55:58 -0800369 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -0800370 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800371 effect_descriptor_t *desc,
372 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -0800373 status_t *status /*non-NULL*/,
Eric Laurent2fe0acd2020-03-13 14:30:46 -0700374 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +0200375 bool probe,
Andy Hung440901d2023-06-29 21:19:25 -0700376 bool notifyFramesProcessed) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800377
378 // return values for hasAudioSession (bit field)
379 enum effect_state {
380 EFFECT_SESSION = 0x1, // the audio session corresponds to at least one
381 // effect
Eric Laurent4c415062016-06-17 16:14:16 -0700382 TRACK_SESSION = 0x2, // the audio session corresponds to at least one
Eric Laurent81784c32012-11-19 14:55:58 -0800383 // track
Eric Laurentb62d0362021-10-26 17:40:18 +0200384 FAST_SESSION = 0x4, // the audio session corresponds to at least one
Eric Laurent4c415062016-06-17 16:14:16 -0700385 // fast track
jiabinc658e452022-10-21 20:52:21 +0000386 SPATIALIZED_SESSION = 0x8, // the audio session corresponds to at least one
387 // spatialized track
388 BIT_PERFECT_SESSION = 0x10 // the audio session corresponds to at least one
389 // bit-perfect track
Eric Laurent81784c32012-11-19 14:55:58 -0800390 };
391
Andy Hung440901d2023-06-29 21:19:25 -0700392 // get effect chain corresponding to session Id.
393 sp<IAfEffectChain> getEffectChain(audio_session_t sessionId) const final;
394 // same as getEffectChain() but must be called with ThreadBase mutex locked
395 sp<IAfEffectChain> getEffectChain_l(audio_session_t sessionId) const final;
396 std::vector<int> getEffectIds_l(audio_session_t sessionId) const final;
397
Eric Laurent81784c32012-11-19 14:55:58 -0800398 // lock all effect chains Mutexes. Must be called before releasing the
399 // ThreadBase mutex before processing the mixer and effects. This guarantees the
400 // integrity of the chains during the process.
401 // Also sets the parameter 'effectChains' to current value of mEffectChains.
Andy Hung440901d2023-06-29 21:19:25 -0700402 void lockEffectChains_l(Vector<sp<IAfEffectChain>>& effectChains) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800403 // unlock effect chains after process
Andy Hung440901d2023-06-29 21:19:25 -0700404 void unlockEffectChains(const Vector<sp<IAfEffectChain>>& effectChains) final;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800405 // get a copy of mEffectChains vector
Andy Hung440901d2023-06-29 21:19:25 -0700406 Vector<sp<IAfEffectChain>> getEffectChains_l() const final { return mEffectChains; };
Eric Laurent81784c32012-11-19 14:55:58 -0800407 // set audio mode to all effect chains
Andy Hung440901d2023-06-29 21:19:25 -0700408 void setMode(audio_mode_t mode) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800409 // get effect module with corresponding ID on specified audio session
Andy Hung440901d2023-06-29 21:19:25 -0700410 sp<IAfEffectModule> getEffect(audio_session_t sessionId, int effectId) const final;
411 sp<IAfEffectModule> getEffect_l(audio_session_t sessionId, int effectId) const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800412 // add and effect module. Also creates the effect chain is none exists for
Eric Laurent6c796322019-04-09 14:13:17 -0700413 // the effects audio session. Only called in a context of moving an effect
414 // from one thread to another
Andy Hung440901d2023-06-29 21:19:25 -0700415 status_t addEffect_l(const sp<IAfEffectModule>& effect) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800416 // remove and effect module. Also removes the effect chain is this was the last
417 // effect
Andy Hung440901d2023-06-29 21:19:25 -0700418 void removeEffect_l(const sp<IAfEffectModule>& effect, bool release = false) final;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -0800419 // disconnect an effect handle from module and destroy module if last handle
Andy Hung440901d2023-06-29 21:19:25 -0700420 void disconnectEffectHandle(IAfEffectHandle* handle, bool unpinIfLast) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800421 // detach all tracks connected to an auxiliary effect
Andy Hung440901d2023-06-29 21:19:25 -0700422 void detachAuxEffect_l(int /* effectId */) override {}
423 // TODO(b/288339104) - remove hasAudioSession_l below.
424 uint32_t hasAudioSession_l(audio_session_t sessionId) const override = 0;
425 uint32_t hasAudioSession(audio_session_t sessionId) const final {
Eric Laurent4c415062016-06-17 16:14:16 -0700426 Mutex::Autolock _l(mLock);
427 return hasAudioSession_l(sessionId);
428 }
429
Andy Hungc3d62f92019-03-14 13:38:51 -0700430 template <typename T>
431 uint32_t hasAudioSession_l(audio_session_t sessionId, const T& tracks) const {
432 uint32_t result = 0;
433 if (getEffectChain_l(sessionId) != 0) {
434 result = EFFECT_SESSION;
435 }
436 for (size_t i = 0; i < tracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -0700437 const sp<IAfTrackBase>& track = tracks[i];
Andy Hungc3d62f92019-03-14 13:38:51 -0700438 if (sessionId == track->sessionId()
439 && !track->isInvalid() // not yet removed from tracks.
440 && !track->isTerminated()) {
441 result |= TRACK_SESSION;
442 if (track->isFastTrack()) {
443 result |= FAST_SESSION; // caution, only represents first track.
444 }
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200445 if (track->isSpatialized()) {
Eric Laurentb62d0362021-10-26 17:40:18 +0200446 result |= SPATIALIZED_SESSION; // caution, only first track.
447 }
jiabinc658e452022-10-21 20:52:21 +0000448 if (track->isBitPerfect()) {
449 result |= BIT_PERFECT_SESSION;
450 }
Andy Hungc3d62f92019-03-14 13:38:51 -0700451 break;
452 }
453 }
454 return result;
455 }
456
Eric Laurent81784c32012-11-19 14:55:58 -0800457 // the value returned by default implementation is not important as the
458 // strategy is only meaningful for PlaybackThread which implements this method
Andy Hung440901d2023-06-29 21:19:25 -0700459 product_strategy_t getStrategyForSession_l(
460 audio_session_t /* sessionId */) const override {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800461 return static_cast<product_strategy_t>(0);
462 }
Eric Laurent81784c32012-11-19 14:55:58 -0800463
Eric Laurent81784c32012-11-19 14:55:58 -0800464 // check if some effects must be suspended/restored when an effect is enabled
465 // or disabled
Andy Hung440901d2023-06-29 21:19:25 -0700466 void checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -0800467 audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -0700468 bool threadLocked) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800469
Eric Laurent81784c32012-11-19 14:55:58 -0800470
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700471 // Return a reference to a per-thread heap which can be used to allocate IMemory
472 // objects that will be read-only to client processes, read/write to mediaserver,
473 // and shared by all client processes of the thread.
474 // The heap is per-thread rather than common across all threads, because
475 // clients can't be trusted not to modify the offset of the IMemory they receive.
476 // If a thread does not have such a heap, this method returns 0.
Andy Hung440901d2023-06-29 21:19:25 -0700477 sp<MemoryDealer> readOnlyHeap() const override { return nullptr; }
Eric Laurent81784c32012-11-19 14:55:58 -0800478
Andy Hung440901d2023-06-29 21:19:25 -0700479 sp<IMemory> pipeMemory() const override { return nullptr; }
Glenn Kasten6181ffd2014-05-13 10:41:52 -0700480
Andy Hung440901d2023-06-29 21:19:25 -0700481 void systemReady() final;
Eric Laurent72e3f392015-05-20 14:43:50 -0700482
Andy Hung440901d2023-06-29 21:19:25 -0700483 void broadcast_l() final;
Eric Laurent4c415062016-06-17 16:14:16 -0700484
Andy Hung440901d2023-06-29 21:19:25 -0700485 bool isTimestampCorrectionEnabled() const override { return false; }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800486
Andy Hung440901d2023-06-29 21:19:25 -0700487 bool isMsdDevice() const final { return mIsMsdDevice; }
Andy Hungc8fddf32018-08-08 18:32:37 -0700488
Andy Hung440901d2023-06-29 21:19:25 -0700489 void dump(int fd, const Vector<String16>& args) override;
Andy Hungdc099c22018-09-18 13:46:39 -0700490
Andy Hungd0979812019-02-21 15:51:44 -0800491 // deliver stats to mediametrics.
Andy Hung440901d2023-06-29 21:19:25 -0700492 void sendStatistics(bool force) final;
Andy Hungd0979812019-02-21 15:51:44 -0800493
Andy Hung440901d2023-06-29 21:19:25 -0700494 Mutex& mutex() const final {
495 return mLock;
496 }
Eric Laurent81784c32012-11-19 14:55:58 -0800497 mutable Mutex mLock;
498
Andy Hung440901d2023-06-29 21:19:25 -0700499 void onEffectEnable(const sp<IAfEffectModule>& effect) final;
500 void onEffectDisable() final;
Eric Laurent6b446ce2019-12-13 10:56:31 -0800501
jiabineb3bda02020-06-30 14:07:03 -0700502 // invalidateTracksForAudioSession_l must be called with holding mLock.
Andy Hung440901d2023-06-29 21:19:25 -0700503 void invalidateTracksForAudioSession_l(audio_session_t /* sessionId */) const override {}
jiabineb3bda02020-06-30 14:07:03 -0700504 // Invalidate all the tracks with the given audio session.
Andy Hung440901d2023-06-29 21:19:25 -0700505 void invalidateTracksForAudioSession(audio_session_t sessionId) const final {
jiabineb3bda02020-06-30 14:07:03 -0700506 Mutex::Autolock _l(mLock);
507 invalidateTracksForAudioSession_l(sessionId);
508 }
509
510 template <typename T>
511 void invalidateTracksForAudioSession_l(audio_session_t sessionId,
512 const T& tracks) const {
513 for (size_t i = 0; i < tracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -0700514 const sp<IAfTrackBase>& track = tracks[i];
jiabineb3bda02020-06-30 14:07:03 -0700515 if (sessionId == track->sessionId()) {
516 track->invalidate();
517 }
518 }
519 }
520
Andy Hung440901d2023-06-29 21:19:25 -0700521 void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) override;
522 void stopMelComputation_l() override;
Vlad Popa6fbbfbf2023-02-22 15:05:43 +0100523
Eric Laurent81784c32012-11-19 14:55:58 -0800524protected:
525
526 // entry describing an effect being suspended in mSuspendedSessions keyed vector
527 class SuspendedSessionDesc : public RefBase {
528 public:
529 SuspendedSessionDesc() : mRefCount(0) {}
530
531 int mRefCount; // number of active suspend requests
532 effect_uuid_t mType; // effect type UUID
533 };
534
Andy Hungdae27702016-10-31 14:01:16 -0700535 void acquireWakeLock();
536 virtual void acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800537 void releaseWakeLock();
538 void releaseWakeLock_l();
Andy Hungd01b0f12016-11-07 16:10:30 -0800539 void updateWakeLockUids_l(const SortedVector<uid_t> &uids);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800540 void getPowerManager_l();
Eric Laurentd8365c52017-07-16 15:27:05 -0700541 // suspend or restore effects of the specified type (or all if type is NULL)
542 // on a given session. The number of suspend requests is counted and restore
543 // occurs when all suspend requests are cancelled.
Eric Laurent81784c32012-11-19 14:55:58 -0800544 void setEffectSuspended_l(const effect_uuid_t *type,
545 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -0800546 audio_session_t sessionId);
Eric Laurentd8365c52017-07-16 15:27:05 -0700547 // updated mSuspendedSessions when an effect is suspended or restored
Eric Laurent81784c32012-11-19 14:55:58 -0800548 void updateSuspendedSessions_l(const effect_uuid_t *type,
549 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -0800550 audio_session_t sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800551 // check if some effects must be suspended when an effect chain is added
Andy Hung116bc262023-06-20 18:56:17 -0700552 void checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain);
Eric Laurent81784c32012-11-19 14:55:58 -0800553
Kevin Rocard069c2712018-03-29 19:09:14 -0700554 // sends the metadata of the active tracks to the HAL
Vlad Popa7e81cea2023-01-19 16:34:16 +0100555 struct MetadataUpdate {
556 std::vector<playback_track_metadata_v7_t> playbackMetadataUpdate;
557 std::vector<record_track_metadata_v7_t> recordMetadataUpdate;
558 };
559 virtual MetadataUpdate updateMetadata_l() = 0;
Kevin Rocard069c2712018-03-29 19:09:14 -0700560
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100561 String16 getWakeLockTag();
562
Eric Laurent81784c32012-11-19 14:55:58 -0800563 virtual void preExit() { }
Andy Hung2ddee192015-12-18 17:34:44 -0800564 virtual void setMasterMono_l(bool mono __unused) { }
565 virtual bool requireMonoBlend() { return false; }
Eric Laurent81784c32012-11-19 14:55:58 -0800566
Andy Hung1c86ebe2018-05-29 20:29:08 -0700567 // called within the threadLoop to obtain timestamp from the HAL.
568 virtual status_t threadloop_getHalTimestamp_l(
569 ExtendedTimestamp *timestamp __unused) const {
570 return INVALID_OPERATION;
571 }
Andy Hung116bc262023-06-20 18:56:17 -0700572public:
573// TODO(b/288339104) organize with publics
Eric Laurentd66d7a12021-07-13 13:35:32 +0200574 product_strategy_t getStrategyForStream(audio_stream_type_t stream) const;
Andy Hung116bc262023-06-20 18:56:17 -0700575protected:
Eric Laurentd66d7a12021-07-13 13:35:32 +0200576
Eric Laurentb0463942022-12-20 16:31:10 +0100577 virtual void onHalLatencyModesChanged_l() {}
578
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700579 virtual void dumpInternals_l(int fd __unused, const Vector<String16>& args __unused)
580 { }
581 virtual void dumpTracks_l(int fd __unused, const Vector<String16>& args __unused) { }
582
583
Vlad Popae8d99472022-06-30 16:02:48 +0200584 friend class AudioFlinger; // for mEffectChains and mAudioManager
Eric Laurent81784c32012-11-19 14:55:58 -0800585
586 const type_t mType;
587
588 // Used by parameters, config events, addTrack_l, exit
589 Condition mWaitWorkCV;
590
591 const sp<AudioFlinger> mAudioFlinger;
Andy Hungcf10d742020-04-28 15:38:24 -0700592 ThreadMetrics mThreadMetrics;
593 const bool mIsOut;
Glenn Kasten9b58f632013-07-16 11:37:48 -0700594
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800595 // updated by PlaybackThread::readOutputParameters_l() or
596 // RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800597 uint32_t mSampleRate;
598 size_t mFrameCount; // output HAL, direct output, record
Eric Laurent81784c32012-11-19 14:55:58 -0800599 audio_channel_mask_t mChannelMask;
Glenn Kastenf6ed4232013-07-16 11:16:27 -0700600 uint32_t mChannelCount;
Eric Laurent81784c32012-11-19 14:55:58 -0800601 size_t mFrameSize;
Glenn Kasten97b7b752014-09-28 13:04:24 -0700602 // not HAL frame size, this is for output sink (to pipe to fast mixer)
Andy Hung463be252014-07-10 16:56:07 -0700603 audio_format_t mFormat; // Source format for Recording and
604 // Sink format for Playback.
605 // Sink format may be different than
606 // HAL format if Fastmixer is used.
607 audio_format_t mHALFormat;
Glenn Kasten70949c42013-08-06 07:40:12 -0700608 size_t mBufferSize; // HAL buffer size for read() or write()
jiabinc52b1ff2019-10-31 17:20:42 -0700609 AudioDeviceTypeAddrVector mOutDeviceTypeAddrs; // output device types and addresses
610 AudioDeviceTypeAddr mInDeviceTypeAddr; // input device type and address
Eric Laurent10351942014-05-08 18:49:52 -0700611 Vector< sp<ConfigEvent> > mConfigEvents;
Eric Laurent72e3f392015-05-20 14:43:50 -0700612 Vector< sp<ConfigEvent> > mPendingConfigEvents; // events awaiting system ready
Eric Laurent81784c32012-11-19 14:55:58 -0800613
614 // These fields are written and read by thread itself without lock or barrier,
jiabinc52b1ff2019-10-31 17:20:42 -0700615 // and read by other threads without lock or barrier via standby(), outDeviceTypes()
616 // and inDeviceType().
Eric Laurent81784c32012-11-19 14:55:58 -0800617 // Because of the absence of a lock or barrier, any other thread that reads
618 // these fields must use the information in isolation, or be prepared to deal
619 // with possibility that it might be inconsistent with other information.
Glenn Kasten4944acb2013-08-19 08:39:20 -0700620 bool mStandby; // Whether thread is currently in standby.
jiabinc52b1ff2019-10-31 17:20:42 -0700621
Eric Laurent296fb132015-05-01 11:38:42 -0700622 struct audio_patch mPatch;
jiabinc52b1ff2019-10-31 17:20:42 -0700623
Glenn Kastenf59497b2015-01-26 16:35:47 -0800624 audio_source_t mAudioSource;
Eric Laurent81784c32012-11-19 14:55:58 -0800625
626 const audio_io_handle_t mId;
Andy Hung116bc262023-06-20 18:56:17 -0700627 Vector<sp<IAfEffectChain>> mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -0800628
Glenn Kastend7dca052015-03-05 16:05:54 -0800629 static const int kThreadNameLength = 16; // prctl(PR_SET_NAME) limit
630 char mThreadName[kThreadNameLength]; // guaranteed NUL-terminated
Chris Ye6597d732020-02-28 22:38:25 -0800631 sp<os::IPowerManager> mPowerManager;
Eric Laurent81784c32012-11-19 14:55:58 -0800632 sp<IBinder> mWakeLockToken;
633 const sp<PMDeathRecipient> mDeathRecipient;
Glenn Kastend848eb42016-03-08 13:42:11 -0800634 // list of suspended effects per session and per type. The first (outer) vector is
635 // keyed by session ID, the second (inner) by type UUID timeLow field
Eric Laurentd8365c52017-07-16 15:27:05 -0700636 // Updated by updateSuspendedSessions_l() only.
Glenn Kastend848eb42016-03-08 13:42:11 -0800637 KeyedVector< audio_session_t, KeyedVector< int, sp<SuspendedSessionDesc> > >
Eric Laurent81784c32012-11-19 14:55:58 -0800638 mSuspendedSessions;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -0700639 // TODO: add comment and adjust size as needed
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800640 static const size_t kLogSize = 4 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -0800641 sp<NBLog::Writer> mNBLogWriter;
Eric Laurent72e3f392015-05-20 14:43:50 -0700642 bool mSystemReady;
Andy Hung818e7a32016-02-16 18:08:07 -0800643 ExtendedTimestamp mTimestamp;
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700644 TimestampVerifier< // For timestamp statistics.
645 int64_t /* frame count */, int64_t /* time ns */> mTimestampVerifier;
Dean Wheatley12473e92021-03-18 23:00:55 +1100646 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush
647 // TODO: add confirmation checks:
648 // 1) DIRECT threads and linear PCM format really resets to 0?
649 // 2) Is frame count really valid if not linear pcm?
650 // 3) Are all 64 bits of position returned, not just lowest 32 bits?
jiabinc52b1ff2019-10-31 17:20:42 -0700651 // Timestamp corrected device should be a single device.
652 audio_devices_t mTimestampCorrectedDevice = AUDIO_DEVICE_NONE;
Andy Hung446f4df2019-02-21 12:26:41 -0800653
654 // ThreadLoop statistics per iteration.
655 int64_t mLastIoBeginNs = -1;
656 int64_t mLastIoEndNs = -1;
657
Andy Hung44d648b2022-04-08 17:33:40 -0700658 // ThreadSnapshot is thread-safe (internally locked)
659 mediautils::ThreadSnapshot mThreadSnapshot;
660
Andy Hung446f4df2019-02-21 12:26:41 -0800661 // This should be read under ThreadBase lock (if not on the threadLoop thread).
662 audio_utils::Statistics<double> mIoJitterMs{0.995 /* alpha */};
663 audio_utils::Statistics<double> mProcessTimeMs{0.995 /* alpha */};
Andy Hunge6c37112019-02-26 17:38:10 -0800664 audio_utils::Statistics<double> mLatencyMs{0.995 /* alpha */};
Robert Wu06db0a32021-08-10 19:05:34 +0000665 audio_utils::Statistics<double> mMonopipePipeDepthStats{0.999 /* alpha */};
Andy Hung446f4df2019-02-21 12:26:41 -0800666
Andy Hungd0979812019-02-21 15:51:44 -0800667 // Save the last count when we delivered statistics to mediametrics.
668 int64_t mLastRecordedTimestampVerifierN = 0;
669 int64_t mLastRecordedTimeNs = 0; // BOOTTIME to include suspend.
670
Andy Hungc8fddf32018-08-08 18:32:37 -0700671 bool mIsMsdDevice = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800672 // A condition that must be evaluated by the thread loop has changed and
673 // we must not wait for async write callback in the thread loop before evaluating it
674 bool mSignalPending;
Andy Hungdae27702016-10-31 14:01:16 -0700675
Andy Hung8946a282018-04-19 20:04:56 -0700676#ifdef TEE_SINK
677 NBAIO_Tee mTee;
678#endif
Andy Hungdae27702016-10-31 14:01:16 -0700679 // ActiveTracks is a sorted vector of track type T representing the
680 // active tracks of threadLoop() to be considered by the locked prepare portion.
681 // ActiveTracks should be accessed with the ThreadBase lock held.
682 //
683 // During processing and I/O, the threadLoop does not hold the lock;
684 // hence it does not directly use ActiveTracks. Care should be taken
685 // to hold local strong references or defer removal of tracks
686 // if the threadLoop may still be accessing those tracks due to mix, etc.
687 //
688 // This class updates power information appropriately.
689 //
690
691 template <typename T>
692 class ActiveTracks {
693 public:
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700694 explicit ActiveTracks(SimpleLog *localLog = nullptr)
Andy Hungdae27702016-10-31 14:01:16 -0700695 : mActiveTracksGeneration(0)
696 , mLastActiveTracksGeneration(0)
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700697 , mLocalLog(localLog)
Andy Hungdae27702016-10-31 14:01:16 -0700698 { }
699
700 ~ActiveTracks() {
701 ALOGW_IF(!mActiveTracks.isEmpty(),
702 "ActiveTracks should be empty in destructor");
703 }
704 // returns the last track added (even though it may have been
705 // subsequently removed from ActiveTracks).
706 //
707 // Used for DirectOutputThread to ensure a flush is called when transitioning
708 // to a new track (even though it may be on the same session).
709 // Used for OffloadThread to ensure that volume and mixer state is
710 // taken from the latest track added.
711 //
712 // The latest track is saved with a weak pointer to prevent keeping an
713 // otherwise useless track alive. Thus the function will return nullptr
714 // if the latest track has subsequently been removed and destroyed.
715 sp<T> getLatest() {
716 return mLatestActiveTrack.promote();
717 }
718
719 // SortedVector methods
720 ssize_t add(const sp<T> &track);
721 ssize_t remove(const sp<T> &track);
722 size_t size() const {
723 return mActiveTracks.size();
724 }
Eric Tan39ec8d62018-07-24 09:49:29 -0700725 bool isEmpty() const {
726 return mActiveTracks.isEmpty();
727 }
Andy Hungdae27702016-10-31 14:01:16 -0700728 ssize_t indexOf(const sp<T>& item) {
729 return mActiveTracks.indexOf(item);
730 }
731 sp<T> operator[](size_t index) const {
732 return mActiveTracks[index];
733 }
734 typename SortedVector<sp<T>>::iterator begin() {
735 return mActiveTracks.begin();
736 }
737 typename SortedVector<sp<T>>::iterator end() {
738 return mActiveTracks.end();
739 }
740
741 // Due to Binder recursion optimization, clear() and updatePowerState()
742 // cannot be called from a Binder thread because they may call back into
743 // the original calling process (system server) for BatteryNotifier
744 // (which requires a Java environment that may not be present).
745 // Hence, call clear() and updatePowerState() only from the
746 // ThreadBase thread.
747 void clear();
748 // periodically called in the threadLoop() to update power state uids.
Andy Hung920f6572022-10-06 12:09:49 -0700749 void updatePowerState(const sp<ThreadBase>& thread, bool force = false);
Andy Hungdae27702016-10-31 14:01:16 -0700750
Kevin Rocardc86a7f72018-04-03 09:00:09 -0700751 /** @return true if one or move active tracks was added or removed since the
Jasmine Chaeaa10e42021-05-11 10:11:14 +0800752 * last time this function was called or the vector was created.
753 * true if volume of one of active tracks was changed.
754 */
Kevin Rocard069c2712018-03-29 19:09:14 -0700755 bool readAndClearHasChanged();
756
Eric Laurentdda206a2022-07-08 17:28:35 +0200757 /** Force updating track metadata to audio HAL stream next time
758 * readAndClearHasChanged() is called.
759 */
760 void setHasChanged() { mHasChanged = true; }
761
Andy Hungdae27702016-10-31 14:01:16 -0700762 private:
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700763 void logTrack(const char *funcName, const sp<T> &track) const;
764
Andy Hungd01b0f12016-11-07 16:10:30 -0800765 SortedVector<uid_t> getWakeLockUids() {
766 SortedVector<uid_t> wakeLockUids;
Andy Hungdae27702016-10-31 14:01:16 -0700767 for (const sp<T> &track : mActiveTracks) {
768 wakeLockUids.add(track->uid());
769 }
770 return wakeLockUids; // moved by underlying SharedBuffer
771 }
772
Andy Hungdae27702016-10-31 14:01:16 -0700773 SortedVector<sp<T>> mActiveTracks;
774 int mActiveTracksGeneration;
775 int mLastActiveTracksGeneration;
776 wp<T> mLatestActiveTrack; // latest track added to ActiveTracks
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700777 SimpleLog * const mLocalLog;
Kevin Rocardc86a7f72018-04-03 09:00:09 -0700778 // If the vector has changed since last call to readAndClearHasChanged
Kevin Rocard069c2712018-03-29 19:09:14 -0700779 bool mHasChanged = false;
Andy Hungdae27702016-10-31 14:01:16 -0700780 };
Andy Hung293558a2017-03-21 12:19:20 -0700781
782 SimpleLog mLocalLog;
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700783
784private:
785 void dumpBase_l(int fd, const Vector<String16>& args);
786 void dumpEffectChains_l(int fd, const Vector<String16>& args);
Eric Laurent81784c32012-11-19 14:55:58 -0800787};
788
789// --- PlaybackThread ---
Andy Hung440901d2023-06-29 21:19:25 -0700790class PlaybackThread : public ThreadBase, public virtual IAfPlaybackThread,
791 public StreamOutHalInterfaceCallback,
jiabinf6eb4c32020-02-25 14:06:25 -0800792 public VolumeInterface, public StreamOutHalInterfaceEventCallback {
Andy Hung8d31fd22023-06-26 19:20:57 -0700793 // TODO(b/288339104) remove friends
794 friend class OutputTrack;
795 friend class Track;
Eric Laurent81784c32012-11-19 14:55:58 -0800796public:
797
Eric Laurente93cc032016-05-05 10:15:10 -0700798 // retry count before removing active track in case of underrun on offloaded thread:
799 // we need to make sure that AudioTrack client has enough time to send large buffers
800 //FIXME may be more appropriate if expressed in time units. Need to revise how underrun is
801 // handled for offloaded tracks
802 static const int8_t kMaxTrackRetriesOffload = 20;
803 static const int8_t kMaxTrackStartupRetriesOffload = 100;
804 static const int8_t kMaxTrackStopRetriesOffload = 2;
Andy Hung8ed196a2018-01-05 13:21:11 -0800805 static constexpr uint32_t kMaxTracksPerUid = 40;
Andy Hung1bc088a2018-02-09 15:57:31 -0800806 static constexpr size_t kMaxTracks = 256;
Eric Laurente93cc032016-05-05 10:15:10 -0700807
rago1bb90822017-05-02 18:31:48 -0700808 // Maximum delay (in nanoseconds) for upcoming buffers in suspend mode, otherwise
809 // if delay is greater, the estimated time for timeLoopNextNs is reset.
810 // This allows for catch-up to be done for small delays, while resetting the estimate
811 // for initial conditions or large delays.
812 static const nsecs_t kMaxNextBufferDelayNs = 100000000;
813
Eric Laurent81784c32012-11-19 14:55:58 -0800814 PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +0200815 audio_io_handle_t id, type_t type, bool systemReady,
816 audio_config_base_t *mixerConfig = nullptr);
Andy Hung440901d2023-06-29 21:19:25 -0700817 ~PlaybackThread() override;
Eric Laurent81784c32012-11-19 14:55:58 -0800818
Eric Laurent81784c32012-11-19 14:55:58 -0800819 // Thread virtuals
Andy Hung440901d2023-06-29 21:19:25 -0700820 bool threadLoop() final;
Eric Laurent81784c32012-11-19 14:55:58 -0800821
822 // RefBase
Andy Hung440901d2023-06-29 21:19:25 -0700823 void onFirstRef() override;
Eric Laurent81784c32012-11-19 14:55:58 -0800824
Andy Hung440901d2023-06-29 21:19:25 -0700825 status_t checkEffectCompatibility_l(
826 const effect_descriptor_t* desc, audio_session_t sessionId) final;
Eric Laurent4c415062016-06-17 16:14:16 -0700827
Eric Laurent81784c32012-11-19 14:55:58 -0800828protected:
829 // Code snippets that were lifted up out of threadLoop()
830 virtual void threadLoop_mix() = 0;
831 virtual void threadLoop_sleepTime() = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800832 virtual ssize_t threadLoop_write();
833 virtual void threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -0800834 virtual void threadLoop_standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800835 virtual void threadLoop_exit();
Andy Hung8d31fd22023-06-26 19:20:57 -0700836 virtual void threadLoop_removeTracks(const Vector<sp<IAfTrack>>& tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -0800837
838 // prepareTracks_l reads and writes mActiveTracks, and returns
839 // the pending set of tracks to remove via Vector 'tracksToRemove'. The caller
840 // is responsible for clearing or destroying this Vector later on, when it
841 // is safe to do so. That will drop the final ref count and destroy the tracks.
Andy Hung8d31fd22023-06-26 19:20:57 -0700842 virtual mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove) = 0;
843 void removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove);
Eric Laurenteab90452019-06-24 15:17:46 -0700844 status_t handleVoipVolume_l(float *volume);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800845
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700846 // StreamOutHalInterfaceCallback implementation
847 virtual void onWriteReady();
848 virtual void onDrainReady();
849 virtual void onError();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800850
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700851 void resetWriteBlocked(uint32_t sequence);
852 void resetDraining(uint32_t sequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800853
854 virtual bool waitingAsyncCallback();
855 virtual bool waitingAsyncCallback_l();
856 virtual bool shouldStandby_l();
Haynes Mathew George4c6a4332014-01-15 12:31:39 -0800857 virtual void onAddNewTrack_l();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -0700858 void onAsyncError(); // error reported by AsyncCallbackThread
Eric Laurent81784c32012-11-19 14:55:58 -0800859
jiabinf6eb4c32020-02-25 14:06:25 -0800860 // StreamHalInterfaceCodecFormatCallback implementation
861 void onCodecFormatChanged(
Andy Hung440901d2023-06-29 21:19:25 -0700862 const std::basic_string<uint8_t>& metadataBs) final;
jiabinf6eb4c32020-02-25 14:06:25 -0800863
Eric Laurent81784c32012-11-19 14:55:58 -0800864 // ThreadBase virtuals
865 virtual void preExit();
866
Eric Laurent64667972016-03-30 18:19:46 -0700867 virtual bool keepWakeLock() const { return true; }
Andy Hungdae27702016-10-31 14:01:16 -0700868 virtual void acquireWakeLock_l() {
869 ThreadBase::acquireWakeLock_l();
870 mActiveTracks.updatePowerState(this, true /* force */);
871 }
Eric Laurent64667972016-03-30 18:19:46 -0700872
Eric Laurentb3f315a2021-07-13 15:09:05 +0200873 virtual void checkOutputStageEffects() {}
Eric Laurent68a40a82022-05-03 18:15:04 +0200874 virtual void setHalLatencyMode_l() {}
875
Eric Laurentb3f315a2021-07-13 15:09:05 +0200876
Andy Hung440901d2023-06-29 21:19:25 -0700877 void dumpInternals_l(int fd, const Vector<String16>& args) override;
878 void dumpTracks_l(int fd, const Vector<String16>& args) final;
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700879
Eric Laurent81784c32012-11-19 14:55:58 -0800880public:
881
Andy Hung440901d2023-06-29 21:19:25 -0700882 status_t initCheck() const final { return mOutput == nullptr ? NO_INIT : NO_ERROR; }
Eric Laurent81784c32012-11-19 14:55:58 -0800883
884 // return estimated latency in milliseconds, as reported by HAL
Andy Hung440901d2023-06-29 21:19:25 -0700885 uint32_t latency() const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800886 // same, but lock must already be held
Andy Hung440901d2023-06-29 21:19:25 -0700887 uint32_t latency_l() const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800888
Eric Laurent6acd1d42017-01-04 14:23:29 -0800889 // VolumeInterface
Andy Hung440901d2023-06-29 21:19:25 -0700890 void setMasterVolume(float value) final;
891 void setMasterBalance(float balance) override;
892 void setMasterMute(bool muted) final;
893 void setStreamVolume(audio_stream_type_t stream, float value) final;
894 void setStreamMute(audio_stream_type_t stream, bool muted) final;
895 float streamVolume(audio_stream_type_t stream) const final;
896 void setVolumeForOutput_l(float left, float right) const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800897
Andy Hung440901d2023-06-29 21:19:25 -0700898 sp<IAfTrack> createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -0700899 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -0800900 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700901 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -0800902 uint32_t *sampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -0800903 audio_format_t format,
904 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -0800905 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -0800906 size_t *pNotificationFrameCount,
907 uint32_t notificationsPerBuffer,
908 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -0800909 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -0800910 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -0700911 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700912 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +0000913 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -0800914 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800915 status_t *status /*non-NULL*/,
jiabinf6eb4c32020-02-25 14:06:25 -0800916 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200917 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +0000918 bool isSpatialized,
Andy Hung440901d2023-06-29 21:19:25 -0700919 bool isBitPerfect) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800920
Andy Hung440901d2023-06-29 21:19:25 -0700921 AudioStreamOut* getOutput() const final;
922 AudioStreamOut* clearOutput() final;
923 sp<StreamHalInterface> stream() const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800924
925 // a very large number of suspend() will eventually wraparound, but unlikely
Andy Hung440901d2023-06-29 21:19:25 -0700926 void suspend() final { (void) android_atomic_inc(&mSuspended); }
927 void restore() final
Eric Laurent81784c32012-11-19 14:55:58 -0800928 {
929 // if restore() is done without suspend(), get back into
930 // range so that the next suspend() will operate correctly
931 if (android_atomic_dec(&mSuspended) <= 0) {
932 android_atomic_release_store(0, &mSuspended);
933 }
934 }
Andy Hung440901d2023-06-29 21:19:25 -0700935 bool isSuspended() const final
Eric Laurent81784c32012-11-19 14:55:58 -0800936 { return android_atomic_acquire_load(&mSuspended) > 0; }
937
Andy Hung440901d2023-06-29 21:19:25 -0700938 String8 getParameters(const String8& keys);
939 void ioConfigChanged(audio_io_config_event_t event, pid_t pid = 0,
940 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final;
941 status_t getRenderPosition(uint32_t* halFrames, uint32_t* dspFrames) const final;
Andy Hung010a1a12014-03-13 13:57:33 -0700942 // Consider also removing and passing an explicit mMainBuffer initialization
Andy Hung8d31fd22023-06-26 19:20:57 -0700943 // parameter to AF::IAfTrack::Track().
Andy Hung440901d2023-06-29 21:19:25 -0700944 float* sinkBuffer() const final {
Andy Hung319587b2023-05-23 14:01:03 -0700945 return reinterpret_cast<float *>(mSinkBuffer); };
Eric Laurent81784c32012-11-19 14:55:58 -0800946
Andy Hung440901d2023-06-29 21:19:25 -0700947 void detachAuxEffect_l(int effectId) final;
Eric Laurent81784c32012-11-19 14:55:58 -0800948
Andy Hung440901d2023-06-29 21:19:25 -0700949 status_t attachAuxEffect(const sp<IAfTrack>& track, int EffectId) final;
950 status_t attachAuxEffect_l(const sp<IAfTrack>& track, int EffectId) final;
951
952 status_t addEffectChain_l(const sp<IAfEffectChain>& chain) final;
953 size_t removeEffectChain_l(const sp<IAfEffectChain>& chain) final;
954 uint32_t hasAudioSession_l(audio_session_t sessionId) const final {
Andy Hungc3d62f92019-03-14 13:38:51 -0700955 return ThreadBase::hasAudioSession_l(sessionId, mTracks);
956 }
Andy Hung440901d2023-06-29 21:19:25 -0700957 product_strategy_t getStrategyForSession_l(audio_session_t sessionId) const final;
Eric Laurent81784c32012-11-19 14:55:58 -0800958
959
Andy Hung440901d2023-06-29 21:19:25 -0700960 status_t setSyncEvent(const sp<audioflinger::SyncEvent>& event) final;
961 bool isValidSyncEvent(const sp<audioflinger::SyncEvent>& event) const final;
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700962
963 // called with AudioFlinger lock held
Andy Hung440901d2023-06-29 21:19:25 -0700964 bool invalidateTracks_l(audio_stream_type_t streamType) final;
965 bool invalidateTracks_l(std::set<audio_port_handle_t>& portIds) final;
966 void invalidateTracks(audio_stream_type_t streamType) override;
jiabinc44b3462022-12-08 12:52:31 -0800967 // Invalidate tracks by a set of port ids. The port id will be removed from
968 // the given set if the corresponding track is found and invalidated.
Andy Hung440901d2023-06-29 21:19:25 -0700969 void invalidateTracks(std::set<audio_port_handle_t>& portIds) override;
Eric Laurent81784c32012-11-19 14:55:58 -0800970
Andy Hung440901d2023-06-29 21:19:25 -0700971 size_t frameCount() const final{ return mNormalFrameCount; }
Glenn Kasten9b58f632013-07-16 11:37:48 -0700972
Andy Hung440901d2023-06-29 21:19:25 -0700973 audio_channel_mask_t mixerChannelMask() const final {
Eric Laurentf1f22e72021-07-13 14:04:14 +0200974 return mMixerChannelMask;
975 }
976
Andy Hung440901d2023-06-29 21:19:25 -0700977 status_t getTimestamp_l(AudioTimestamp& timestamp) final;
Eric Laurent83b88082014-06-20 18:31:16 -0700978
Andy Hung440901d2023-06-29 21:19:25 -0700979 void addPatchTrack(const sp<IAfPatchTrack>& track) final;
980 void deletePatchTrack(const sp<IAfPatchTrack>& track) final;
Eric Laurent83b88082014-06-20 18:31:16 -0700981
Andy Hung440901d2023-06-29 21:19:25 -0700982 void toAudioPortConfig(struct audio_port_config* config) final;
Eric Laurentaccc1472013-09-20 09:36:34 -0700983
Andy Hung10cbff12017-02-21 17:30:14 -0800984 // Return the asynchronous signal wait time.
Andy Hung440901d2023-06-29 21:19:25 -0700985 int64_t computeWaitTimeNs_l() const override { return INT64_MAX; }
Andy Hung1bc088a2018-02-09 15:57:31 -0800986 // returns true if the track is allowed to be added to the thread.
Andy Hung440901d2023-06-29 21:19:25 -0700987 bool isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -0800988 audio_channel_mask_t channelMask __unused,
989 audio_format_t format __unused,
990 audio_session_t sessionId __unused,
Andy Hung440901d2023-06-29 21:19:25 -0700991 uid_t uid) const override {
Andy Hung1bc088a2018-02-09 15:57:31 -0800992 return trackCountForUid_l(uid) < PlaybackThread::kMaxTracksPerUid
993 && mTracks.size() < PlaybackThread::kMaxTracks;
994 }
995
Andy Hung440901d2023-06-29 21:19:25 -0700996 bool isTimestampCorrectionEnabled() const final {
jiabinc52b1ff2019-10-31 17:20:42 -0700997 return audio_is_output_devices(mTimestampCorrectedDevice)
998 && outDeviceTypes().count(mTimestampCorrectedDevice) != 0;
Andy Hungc8fddf32018-08-08 18:32:37 -0700999 }
jiabinc52b1ff2019-10-31 17:20:42 -07001000
Andy Hung440901d2023-06-29 21:19:25 -07001001 bool isStreamInitialized() const final {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001002 return !(mOutput == nullptr || mOutput->stream == nullptr);
1003 }
1004
Andy Hung440901d2023-06-29 21:19:25 -07001005 audio_channel_mask_t hapticChannelMask() const final {
jiabineb3bda02020-06-30 14:07:03 -07001006 return mHapticChannelMask;
1007 }
Andy Hung440901d2023-06-29 21:19:25 -07001008 bool supportsHapticPlayback() const final {
jiabineb3bda02020-06-30 14:07:03 -07001009 return (mHapticChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE;
1010 }
1011
Andy Hung440901d2023-06-29 21:19:25 -07001012 void setDownStreamPatch(const struct audio_patch* patch) final {
Eric Laurent74c38dc2020-12-23 18:19:44 +01001013 Mutex::Autolock _l(mLock);
1014 mDownStreamPatch = *patch;
1015 }
1016
Andy Hung440901d2023-06-29 21:19:25 -07001017 IAfTrack* getTrackById_l(audio_port_handle_t trackId) final;
jiabinf042b9b2021-05-07 23:46:28 +00001018
Andy Hung440901d2023-06-29 21:19:25 -07001019 bool hasMixer() const final {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001020 return mType == MIXER || mType == DUPLICATING || mType == SPATIALIZER;
Eric Laurentb3f315a2021-07-13 15:09:05 +02001021 }
Eric Laurent68a40a82022-05-03 18:15:04 +02001022
Andy Hung440901d2023-06-29 21:19:25 -07001023 status_t setRequestedLatencyMode(
1024 audio_latency_mode_t /* mode */) override { return INVALID_OPERATION; }
Eric Laurent68a40a82022-05-03 18:15:04 +02001025
Andy Hung440901d2023-06-29 21:19:25 -07001026 status_t getSupportedLatencyModes(
1027 std::vector<audio_latency_mode_t>* /* modes */) override {
Eric Laurent68a40a82022-05-03 18:15:04 +02001028 return INVALID_OPERATION;
1029 }
1030
Andy Hung440901d2023-06-29 21:19:25 -07001031 status_t setBluetoothVariableLatencyEnabled(bool /* enabled */) override{
Eric Laurentb0463942022-12-20 16:31:10 +01001032 return INVALID_OPERATION;
1033 }
Eric Laurent52057642022-12-16 11:45:07 +01001034
Andy Hung440901d2023-06-29 21:19:25 -07001035 void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) override;
1036 void stopMelComputation_l() override;
Vlad Popab042ee62022-10-20 18:05:00 +02001037
Andy Hung440901d2023-06-29 21:19:25 -07001038 void setStandby() final {
Eric Laurent19952e12023-04-20 10:08:29 +02001039 Mutex::Autolock _l(mLock);
1040 setStandby_l();
1041 }
1042
Andy Hung440901d2023-06-29 21:19:25 -07001043 void setStandby_l() final {
Eric Laurent19952e12023-04-20 10:08:29 +02001044 mStandby = true;
1045 mHalStarted = false;
1046 mKernelPositionOnStandby =
1047 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
1048 }
1049
Andy Hung440901d2023-06-29 21:19:25 -07001050 bool waitForHalStart() final {
Eric Laurent19952e12023-04-20 10:08:29 +02001051 Mutex::Autolock _l(mLock);
1052 static const nsecs_t kWaitHalTimeoutNs = seconds(2);
1053 nsecs_t endWaitTimetNs = systemTime() + kWaitHalTimeoutNs;
1054 while (!mHalStarted) {
1055 nsecs_t timeNs = systemTime();
1056 if (timeNs >= endWaitTimetNs) {
1057 break;
1058 }
1059 nsecs_t waitTimeLeftNs = endWaitTimetNs - timeNs;
1060 mWaitHalStartCV.waitRelative(mLock, waitTimeLeftNs);
1061 }
1062 return mHalStarted;
1063 }
Eric Laurent81784c32012-11-19 14:55:58 -08001064protected:
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001065 // updated by readOutputParameters_l()
Glenn Kasten9b58f632013-07-16 11:37:48 -07001066 size_t mNormalFrameCount; // normal mixer and effects
1067
Andy Hung08fb1742015-05-31 23:22:10 -07001068 bool mThreadThrottle; // throttle the thread processing
Andy Hung40eb1a12015-06-18 13:42:02 -07001069 uint32_t mThreadThrottleTimeMs; // throttle time for MIXER threads
1070 uint32_t mThreadThrottleEndMs; // notify once per throttling
Andy Hung08fb1742015-05-31 23:22:10 -07001071 uint32_t mHalfBufferMs; // half the buffer size in milliseconds
1072
Andy Hung010a1a12014-03-13 13:57:33 -07001073 void* mSinkBuffer; // frame size aligned sink buffer
Eric Laurent81784c32012-11-19 14:55:58 -08001074
Andy Hung98ef9782014-03-04 14:46:50 -08001075 // TODO:
1076 // Rearrange the buffer info into a struct/class with
1077 // clear, copy, construction, destruction methods.
1078 //
1079 // mSinkBuffer also has associated with it:
1080 //
1081 // mSinkBufferSize: Sink Buffer Size
1082 // mFormat: Sink Buffer Format
1083
Andy Hung69aed5f2014-02-25 17:24:40 -08001084 // Mixer Buffer (mMixerBuffer*)
1085 //
1086 // In the case of floating point or multichannel data, which is not in the
1087 // sink format, it is required to accumulate in a higher precision or greater channel count
1088 // buffer before downmixing or data conversion to the sink buffer.
1089
1090 // Set to "true" to enable the Mixer Buffer otherwise mixer output goes to sink buffer.
1091 bool mMixerBufferEnabled;
1092
1093 // Storage, 32 byte aligned (may make this alignment a requirement later).
1094 // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
1095 void* mMixerBuffer;
1096
1097 // Size of mMixerBuffer in bytes: mNormalFrameCount * #channels * sampsize.
1098 size_t mMixerBufferSize;
1099
1100 // The audio format of mMixerBuffer. Set to AUDIO_FORMAT_PCM_(FLOAT|16_BIT) only.
1101 audio_format_t mMixerBufferFormat;
1102
1103 // An internal flag set to true by MixerThread::prepareTracks_l()
1104 // when mMixerBuffer contains valid data after mixing.
1105 bool mMixerBufferValid;
1106
Andy Hung98ef9782014-03-04 14:46:50 -08001107 // Effects Buffer (mEffectsBuffer*)
1108 //
1109 // In the case of effects data, which is not in the sink format,
1110 // it is required to accumulate in a different buffer before data conversion
1111 // to the sink buffer.
1112
1113 // Set to "true" to enable the Effects Buffer otherwise effects output goes to sink buffer.
1114 bool mEffectBufferEnabled;
1115
1116 // Storage, 32 byte aligned (may make this alignment a requirement later).
1117 // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
1118 void* mEffectBuffer;
1119
1120 // Size of mEffectsBuffer in bytes: mNormalFrameCount * #channels * sampsize.
1121 size_t mEffectBufferSize;
1122
1123 // The audio format of mEffectsBuffer. Set to AUDIO_FORMAT_PCM_16_BIT only.
1124 audio_format_t mEffectBufferFormat;
1125
1126 // An internal flag set to true by MixerThread::prepareTracks_l()
1127 // when mEffectsBuffer contains valid data after mixing.
1128 //
1129 // When this is set, all mixer data is routed into the effects buffer
1130 // for any processing (including output processing).
1131 bool mEffectBufferValid;
1132
jiabinc658e452022-10-21 20:52:21 +00001133 // Set to "true" to enable when data has already copied to sink
1134 bool mHasDataCopiedToSinkBuffer = false;
1135
Eric Laurentb62d0362021-10-26 17:40:18 +02001136 // Frame size aligned buffer used as input and output to all post processing effects
1137 // except the Spatializer in a SPATIALIZER thread. Non spatialized tracks are mixed into
1138 // this buffer so that post processing effects can be applied.
1139 void* mPostSpatializerBuffer = nullptr;
1140
1141 // Size of mPostSpatializerBuffer in bytes
1142 size_t mPostSpatializerBufferSize;
Eric Laurent39095982021-08-24 18:29:27 +02001143
1144
Eric Laurent81784c32012-11-19 14:55:58 -08001145 // suspend count, > 0 means suspended. While suspended, the thread continues to pull from
1146 // tracks and mix, but doesn't write to HAL. A2DP and SCO HAL implementations can't handle
1147 // concurrent use of both of them, so Audio Policy Service suspends one of the threads to
1148 // workaround that restriction.
1149 // 'volatile' means accessed via atomic operations and no lock.
1150 volatile int32_t mSuspended;
1151
Andy Hung818e7a32016-02-16 18:08:07 -08001152 int64_t mBytesWritten;
yucliu6cfb5932022-07-20 17:40:39 -07001153 std::atomic<int64_t> mFramesWritten; // not reset on standby
Dean Wheatley12473e92021-03-18 23:00:55 +11001154 int64_t mLastFramesWritten = -1; // track changes in timestamp
1155 // server frames written.
Andy Hung238fa3d2016-07-28 10:53:22 -07001156 int64_t mSuspendedFrames; // not reset on standby
jiabin245cdd92018-12-07 17:55:15 -08001157
1158 // mHapticChannelMask and mHapticChannelCount will only be valid when the thread support
1159 // haptic playback.
1160 audio_channel_mask_t mHapticChannelMask = AUDIO_CHANNEL_NONE;
1161 uint32_t mHapticChannelCount = 0;
Eric Laurentf1f22e72021-07-13 14:04:14 +02001162
1163 audio_channel_mask_t mMixerChannelMask = AUDIO_CHANNEL_NONE;
1164
Eric Laurent81784c32012-11-19 14:55:58 -08001165private:
1166 // mMasterMute is in both PlaybackThread and in AudioFlinger. When a
1167 // PlaybackThread needs to find out if master-muted, it checks it's local
1168 // copy rather than the one in AudioFlinger. This optimization saves a lock.
1169 bool mMasterMute;
1170 void setMasterMute_l(bool muted) { mMasterMute = muted; }
Dean Wheatley12473e92021-03-18 23:00:55 +11001171
1172 auto discontinuityForStandbyOrFlush() const { // call on threadLoop or with lock.
1173 return ((mType == DIRECT && !audio_is_linear_pcm(mFormat))
1174 || mType == OFFLOAD)
1175 ? mTimestampVerifier.DISCONTINUITY_MODE_ZERO
1176 : mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS;
1177 }
1178
Eric Laurent81784c32012-11-19 14:55:58 -08001179protected:
Andy Hung8d31fd22023-06-26 19:20:57 -07001180 ActiveTracks<IAfTrack> mActiveTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08001181
Eric Laurent81784c32012-11-19 14:55:58 -08001182 // Time to sleep between cycles when:
1183 virtual uint32_t activeSleepTimeUs() const; // mixer state MIXER_TRACKS_ENABLED
1184 virtual uint32_t idleSleepTimeUs() const = 0; // mixer state MIXER_IDLE
1185 virtual uint32_t suspendSleepTimeUs() const = 0; // audio policy manager suspended us
1186 // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write()
1187 // No sleep in standby mode; waits on a condition
1188
1189 // Code snippets that are temporarily lifted up out of threadLoop() until the merge
Andy Hung440901d2023-06-29 21:19:25 -07001190 virtual void checkSilentMode_l() final; // consider unification with MMapThread
Eric Laurent81784c32012-11-19 14:55:58 -08001191
1192 // Non-trivial for DUPLICATING only
1193 virtual void saveOutputTracks() { }
1194 virtual void clearOutputTracks() { }
1195
1196 // Cache various calculated values, at threadLoop() entry and after a parameter change
1197 virtual void cacheParameters_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02001198 void setCheckOutputStageEffects() override {
1199 mCheckOutputStageEffects.store(true);
1200 }
Eric Laurent81784c32012-11-19 14:55:58 -08001201
1202 virtual uint32_t correctLatency_l(uint32_t latency) const;
1203
Eric Laurent1c333e22014-05-20 10:48:17 -07001204 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
1205 audio_patch_handle_t *handle);
1206 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle);
1207
Phil Burk6fc2a7c2015-04-30 16:08:10 -07001208 bool usesHwAvSync() const { return (mType == DIRECT) && (mOutput != NULL)
1209 && mHwSupportsPause
1210 && (mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC); }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08001211
Andy Hung1bc088a2018-02-09 15:57:31 -08001212 uint32_t trackCountForUid_l(uid_t uid) const;
Eric Laurentad7dd962016-09-22 12:38:37 -07001213
jiabineb3bda02020-06-30 14:07:03 -07001214 void invalidateTracksForAudioSession_l(
Andy Hung440901d2023-06-29 21:19:25 -07001215 audio_session_t sessionId) const override {
jiabineb3bda02020-06-30 14:07:03 -07001216 ThreadBase::invalidateTracksForAudioSession_l(sessionId, mTracks);
1217 }
1218
Eric Laurent81784c32012-11-19 14:55:58 -08001219private:
1220
1221 friend class AudioFlinger; // for numerous
1222
Mikhail Naganovbf493082017-04-17 17:37:12 -07001223 DISALLOW_COPY_AND_ASSIGN(PlaybackThread);
Eric Laurent81784c32012-11-19 14:55:58 -08001224
Andy Hung8d31fd22023-06-26 19:20:57 -07001225 status_t addTrack_l(const sp<IAfTrack>& track);
1226 bool destroyTrack_l(const sp<IAfTrack>& track);
1227 void removeTrack_l(const sp<IAfTrack>& track);
Eric Laurent81784c32012-11-19 14:55:58 -08001228
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001229 void readOutputParameters_l();
Vlad Popa7e81cea2023-01-19 16:34:16 +01001230 MetadataUpdate updateMetadata_l() final;
Kevin Rocardc86a7f72018-04-03 09:00:09 -07001231 virtual void sendMetadataToBackend_l(const StreamOutHalInterface::SourceMetadata& metadata);
Eric Laurent81784c32012-11-19 14:55:58 -08001232
Dean Wheatley12473e92021-03-18 23:00:55 +11001233 void collectTimestamps_l();
1234
Andy Hungc0691382018-09-12 18:01:57 -07001235 // The Tracks class manages tracks added and removed from the Thread.
Andy Hung1bc088a2018-02-09 15:57:31 -08001236 template <typename T>
1237 class Tracks {
1238 public:
Andy Hung920f6572022-10-06 12:09:49 -07001239 explicit Tracks(bool saveDeletedTrackIds) :
Andy Hungc0691382018-09-12 18:01:57 -07001240 mSaveDeletedTrackIds(saveDeletedTrackIds) { }
Andy Hung1bc088a2018-02-09 15:57:31 -08001241
1242 // SortedVector methods
Andy Hungc0691382018-09-12 18:01:57 -07001243 ssize_t add(const sp<T> &track) {
1244 const ssize_t index = mTracks.add(track);
1245 LOG_ALWAYS_FATAL_IF(index < 0, "cannot add track");
1246 return index;
1247 }
Andy Hung1bc088a2018-02-09 15:57:31 -08001248 ssize_t remove(const sp<T> &track);
1249 size_t size() const {
1250 return mTracks.size();
1251 }
1252 bool isEmpty() const {
1253 return mTracks.isEmpty();
1254 }
1255 ssize_t indexOf(const sp<T> &item) {
1256 return mTracks.indexOf(item);
1257 }
1258 sp<T> operator[](size_t index) const {
1259 return mTracks[index];
1260 }
1261 typename SortedVector<sp<T>>::iterator begin() {
1262 return mTracks.begin();
1263 }
1264 typename SortedVector<sp<T>>::iterator end() {
1265 return mTracks.end();
1266 }
1267
Andy Hung920f6572022-10-06 12:09:49 -07001268 size_t processDeletedTrackIds(const std::function<void(int)>& f) {
Andy Hungc0691382018-09-12 18:01:57 -07001269 for (const int trackId : mDeletedTrackIds) {
1270 f(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08001271 }
Andy Hungc0691382018-09-12 18:01:57 -07001272 return mDeletedTrackIds.size();
Andy Hung1bc088a2018-02-09 15:57:31 -08001273 }
1274
Andy Hungc0691382018-09-12 18:01:57 -07001275 void clearDeletedTrackIds() { mDeletedTrackIds.clear(); }
Andy Hung1bc088a2018-02-09 15:57:31 -08001276
1277 private:
Andy Hungc0691382018-09-12 18:01:57 -07001278 // Tracks pending deletion for MIXER type threads
1279 const bool mSaveDeletedTrackIds; // true to enable tracking
1280 std::set<int> mDeletedTrackIds;
Andy Hung1bc088a2018-02-09 15:57:31 -08001281
1282 SortedVector<sp<T>> mTracks; // wrapped SortedVector.
1283 };
1284
Andy Hung8d31fd22023-06-26 19:20:57 -07001285 Tracks<IAfTrack> mTracks;
Andy Hung1bc088a2018-02-09 15:57:31 -08001286
Eric Laurent223fd5c2014-11-11 13:43:36 -08001287 stream_type_t mStreamTypes[AUDIO_STREAM_CNT];
Eric Laurent81784c32012-11-19 14:55:58 -08001288 AudioStreamOut *mOutput;
1289
1290 float mMasterVolume;
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001291 std::atomic<float> mMasterBalance{};
1292 audio_utils::Balance mBalance;
Eric Laurent81784c32012-11-19 14:55:58 -08001293 int mNumWrites;
1294 int mNumDelayedWrites;
1295 bool mInWrite;
1296
1297 // FIXME rename these former local variables of threadLoop to standard "m" names
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001298 nsecs_t mStandbyTimeNs;
Andy Hung25c2dac2014-02-27 14:56:00 -08001299 size_t mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001300
1301 // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l()
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001302 uint32_t mActiveSleepTimeUs;
1303 uint32_t mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08001304
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001305 uint32_t mSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08001306
1307 // mixer status returned by prepareTracks_l()
1308 mixer_state mMixerStatus; // current cycle
1309 // previous cycle when in prepareTracks_l()
1310 mixer_state mMixerStatusIgnoringFastTracks;
1311 // FIXME or a separate ready state per track
1312
1313 // FIXME move these declarations into the specific sub-class that needs them
1314 // MIXER only
1315 uint32_t sleepTimeShift;
1316
1317 // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001318 nsecs_t mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08001319
1320 // MIXER only
1321 nsecs_t maxPeriod;
1322
1323 // DUPLICATING only
1324 uint32_t writeFrames;
1325
Eric Laurentbfb1b832013-01-07 09:53:42 -08001326 size_t mBytesRemaining;
1327 size_t mCurrentWriteLength;
1328 bool mUseAsyncWrite;
Eric Laurent3b4529e2013-09-05 18:09:19 -07001329 // mWriteAckSequence contains current write sequence on bits 31-1. The write sequence is
1330 // incremented each time a write(), a flush() or a standby() occurs.
1331 // Bit 0 is set when a write blocks and indicates a callback is expected.
1332 // Bit 0 is reset by the async callback thread calling resetWriteBlocked(). Out of sequence
1333 // callbacks are ignored.
1334 uint32_t mWriteAckSequence;
1335 // mDrainSequence contains current drain sequence on bits 31-1. The drain sequence is
1336 // incremented each time a drain is requested or a flush() or standby() occurs.
1337 // Bit 0 is set when the drain() command is called at the HAL and indicates a callback is
1338 // expected.
1339 // Bit 0 is reset by the async callback thread calling resetDraining(). Out of sequence
1340 // callbacks are ignored.
1341 uint32_t mDrainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001342 sp<AsyncCallbackThread> mCallbackThread;
1343
jiabinf6eb4c32020-02-25 14:06:25 -08001344 Mutex mAudioTrackCbLock;
1345 // Record of IAudioTrackCallback
Andy Hung8d31fd22023-06-26 19:20:57 -07001346 std::map<sp<IAfTrack>, sp<media::IAudioTrackCallback>> mAudioTrackCallbacks;
jiabinf6eb4c32020-02-25 14:06:25 -08001347
Eric Laurent81784c32012-11-19 14:55:58 -08001348private:
1349 // The HAL output sink is treated as non-blocking, but current implementation is blocking
1350 sp<NBAIO_Sink> mOutputSink;
1351 // If a fast mixer is present, the blocking pipe sink, otherwise clear
1352 sp<NBAIO_Sink> mPipeSink;
1353 // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink
1354 sp<NBAIO_Sink> mNormalSink;
Eric Laurent81784c32012-11-19 14:55:58 -08001355 uint32_t mScreenState; // cached copy of gScreenState
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07001356 // TODO: add comment and adjust size as needed
Glenn Kasteneef598c2017-04-03 14:41:13 -07001357 static const size_t kFastMixerLogSize = 8 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -08001358 sp<NBLog::Writer> mFastMixerNBLogWriter;
Andy Hung2148bf02016-11-28 19:01:02 -08001359
Dean Wheatley30d28422018-11-06 10:27:40 +11001360 // Downstream patch latency, available if mDownstreamLatencyStatMs.getN() > 0.
1361 audio_utils::Statistics<double> mDownstreamLatencyStatMs{0.999};
Andy Hung2148bf02016-11-28 19:01:02 -08001362
Eric Laurent19952e12023-04-20 10:08:29 +02001363 // output stream start detection based on render position returned by the kernel
1364 // condition signalled when the output stream has started
1365 Condition mWaitHalStartCV;
1366 // true when the output stream render position has moved, reset to false in standby
1367 bool mHalStarted = false;
1368 // last kernel render position saved when entering standby
1369 int64_t mKernelPositionOnStandby = 0;
1370
Eric Laurent81784c32012-11-19 14:55:58 -08001371public:
Andy Hung440901d2023-06-29 21:19:25 -07001372 FastTrackUnderruns getFastTrackUnderruns(size_t /* fastIndex */) const override
1373 { return {}; }
1374 const std::atomic<int64_t>& framesWritten() const final { return mFramesWritten; }
Eric Laurent81784c32012-11-19 14:55:58 -08001375
1376protected:
1377 // accessed by both binder threads and within threadLoop(), lock on mutex needed
1378 unsigned mFastTrackAvailMask; // bit i set if fast track [i] is available
Eric Laurentd1f69b02014-12-15 14:33:13 -08001379 bool mHwSupportsPause;
1380 bool mHwPaused;
1381 bool mFlushPending;
Eric Laurent7c29ec92017-09-20 17:54:22 -07001382 // volumes last sent to audio HAL with stream->setVolume()
1383 float mLeftVolFloat;
1384 float mRightVolFloat;
Eric Laurent74c38dc2020-12-23 18:19:44 +01001385
1386 // audio patch used by the downstream software patch.
1387 // Only used if ThreadBase::mIsMsdDevice is true.
1388 struct audio_patch mDownStreamPatch;
Eric Laurentb3f315a2021-07-13 15:09:05 +02001389
1390 std::atomic_bool mCheckOutputStageEffects{};
ziyangch8f194f12021-12-01 13:48:04 -08001391
ziyangch8f194f12021-12-01 13:48:04 -08001392
Brian Lindahl65e90012022-07-27 18:01:07 +02001393 // Provides periodic checking for timestamp advancement for underrun detection.
1394 class IsTimestampAdvancing {
1395 public:
1396 // The timestamp will not be checked any faster than the specified time.
Andy Hung920f6572022-10-06 12:09:49 -07001397 explicit IsTimestampAdvancing(nsecs_t minimumTimeBetweenChecksNs)
Brian Lindahl65e90012022-07-27 18:01:07 +02001398 : mMinimumTimeBetweenChecksNs(minimumTimeBetweenChecksNs)
1399 {
1400 clear();
1401 }
1402 // Check if the presentation position has advanced in the last periodic time.
1403 bool check(AudioStreamOut * output);
1404 // Clear the internal state when the playback state changes for the output
1405 // stream.
1406 void clear();
1407 private:
1408 // The minimum time between timestamp checks.
1409 const nsecs_t mMinimumTimeBetweenChecksNs;
1410 // Add differential check on the timestamps to see if there is a change in the
1411 // timestamp frame position between the last call to check.
1412 uint64_t mPreviousPosition;
1413 // The time at which the last check occurred, to ensure we don't check too
1414 // frequently, giving the Audio HAL enough time to update its timestamps.
1415 nsecs_t mPreviousNs;
1416 // The valued is latched so we don't check timestamps too frequently.
1417 bool mLatchedValue;
1418 };
1419 IsTimestampAdvancing mIsTimestampAdvancing;
ziyangch8f194f12021-12-01 13:48:04 -08001420
Brian Lindahl65e90012022-07-27 18:01:07 +02001421 virtual void flushHw_l() {
1422 mIsTimestampAdvancing.clear();
1423 }
Eric Laurent81784c32012-11-19 14:55:58 -08001424};
1425
Eric Laurentb0463942022-12-20 16:31:10 +01001426class MixerThread : public PlaybackThread,
1427 public StreamOutHalInterfaceLatencyModeCallback {
Eric Laurent81784c32012-11-19 14:55:58 -08001428public:
1429 MixerThread(const sp<AudioFlinger>& audioFlinger,
1430 AudioStreamOut* output,
1431 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001432 bool systemReady,
Eric Laurentf1f22e72021-07-13 14:04:14 +02001433 type_t type = MIXER,
1434 audio_config_base_t *mixerConfig = nullptr);
Andy Hung440901d2023-06-29 21:19:25 -07001435 ~MixerThread() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001436
Eric Laurentb0463942022-12-20 16:31:10 +01001437 // RefBase
Andy Hung440901d2023-06-29 21:19:25 -07001438 void onFirstRef() override;
Eric Laurentb0463942022-12-20 16:31:10 +01001439
1440 // StreamOutHalInterfaceLatencyModeCallback
1441 void onRecommendedLatencyModeChanged(
Andy Hung440901d2023-06-29 21:19:25 -07001442 std::vector<audio_latency_mode_t> modes) final;
Eric Laurentb0463942022-12-20 16:31:10 +01001443
Eric Laurent81784c32012-11-19 14:55:58 -08001444 // Thread virtuals
1445
Andy Hung440901d2023-06-29 21:19:25 -07001446 bool checkForNewParameter_l(const String8& keyValuePair, status_t& status) final;
Eric Laurent81784c32012-11-19 14:55:58 -08001447
Andy Hung440901d2023-06-29 21:19:25 -07001448 bool isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08001449 audio_channel_mask_t channelMask, audio_format_t format,
Andy Hung440901d2023-06-29 21:19:25 -07001450 audio_session_t sessionId, uid_t uid) const final;
Eric Laurent81784c32012-11-19 14:55:58 -08001451protected:
Andy Hung440901d2023-06-29 21:19:25 -07001452 mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove) override;
1453 uint32_t idleSleepTimeUs() const final;
1454 uint32_t suspendSleepTimeUs() const final;
1455 void cacheParameters_l() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001456
Andy Hung440901d2023-06-29 21:19:25 -07001457 void acquireWakeLock_l() final {
Andy Hungdae27702016-10-31 14:01:16 -07001458 PlaybackThread::acquireWakeLock_l();
Andy Hung818e7a32016-02-16 18:08:07 -08001459 if (hasFastMixer()) {
1460 mFastMixer->setBoottimeOffset(
1461 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME]);
1462 }
1463 }
1464
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001465 void dumpInternals_l(int fd, const Vector<String16>& args) override;
1466
Eric Laurent81784c32012-11-19 14:55:58 -08001467 // threadLoop snippets
Andy Hung440901d2023-06-29 21:19:25 -07001468 ssize_t threadLoop_write() override;
1469 void threadLoop_standby() override;
1470 void threadLoop_mix() override;
1471 void threadLoop_sleepTime() override;
1472 uint32_t correctLatency_l(uint32_t latency) const final;
Eric Laurent81784c32012-11-19 14:55:58 -08001473
Andy Hung440901d2023-06-29 21:19:25 -07001474 status_t createAudioPatch_l(
1475 const struct audio_patch* patch, audio_patch_handle_t* handle) final;
1476 status_t releaseAudioPatch_l(const audio_patch_handle_t handle) final;
Eric Laurent054d9d32015-04-24 08:48:48 -07001477
Eric Laurent81784c32012-11-19 14:55:58 -08001478 AudioMixer* mAudioMixer; // normal mixer
Eric Laurentb0463942022-12-20 16:31:10 +01001479
1480 // Support low latency mode by default as unless explicitly indicated by the audio HAL
1481 // we assume the audio path is compatible with the head tracking latency requirements
1482 std::vector<audio_latency_mode_t> mSupportedLatencyModes = {AUDIO_LATENCY_MODE_LOW};
1483 // default to invalid value to force first update to the audio HAL
1484 audio_latency_mode_t mSetLatencyMode =
1485 (audio_latency_mode_t)AUDIO_LATENCY_MODE_INVALID;
1486
1487 // Bluetooth Variable latency control logic is enabled or disabled for this thread
1488 std::atomic_bool mBluetoothLatencyModesEnabled;
1489
Eric Laurent81784c32012-11-19 14:55:58 -08001490private:
1491 // one-time initialization, no locks required
Glenn Kasten4d23ca32014-05-13 10:39:51 -07001492 sp<FastMixer> mFastMixer; // non-0 if there is also a fast mixer
Eric Laurent81784c32012-11-19 14:55:58 -08001493 sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread
1494
1495 // contents are not guaranteed to be consistent, no locks required
1496 FastMixerDumpState mFastMixerDumpState;
1497#ifdef STATE_QUEUE_DUMP
1498 StateQueueObserverDump mStateQueueObserverDump;
1499 StateQueueMutatorDump mStateQueueMutatorDump;
1500#endif
1501 AudioWatchdogDump mAudioWatchdogDump;
1502
1503 // accessible only within the threadLoop(), no locks required
1504 // mFastMixer->sq() // for mutating and pushing state
1505 int32_t mFastMixerFutex; // for cold idle
1506
Andy Hung2ddee192015-12-18 17:34:44 -08001507 std::atomic_bool mMasterMono;
Eric Laurent81784c32012-11-19 14:55:58 -08001508public:
Glenn Kasten4d23ca32014-05-13 10:39:51 -07001509 virtual bool hasFastMixer() const { return mFastMixer != 0; }
Eric Laurent81784c32012-11-19 14:55:58 -08001510 virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const {
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001511 ALOG_ASSERT(fastIndex < FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08001512 return mFastMixerDumpState.mTracks[fastIndex].mUnderruns;
1513 }
Eric Laurent83b88082014-06-20 18:31:16 -07001514
Andy Hung1c86ebe2018-05-29 20:29:08 -07001515 status_t threadloop_getHalTimestamp_l(
1516 ExtendedTimestamp *timestamp) const override {
1517 if (mNormalSink.get() != nullptr) {
1518 return mNormalSink->getTimestamp(*timestamp);
1519 }
1520 return INVALID_OPERATION;
1521 }
1522
Eric Laurentb0463942022-12-20 16:31:10 +01001523 status_t getSupportedLatencyModes(
1524 std::vector<audio_latency_mode_t>* modes) override;
1525
1526 status_t setBluetoothVariableLatencyEnabled(bool enabled) override;
1527
Andy Hung2ddee192015-12-18 17:34:44 -08001528protected:
1529 virtual void setMasterMono_l(bool mono) {
1530 mMasterMono.store(mono);
1531 if (mFastMixer != nullptr) { /* hasFastMixer() */
1532 mFastMixer->setMasterMono(mMasterMono);
1533 }
1534 }
1535 // the FastMixer performs mono blend if it exists.
Glenn Kasten03c48d52016-01-27 17:25:17 -08001536 // Blending with limiter is not idempotent,
1537 // and blending without limiter is idempotent but inefficient to do twice.
Andy Hung2ddee192015-12-18 17:34:44 -08001538 virtual bool requireMonoBlend() { return mMasterMono.load() && !hasFastMixer(); }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001539
1540 void setMasterBalance(float balance) override {
1541 mMasterBalance.store(balance);
1542 if (hasFastMixer()) {
1543 mFastMixer->setMasterBalance(balance);
1544 }
1545 }
Eric Laurentb0463942022-12-20 16:31:10 +01001546
1547 void updateHalSupportedLatencyModes_l();
1548 void onHalLatencyModesChanged_l() override;
1549 void setHalLatencyMode_l() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001550};
1551
1552class DirectOutputThread : public PlaybackThread {
1553public:
1554
1555 DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Gareth Fennb18c1a32022-10-05 13:42:36 -07001556 audio_io_handle_t id, bool systemReady,
1557 const audio_offload_info_t& offloadInfo)
1558 : DirectOutputThread(audioFlinger, output, id, DIRECT, systemReady, offloadInfo) { }
Andy Hung48f59ed2019-01-28 15:06:59 -08001559
Eric Laurent81784c32012-11-19 14:55:58 -08001560 virtual ~DirectOutputThread();
1561
Mikhail Naganovac917ac2018-11-28 14:03:52 -08001562 status_t selectPresentation(int presentationId, int programId);
1563
Eric Laurent81784c32012-11-19 14:55:58 -08001564 // Thread virtuals
1565
Eric Laurent10351942014-05-08 18:49:52 -07001566 virtual bool checkForNewParameter_l(const String8& keyValuePair,
1567 status_t& status);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001568
ziyangch8f194f12021-12-01 13:48:04 -08001569 void flushHw_l() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001570
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001571 void setMasterBalance(float balance) override;
1572
Eric Laurent81784c32012-11-19 14:55:58 -08001573protected:
Eric Laurent81784c32012-11-19 14:55:58 -08001574 virtual uint32_t activeSleepTimeUs() const;
1575 virtual uint32_t idleSleepTimeUs() const;
1576 virtual uint32_t suspendSleepTimeUs() const;
1577 virtual void cacheParameters_l();
1578
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001579 void dumpInternals_l(int fd, const Vector<String16>& args) override;
1580
Eric Laurent81784c32012-11-19 14:55:58 -08001581 // threadLoop snippets
Andy Hung8d31fd22023-06-26 19:20:57 -07001582 virtual mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08001583 virtual void threadLoop_mix();
1584 virtual void threadLoop_sleepTime();
Eric Laurentd1f69b02014-12-15 14:33:13 -08001585 virtual void threadLoop_exit();
1586 virtual bool shouldStandby_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001587
Phil Burk43b4dcc2015-06-09 16:53:44 -07001588 virtual void onAddNewTrack_l();
1589
Gareth Fennb18c1a32022-10-05 13:42:36 -07001590 const audio_offload_info_t mOffloadInfo;
Andy Hung398ffa22022-12-13 19:19:53 -08001591
1592 audioflinger::MonotonicFrameCounter mMonotonicFrameCounter; // for VolumeShaper
Andy Hung48f59ed2019-01-28 15:06:59 -08001593 bool mVolumeShaperActive = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001594
Eric Laurentbfb1b832013-01-07 09:53:42 -08001595 DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Gareth Fennb18c1a32022-10-05 13:42:36 -07001596 audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
1597 const audio_offload_info_t& offloadInfo);
Andy Hung8d31fd22023-06-26 19:20:57 -07001598 void processVolume_l(IAfTrack *track, bool lastTrack);
Gareth Fennb18c1a32022-10-05 13:42:36 -07001599 bool isTunerStream() const { return (mOffloadInfo.content_id > 0); }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001600
Eric Laurent81784c32012-11-19 14:55:58 -08001601 // prepareTracks_l() tells threadLoop_mix() the name of the single active track
Andy Hung8d31fd22023-06-26 19:20:57 -07001602 sp<IAfTrack> mActiveTrack;
Phil Burk43b4dcc2015-06-09 16:53:44 -07001603
Andy Hung8d31fd22023-06-26 19:20:57 -07001604 wp<IAfTrack> mPreviousTrack; // used to detect track switch
Phil Burk43b4dcc2015-06-09 16:53:44 -07001605
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001606 // This must be initialized for initial condition of mMasterBalance = 0 (disabled).
1607 float mMasterBalanceLeft = 1.f;
1608 float mMasterBalanceRight = 1.f;
1609
Eric Laurent81784c32012-11-19 14:55:58 -08001610public:
1611 virtual bool hasFastMixer() const { return false; }
Andy Hung10cbff12017-02-21 17:30:14 -08001612
1613 virtual int64_t computeWaitTimeNs_l() const override;
Andy Hungf3234512018-07-03 14:51:47 -07001614
1615 status_t threadloop_getHalTimestamp_l(ExtendedTimestamp *timestamp) const override {
1616 // For DIRECT and OFFLOAD threads, query the output sink directly.
1617 if (mOutput != nullptr) {
1618 uint64_t uposition64;
1619 struct timespec time;
1620 if (mOutput->getPresentationPosition(
1621 &uposition64, &time) == OK) {
1622 timestamp->mPosition[ExtendedTimestamp::LOCATION_KERNEL]
1623 = (int64_t)uposition64;
1624 timestamp->mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
1625 = audio_utils_ns_from_timespec(&time);
1626 return NO_ERROR;
1627 }
1628 }
1629 return INVALID_OPERATION;
1630 }
Eric Laurent81784c32012-11-19 14:55:58 -08001631};
1632
Eric Laurentbfb1b832013-01-07 09:53:42 -08001633class OffloadThread : public DirectOutputThread {
1634public:
1635
1636 OffloadThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Gareth Fennb18c1a32022-10-05 13:42:36 -07001637 audio_io_handle_t id, bool systemReady,
1638 const audio_offload_info_t& offloadInfo);
Eric Laurent6a51d7e2013-10-17 18:59:26 -07001639 virtual ~OffloadThread() {};
ziyangch8f194f12021-12-01 13:48:04 -08001640 void flushHw_l() override;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001641
1642protected:
1643 // threadLoop snippets
Andy Hung8d31fd22023-06-26 19:20:57 -07001644 virtual mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001645 virtual void threadLoop_exit();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001646
1647 virtual bool waitingAsyncCallback();
1648 virtual bool waitingAsyncCallback_l();
Haynes Mathew George05317d22016-05-03 16:34:26 -07001649 virtual void invalidateTracks(audio_stream_type_t streamType);
jiabinc44b3462022-12-08 12:52:31 -08001650 void invalidateTracks(std::set<audio_port_handle_t>& portIds) override;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001651
Eric Laurentde0613d2016-07-22 18:19:11 -07001652 virtual bool keepWakeLock() const { return (mKeepWakeLock || (mDrainSequence & 1)); }
Eric Laurent64667972016-03-30 18:19:46 -07001653
Eric Laurentbfb1b832013-01-07 09:53:42 -08001654private:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001655 size_t mPausedWriteLength; // length in bytes of write interrupted by pause
1656 size_t mPausedBytesRemaining; // bytes still waiting in mixbuffer after resume
Eric Laurent64667972016-03-30 18:19:46 -07001657 bool mKeepWakeLock; // keep wake lock while waiting for write callback
Eric Laurentbfb1b832013-01-07 09:53:42 -08001658};
1659
1660class AsyncCallbackThread : public Thread {
1661public:
1662
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001663 explicit AsyncCallbackThread(const wp<PlaybackThread>& playbackThread);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001664
1665 virtual ~AsyncCallbackThread();
1666
1667 // Thread virtuals
1668 virtual bool threadLoop();
1669
1670 // RefBase
1671 virtual void onFirstRef();
1672
1673 void exit();
Eric Laurent3b4529e2013-09-05 18:09:19 -07001674 void setWriteBlocked(uint32_t sequence);
1675 void resetWriteBlocked();
1676 void setDraining(uint32_t sequence);
1677 void resetDraining();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07001678 void setAsyncError();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001679
1680private:
Eric Laurent4de95592013-09-26 15:28:21 -07001681 const wp<PlaybackThread> mPlaybackThread;
Eric Laurent3b4529e2013-09-05 18:09:19 -07001682 // mWriteAckSequence corresponds to the last write sequence passed by the offload thread via
1683 // setWriteBlocked(). The sequence is shifted one bit to the left and the lsb is used
1684 // to indicate that the callback has been received via resetWriteBlocked()
Eric Laurent4de95592013-09-26 15:28:21 -07001685 uint32_t mWriteAckSequence;
Eric Laurent3b4529e2013-09-05 18:09:19 -07001686 // mDrainSequence corresponds to the last drain sequence passed by the offload thread via
1687 // setDraining(). The sequence is shifted one bit to the left and the lsb is used
1688 // to indicate that the callback has been received via resetDraining()
Eric Laurent4de95592013-09-26 15:28:21 -07001689 uint32_t mDrainSequence;
1690 Condition mWaitWorkCV;
1691 Mutex mLock;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07001692 bool mAsyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001693};
1694
Eric Laurent81784c32012-11-19 14:55:58 -08001695class DuplicatingThread : public MixerThread {
1696public:
1697 DuplicatingThread(const sp<AudioFlinger>& audioFlinger, MixerThread* mainThread,
Eric Laurent72e3f392015-05-20 14:43:50 -07001698 audio_io_handle_t id, bool systemReady);
Eric Laurent81784c32012-11-19 14:55:58 -08001699 virtual ~DuplicatingThread();
1700
1701 // Thread virtuals
1702 void addOutputTrack(MixerThread* thread);
1703 void removeOutputTrack(MixerThread* thread);
1704 uint32_t waitTimeMs() const { return mWaitTimeMs; }
Kevin Rocard069c2712018-03-29 19:09:14 -07001705
Kevin Rocardc86a7f72018-04-03 09:00:09 -07001706 void sendMetadataToBackend_l(
1707 const StreamOutHalInterface::SourceMetadata& metadata) override;
Eric Laurent81784c32012-11-19 14:55:58 -08001708protected:
1709 virtual uint32_t activeSleepTimeUs() const;
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001710 void dumpInternals_l(int fd, const Vector<String16>& args) override;
Eric Laurent81784c32012-11-19 14:55:58 -08001711
1712private:
Andy Hung920f6572022-10-06 12:09:49 -07001713 bool outputsReady();
Eric Laurent81784c32012-11-19 14:55:58 -08001714protected:
1715 // threadLoop snippets
1716 virtual void threadLoop_mix();
1717 virtual void threadLoop_sleepTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001718 virtual ssize_t threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08001719 virtual void threadLoop_standby();
1720 virtual void cacheParameters_l();
1721
1722private:
1723 // called from threadLoop, addOutputTrack, removeOutputTrack
1724 virtual void updateWaitTime_l();
1725protected:
1726 virtual void saveOutputTracks();
1727 virtual void clearOutputTracks();
1728private:
1729
1730 uint32_t mWaitTimeMs;
Andy Hung8d31fd22023-06-26 19:20:57 -07001731 SortedVector <sp<IAfOutputTrack>> outputTracks;
1732 SortedVector <sp<IAfOutputTrack>> mOutputTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08001733public:
1734 virtual bool hasFastMixer() const { return false; }
Andy Hung1c86ebe2018-05-29 20:29:08 -07001735 status_t threadloop_getHalTimestamp_l(
1736 ExtendedTimestamp *timestamp) const override {
1737 if (mOutputTracks.size() > 0) {
1738 // forward the first OutputTrack's kernel information for timestamp.
1739 const ExtendedTimestamp trackTimestamp =
1740 mOutputTracks[0]->getClientProxyTimestamp();
1741 if (trackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] > 0) {
1742 timestamp->mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
1743 trackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
1744 timestamp->mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
1745 trackTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
1746 return OK; // discard server timestamp - that's ignored.
1747 }
1748 }
1749 return INVALID_OPERATION;
1750 }
Eric Laurent81784c32012-11-19 14:55:58 -08001751};
1752
Eric Laurentb0463942022-12-20 16:31:10 +01001753class SpatializerThread : public MixerThread {
Eric Laurentb3f315a2021-07-13 15:09:05 +02001754public:
Eric Laurentfa0f6742021-08-17 18:39:44 +02001755 SpatializerThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurentb3f315a2021-07-13 15:09:05 +02001756 AudioStreamOut* output,
1757 audio_io_handle_t id,
1758 bool systemReady,
1759 audio_config_base_t *mixerConfig);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001760
Andy Hung440901d2023-06-29 21:19:25 -07001761 bool hasFastMixer() const final { return false; }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001762
Eric Laurent68a40a82022-05-03 18:15:04 +02001763 // RefBase
Andy Hung440901d2023-06-29 21:19:25 -07001764 void onFirstRef() final;
Eric Laurent68a40a82022-05-03 18:15:04 +02001765
Andy Hung440901d2023-06-29 21:19:25 -07001766 status_t setRequestedLatencyMode(audio_latency_mode_t mode) final;
Eric Laurent68a40a82022-05-03 18:15:04 +02001767
Eric Laurentb3f315a2021-07-13 15:09:05 +02001768protected:
Andy Hung440901d2023-06-29 21:19:25 -07001769 void checkOutputStageEffects() final;
1770 void setHalLatencyMode_l() final;
Eric Laurentb3f315a2021-07-13 15:09:05 +02001771
1772private:
Eric Laurent68a40a82022-05-03 18:15:04 +02001773 // Do not request a specific mode by default
1774 audio_latency_mode_t mRequestedLatencyMode = AUDIO_LATENCY_MODE_FREE;
1775
Andy Hung116bc262023-06-20 18:56:17 -07001776 sp<IAfEffectHandle> mFinalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02001777};
1778
Eric Laurent81784c32012-11-19 14:55:58 -08001779// record thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001780class RecordThread : public ThreadBase
Eric Laurent81784c32012-11-19 14:55:58 -08001781{
Andy Hung8d31fd22023-06-26 19:20:57 -07001782 // TODO(b/288339104) remove friends
1783 friend class PassthruPatchRecord;
1784 friend class RecordTrack;
1785 friend class ResamplerBufferProvider;
Eric Laurent81784c32012-11-19 14:55:58 -08001786public:
1787
Eric Laurent81784c32012-11-19 14:55:58 -08001788
1789 RecordThread(const sp<AudioFlinger>& audioFlinger,
1790 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08001791 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001792 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08001793 );
Andy Hung440901d2023-06-29 21:19:25 -07001794 ~RecordThread() override;
Eric Laurent81784c32012-11-19 14:55:58 -08001795
1796 // no addTrack_l ?
Andy Hung8d31fd22023-06-26 19:20:57 -07001797 void destroyTrack_l(const sp<IAfRecordTrack>& track);
1798 void removeTrack_l(const sp<IAfRecordTrack>& track);
Eric Laurent81784c32012-11-19 14:55:58 -08001799
Eric Laurent81784c32012-11-19 14:55:58 -08001800 // Thread virtuals
Andy Hung440901d2023-06-29 21:19:25 -07001801 bool threadLoop() final;
1802 void preExit() final;
Eric Laurent81784c32012-11-19 14:55:58 -08001803
1804 // RefBase
Andy Hung440901d2023-06-29 21:19:25 -07001805 void onFirstRef() final;
Eric Laurent81784c32012-11-19 14:55:58 -08001806
Andy Hung440901d2023-06-29 21:19:25 -07001807 status_t initCheck() const final { return mInput == nullptr ? NO_INIT : NO_ERROR; }
Glenn Kastene198c362013-08-13 09:13:36 -07001808
Andy Hung440901d2023-06-29 21:19:25 -07001809 sp<MemoryDealer> readOnlyHeap() const final { return mReadOnlyHeap; }
Glenn Kastenb880f5e2014-05-07 08:43:45 -07001810
Andy Hung440901d2023-06-29 21:19:25 -07001811 sp<IMemory> pipeMemory() const final { return mPipeMemory; }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001812
Andy Hung8d31fd22023-06-26 19:20:57 -07001813 sp<IAfRecordTrack> createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001814 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001815 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001816 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001817 audio_format_t format,
1818 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001819 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08001820 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001821 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07001822 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00001823 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07001824 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001825 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001826 status_t *status /*non-NULL*/,
Eric Laurentec376dc2021-04-08 20:41:22 +02001827 audio_port_handle_t portId,
1828 int32_t maxSharedAudioHistoryMs);
Eric Laurent81784c32012-11-19 14:55:58 -08001829
Andy Hung8d31fd22023-06-26 19:20:57 -07001830 status_t start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08001831 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001832 audio_session_t triggerSession);
Eric Laurent81784c32012-11-19 14:55:58 -08001833
1834 // ask the thread to stop the specified track, and
1835 // return true if the caller should then do it's part of the stopping process
Andy Hung8d31fd22023-06-26 19:20:57 -07001836 bool stop(IAfRecordTrack* recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08001837
Eric Laurent81784c32012-11-19 14:55:58 -08001838 AudioStreamIn* clearInput();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001839 virtual sp<StreamHalInterface> stream() const;
Eric Laurent81784c32012-11-19 14:55:58 -08001840
Eric Laurent81784c32012-11-19 14:55:58 -08001841
Eric Laurent10351942014-05-08 18:49:52 -07001842 virtual bool checkForNewParameter_l(const String8& keyValuePair,
1843 status_t& status);
1844 virtual void cacheParameters_l() {}
Eric Laurent81784c32012-11-19 14:55:58 -08001845 virtual String8 getParameters(const String8& keys);
Mikhail Naganov88536df2021-07-26 17:30:29 -07001846 virtual void ioConfigChanged(audio_io_config_event_t event, pid_t pid = 0,
Eric Laurent09f1ed22019-04-24 17:45:17 -07001847 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE);
Eric Laurent1c333e22014-05-20 10:48:17 -07001848 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
1849 audio_patch_handle_t *handle);
1850 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle);
jiabinc52b1ff2019-10-31 17:20:42 -07001851 void updateOutDevices(const DeviceDescriptorBaseVector& outDevices) override;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02001852 void resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs) override;
Eric Laurent83b88082014-06-20 18:31:16 -07001853
Andy Hung8d31fd22023-06-26 19:20:57 -07001854 void addPatchTrack(const sp<IAfPatchRecord>& record);
1855 void deletePatchTrack(const sp<IAfPatchRecord>& record);
Eric Laurent83b88082014-06-20 18:31:16 -07001856
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001857 void readInputParameters_l();
Glenn Kasten5f972c02014-01-13 09:59:31 -08001858 virtual uint32_t getInputFramesLost();
Eric Laurent81784c32012-11-19 14:55:58 -08001859
Andy Hung116bc262023-06-20 18:56:17 -07001860 virtual status_t addEffectChain_l(const sp<IAfEffectChain>& chain);
1861 virtual size_t removeEffectChain_l(const sp<IAfEffectChain>& chain);
Andy Hungc3d62f92019-03-14 13:38:51 -07001862 uint32_t hasAudioSession_l(audio_session_t sessionId) const override {
1863 return ThreadBase::hasAudioSession_l(sessionId, mTracks);
1864 }
Eric Laurent81784c32012-11-19 14:55:58 -08001865
1866 // Return the set of unique session IDs across all tracks.
1867 // The keys are the session IDs, and the associated values are meaningless.
1868 // FIXME replace by Set [and implement Bag/Multiset for other uses].
Glenn Kastend848eb42016-03-08 13:42:11 -08001869 KeyedVector<audio_session_t, bool> sessionIds() const;
Eric Laurent81784c32012-11-19 14:55:58 -08001870
Andy Hung068e08e2023-05-15 19:02:55 -07001871 status_t setSyncEvent(const sp<audioflinger::SyncEvent>& event) override;
1872 bool isValidSyncEvent(const sp<audioflinger::SyncEvent>& event) const override;
Eric Laurent81784c32012-11-19 14:55:58 -08001873
Andy Hung068e08e2023-05-15 19:02:55 -07001874 static void syncStartEventCallback(const wp<audioflinger::SyncEvent>& event);
Eric Laurent81784c32012-11-19 14:55:58 -08001875
Glenn Kasten9b58f632013-07-16 11:37:48 -07001876 virtual size_t frameCount() const { return mFrameCount; }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001877 bool hasFastCapture() const { return mFastCapture != 0; }
Mikhail Naganovdc769682018-05-04 15:34:08 -07001878 virtual void toAudioPortConfig(struct audio_port_config *config);
Glenn Kasten9b58f632013-07-16 11:37:48 -07001879
Eric Laurent4c415062016-06-17 16:14:16 -07001880 virtual status_t checkEffectCompatibility_l(const effect_descriptor_t *desc,
1881 audio_session_t sessionId);
1882
Andy Hungdae27702016-10-31 14:01:16 -07001883 virtual void acquireWakeLock_l() {
1884 ThreadBase::acquireWakeLock_l();
1885 mActiveTracks.updatePowerState(this, true /* force */);
1886 }
1887
Eric Laurentd8365c52017-07-16 15:27:05 -07001888 void checkBtNrec();
1889
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001890 // Sets the UID records silence
Eric Laurent5ada82e2019-08-29 17:53:54 -07001891 void setRecordSilenced(audio_port_handle_t portId, bool silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001892
Mikhail Naganovd5d9de72023-02-13 11:45:03 -08001893 status_t getActiveMicrophones(
1894 std::vector<media::MicrophoneInfoFw>* activeMicrophones);
jiabin653cc0a2018-01-17 17:54:10 -08001895
Paul McLean12340082019-03-19 09:35:05 -06001896 status_t setPreferredMicrophoneDirection(audio_microphone_direction_t direction);
1897 status_t setPreferredMicrophoneFieldDimension(float zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07001898
Vlad Popa7e81cea2023-01-19 16:34:16 +01001899 MetadataUpdate updateMetadata_l() override;
Kevin Rocard069c2712018-03-29 19:09:14 -07001900
jiabin01c8f562018-07-19 17:47:28 -07001901 bool fastTrackAvailable() const { return mFastTrackAvail; }
1902
Andy Hungc8fddf32018-08-08 18:32:37 -07001903 bool isTimestampCorrectionEnabled() const override {
1904 // checks popcount for exactly one device.
Atneya Nair497fff12022-01-18 16:23:04 -05001905 // Is currently disabled. Before enabling,
1906 // verify compressed record timestamps.
jiabinc52b1ff2019-10-31 17:20:42 -07001907 return audio_is_input_device(mTimestampCorrectedDevice)
1908 && inDeviceType() == mTimestampCorrectedDevice;
Andy Hungc8fddf32018-08-08 18:32:37 -07001909 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001910
Eric Laurentec376dc2021-04-08 20:41:22 +02001911 status_t shareAudioHistory(const std::string& sharedAudioPackageName,
1912 audio_session_t sharedSessionId = AUDIO_SESSION_NONE,
1913 int64_t sharedAudioStartMs = -1);
1914 status_t shareAudioHistory_l(const std::string& sharedAudioPackageName,
1915 audio_session_t sharedSessionId = AUDIO_SESSION_NONE,
1916 int64_t sharedAudioStartMs = -1);
Eric Laurent92d0a322021-07-16 15:32:33 +02001917 void resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02001918
Andy Hung440901d2023-06-29 21:19:25 -07001919 bool isStreamInitialized() const final {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001920 return !(mInput == nullptr || mInput->stream == nullptr);
1921 }
1922
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001923protected:
1924 void dumpInternals_l(int fd, const Vector<String16>& args) override;
1925 void dumpTracks_l(int fd, const Vector<String16>& args) override;
1926
Eric Laurent81784c32012-11-19 14:55:58 -08001927private:
Eric Laurent81784c32012-11-19 14:55:58 -08001928 // Enter standby if not already in standby, and set mStandby flag
Glenn Kasten93e471f2013-08-19 08:40:07 -07001929 void standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08001930
1931 // Call the HAL standby method unconditionally, and don't change mStandby flag
Glenn Kastene198c362013-08-13 09:13:36 -07001932 void inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08001933
Eric Laurentd8365c52017-07-16 15:27:05 -07001934 void checkBtNrec_l();
1935
Eric Laurentec376dc2021-04-08 20:41:22 +02001936 int32_t getOldestFront_l();
1937 void updateFronts_l(int32_t offset);
1938
Eric Laurent81784c32012-11-19 14:55:58 -08001939 AudioStreamIn *mInput;
Mikhail Naganov2534b382019-09-25 13:05:02 -07001940 Source *mSource;
Andy Hung8d31fd22023-06-26 19:20:57 -07001941 SortedVector <sp<IAfRecordTrack>> mTracks;
Glenn Kasten2b806402013-11-20 16:37:38 -08001942 // mActiveTracks has dual roles: it indicates the current active track(s), and
Eric Laurent81784c32012-11-19 14:55:58 -08001943 // is used together with mStartStopCond to indicate start()/stop() progress
Andy Hung8d31fd22023-06-26 19:20:57 -07001944 ActiveTracks<IAfRecordTrack> mActiveTracks;
Andy Hungdae27702016-10-31 14:01:16 -07001945
Eric Laurent81784c32012-11-19 14:55:58 -08001946 Condition mStartStopCond;
Glenn Kasten9b58f632013-07-16 11:37:48 -07001947
Glenn Kasten85948432013-08-19 12:09:05 -07001948 // resampler converts input at HAL Hz to output at AudioRecord client Hz
Glenn Kasten1b291842016-07-18 14:55:21 -07001949 void *mRsmpInBuffer; // size = mRsmpInFramesOA
Glenn Kasten85948432013-08-19 12:09:05 -07001950 size_t mRsmpInFrames; // size of resampler input in frames
1951 size_t mRsmpInFramesP2;// size rounded up to a power-of-2
Glenn Kasten1b291842016-07-18 14:55:21 -07001952 size_t mRsmpInFramesOA;// mRsmpInFramesP2 + over-allocation
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001953
1954 // rolling index that is never cleared
Glenn Kasten85948432013-08-19 12:09:05 -07001955 int32_t mRsmpInRear; // last filled frame + 1
Glenn Kasten85948432013-08-19 12:09:05 -07001956
Eric Laurent81784c32012-11-19 14:55:58 -08001957 // For dumpsys
Glenn Kastenb880f5e2014-05-07 08:43:45 -07001958 const sp<MemoryDealer> mReadOnlyHeap;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001959
1960 // one-time initialization, no locks required
Glenn Kastenb187de12014-12-30 08:18:15 -08001961 sp<FastCapture> mFastCapture; // non-0 if there is also
1962 // a fast capture
Eric Laurent72e3f392015-05-20 14:43:50 -07001963
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001964 // FIXME audio watchdog thread
1965
1966 // contents are not guaranteed to be consistent, no locks required
1967 FastCaptureDumpState mFastCaptureDumpState;
1968#ifdef STATE_QUEUE_DUMP
1969 // FIXME StateQueue observer and mutator dump fields
1970#endif
1971 // FIXME audio watchdog dump
1972
1973 // accessible only within the threadLoop(), no locks required
1974 // mFastCapture->sq() // for mutating and pushing state
1975 int32_t mFastCaptureFutex; // for cold idle
1976
1977 // The HAL input source is treated as non-blocking,
1978 // but current implementation is blocking
1979 sp<NBAIO_Source> mInputSource;
1980 // The source for the normal capture thread to read from: mInputSource or mPipeSource
1981 sp<NBAIO_Source> mNormalSource;
1982 // If a fast capture is present, the non-blocking pipe sink written to by fast capture,
1983 // otherwise clear
1984 sp<NBAIO_Sink> mPipeSink;
1985 // If a fast capture is present, the non-blocking pipe source read by normal thread,
1986 // otherwise clear
1987 sp<NBAIO_Source> mPipeSource;
1988 // Depth of pipe from fast capture to normal thread and fast clients, always power of 2
1989 size_t mPipeFramesP2;
1990 // If a fast capture is present, the Pipe as IMemory, otherwise clear
1991 sp<IMemory> mPipeMemory;
1992
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07001993 // TODO: add comment and adjust size as needed
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001994 static const size_t kFastCaptureLogSize = 4 * 1024;
1995 sp<NBLog::Writer> mFastCaptureNBLogWriter;
1996
1997 bool mFastTrackAvail; // true if fast track available
Eric Laurentd8365c52017-07-16 15:27:05 -07001998 // common state to all record threads
1999 std::atomic_bool mBtNrecSuspended;
Andy Hung6427e442018-08-09 12:51:02 -07002000
2001 int64_t mFramesRead = 0; // continuous running counter.
jiabinc52b1ff2019-10-31 17:20:42 -07002002
2003 DeviceDescriptorBaseVector mOutDevices;
Eric Laurentec376dc2021-04-08 20:41:22 +02002004
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02002005 int32_t mMaxSharedAudioHistoryMs = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02002006 std::string mSharedAudioPackageName = {};
Eric Laurent2407ce32021-04-26 14:56:03 +02002007 int32_t mSharedAudioStartFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02002008 audio_session_t mSharedAudioSessionId = AUDIO_SESSION_NONE;
Eric Laurent81784c32012-11-19 14:55:58 -08002009};
Eric Laurent6acd1d42017-01-04 14:23:29 -08002010
2011class MmapThread : public ThreadBase
2012{
2013 public:
Eric Laurent6acd1d42017-01-04 14:23:29 -08002014 MmapThread(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -07002015 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady,
Andy Hungcf10d742020-04-28 15:38:24 -07002016 bool isOut);
Andy Hung440901d2023-06-29 21:19:25 -07002017 ~MmapThread() override;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002018
2019 virtual void configure(const audio_attributes_t *attr,
2020 audio_stream_type_t streamType,
2021 audio_session_t sessionId,
2022 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07002023 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08002024 audio_port_handle_t portId);
2025
2026 void disconnect();
2027
Andy Hung440901d2023-06-29 21:19:25 -07002028 // MmapStreamInterface for adapter.
2029 virtual status_t createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -08002030 struct audio_mmap_buffer_info *info);
Andy Hung440901d2023-06-29 21:19:25 -07002031 virtual status_t getMmapPosition(struct audio_mmap_position* position);
2032 virtual status_t start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07002033 const audio_attributes_t *attr,
2034 audio_port_handle_t *handle);
Andy Hung440901d2023-06-29 21:19:25 -07002035 virtual status_t stop(audio_port_handle_t handle);
2036 virtual status_t standby();
2037 virtual status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) const = 0;
jiabinfc791ee2023-02-15 19:43:40 +00002038 virtual status_t reportData(const void* buffer, size_t frameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002039
2040 // RefBase
Andy Hung440901d2023-06-29 21:19:25 -07002041 void onFirstRef() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002042
2043 // Thread virtuals
Andy Hung440901d2023-06-29 21:19:25 -07002044 bool threadLoop() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002045
Andy Hung440901d2023-06-29 21:19:25 -07002046 // Not in ThreadBase
2047 virtual void threadLoop_exit() final;
2048 virtual void threadLoop_standby() final;
2049 virtual bool shouldStandby_l() final { return false; }
2050 virtual status_t exitStandby_l() REQUIRES(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002051
Andy Hung440901d2023-06-29 21:19:25 -07002052 status_t initCheck() const final { return mHalStream == nullptr ? NO_INIT : NO_ERROR; }
2053 size_t frameCount() const final { return mFrameCount; }
2054 bool checkForNewParameter_l(const String8& keyValuePair, status_t& status) final;
2055 String8 getParameters(const String8& keys) final;
2056 void ioConfigChanged(audio_io_config_event_t event, pid_t pid = 0,
2057 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002058 void readHalParameters_l();
Andy Hung440901d2023-06-29 21:19:25 -07002059 void cacheParameters_l() final {}
2060 status_t createAudioPatch_l(
2061 const struct audio_patch* patch, audio_patch_handle_t* handle) final;
2062 status_t releaseAudioPatch_l(const audio_patch_handle_t handle) final;
2063 void toAudioPortConfig(struct audio_port_config* config) override;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002064
Andy Hung440901d2023-06-29 21:19:25 -07002065 sp<StreamHalInterface> stream() const final { return mHalStream; }
2066 status_t addEffectChain_l(const sp<IAfEffectChain>& chain) final;
2067 size_t removeEffectChain_l(const sp<IAfEffectChain>& chain) final;
2068 status_t checkEffectCompatibility_l(
2069 const effect_descriptor_t *desc, audio_session_t sessionId) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002070
Andy Hung440901d2023-06-29 21:19:25 -07002071 uint32_t hasAudioSession_l(audio_session_t sessionId) const override {
Andy Hungc3d62f92019-03-14 13:38:51 -07002072 // Note: using mActiveTracks as no mTracks here.
2073 return ThreadBase::hasAudioSession_l(sessionId, mActiveTracks);
2074 }
Andy Hung440901d2023-06-29 21:19:25 -07002075 status_t setSyncEvent(const sp<audioflinger::SyncEvent>& event) final;
2076 bool isValidSyncEvent(const sp<audioflinger::SyncEvent>& event) const final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002077
Andy Hung440901d2023-06-29 21:19:25 -07002078 virtual void checkSilentMode_l() {} // cannot be const (RecordThread)
2079 virtual void processVolume_l() {}
Eric Laurent6acd1d42017-01-04 14:23:29 -08002080 void checkInvalidTracks_l();
2081
Andy Hung440901d2023-06-29 21:19:25 -07002082 // Not in ThreadBase
2083 virtual audio_stream_type_t streamType() const { return AUDIO_STREAM_DEFAULT; }
2084 virtual void invalidateTracks(audio_stream_type_t /* streamType */) {}
2085 virtual void invalidateTracks(std::set<audio_port_handle_t>& /* portIds */) {}
Eric Laurent6acd1d42017-01-04 14:23:29 -08002086
Eric Laurent331679c2018-04-16 17:03:16 -07002087 // Sets the UID records silence
Eric Laurent5ada82e2019-08-29 17:53:54 -07002088 virtual void setRecordSilenced(audio_port_handle_t portId __unused,
2089 bool silenced __unused) {}
Eric Laurent331679c2018-04-16 17:03:16 -07002090
Andy Hung440901d2023-06-29 21:19:25 -07002091 bool isStreamInitialized() const override { return false; }
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002092
jiabin09609032022-06-15 19:26:01 +00002093 void setClientSilencedState_l(audio_port_handle_t portId, bool silenced) {
2094 mClientSilencedStates[portId] = silenced;
2095 }
2096
2097 size_t eraseClientSilencedState_l(audio_port_handle_t portId) {
2098 return mClientSilencedStates.erase(portId);
2099 }
2100
2101 bool isClientSilenced_l(audio_port_handle_t portId) const {
2102 const auto it = mClientSilencedStates.find(portId);
2103 return it != mClientSilencedStates.end() ? it->second : false;
2104 }
2105
2106 void setClientSilencedIfExists_l(audio_port_handle_t portId, bool silenced) {
2107 const auto it = mClientSilencedStates.find(portId);
2108 if (it != mClientSilencedStates.end()) {
2109 it->second = silenced;
2110 }
2111 }
2112
Eric Laurent6acd1d42017-01-04 14:23:29 -08002113 protected:
Andy Hung440901d2023-06-29 21:19:25 -07002114 void dumpInternals_l(int fd, const Vector<String16>& args) override;
2115 void dumpTracks_l(int fd, const Vector<String16>& args) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002116
jiabinc52b1ff2019-10-31 17:20:42 -07002117 /**
2118 * @brief mDeviceId current device port unique identifier
2119 */
2120 audio_port_handle_t mDeviceId = AUDIO_PORT_HANDLE_NONE;
2121
Eric Laurent6acd1d42017-01-04 14:23:29 -08002122 audio_attributes_t mAttr;
2123 audio_session_t mSessionId;
2124 audio_port_handle_t mPortId;
2125
Phil Burk7f6b40d2017-02-09 13:18:38 -08002126 wp<MmapStreamCallback> mCallback;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002127 sp<StreamHalInterface> mHalStream;
2128 sp<DeviceHalInterface> mHalDevice;
2129 AudioHwDevice* const mAudioHwDev;
Andy Hung8d31fd22023-06-26 19:20:57 -07002130 ActiveTracks<IAfMmapTrack> mActiveTracks;
Eric Laurent67f97292018-04-20 18:05:41 -07002131 float mHalVolFloat;
jiabin09609032022-06-15 19:26:01 +00002132 std::map<audio_port_handle_t, bool> mClientSilencedStates;
Eric Laurent331679c2018-04-16 17:03:16 -07002133
2134 int32_t mNoCallbackWarningCount;
2135 static constexpr int32_t kMaxNoCallbackWarnings = 5;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002136};
2137
2138class MmapPlaybackThread : public MmapThread, public VolumeInterface
2139{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002140public:
2141 MmapPlaybackThread(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07002142 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002143
Andy Hung440901d2023-06-29 21:19:25 -07002144 void configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08002145 audio_stream_type_t streamType,
2146 audio_session_t sessionId,
2147 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07002148 audio_port_handle_t deviceId,
Andy Hung440901d2023-06-29 21:19:25 -07002149 audio_port_handle_t portId) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002150
2151 AudioStreamOut* clearOutput();
2152
2153 // VolumeInterface
Andy Hung440901d2023-06-29 21:19:25 -07002154 void setMasterVolume(float value) final;
2155 void setMasterBalance(float /* value */) final {} // Needs implementation?
2156 void setMasterMute(bool muted) final;
2157 void setStreamVolume(audio_stream_type_t stream, float value) final;
2158 void setStreamMute(audio_stream_type_t stream, bool muted) final;
2159 float streamVolume(audio_stream_type_t stream) const final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002160
2161 void setMasterMute_l(bool muted) { mMasterMute = muted; }
2162
Andy Hung440901d2023-06-29 21:19:25 -07002163 void invalidateTracks(audio_stream_type_t streamType) final;
2164 void invalidateTracks(std::set<audio_port_handle_t>& portIds) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002165
Andy Hung440901d2023-06-29 21:19:25 -07002166 audio_stream_type_t streamType() const final { return mStreamType; }
2167 void checkSilentMode_l() final;
2168 void processVolume_l() final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002169
Andy Hung440901d2023-06-29 21:19:25 -07002170 MetadataUpdate updateMetadata_l() final;
Kevin Rocard069c2712018-03-29 19:09:14 -07002171
Andy Hung440901d2023-06-29 21:19:25 -07002172 void toAudioPortConfig(struct audio_port_config* config) final;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07002173
Andy Hung440901d2023-06-29 21:19:25 -07002174 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) const final;
jiabinb7d8c5a2020-08-26 17:24:52 -07002175
Andy Hung440901d2023-06-29 21:19:25 -07002176 bool isStreamInitialized() const final {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002177 return !(mOutput == nullptr || mOutput->stream == nullptr);
2178 }
2179
Andy Hung440901d2023-06-29 21:19:25 -07002180 status_t reportData(const void* buffer, size_t frameCount) final;
jiabinfc791ee2023-02-15 19:43:40 +00002181
Andy Hung440901d2023-06-29 21:19:25 -07002182 void startMelComputation_l(const sp<audio_utils::MelProcessor>& processor) final;
2183 void stopMelComputation_l() final;
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002184
Eric Laurent6acd1d42017-01-04 14:23:29 -08002185protected:
Andy Hung440901d2023-06-29 21:19:25 -07002186 void dumpInternals_l(int fd, const Vector<String16>& args) final;
Eric Laurent1f9b5e62023-07-03 18:14:07 +02002187 float streamVolume_l() const {
2188 return mStreamTypes[mStreamType].volume;
2189 }
2190 bool streamMuted_l() const {
2191 return mStreamTypes[mStreamType].mute;
2192 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002193
Eric Laurent1f9b5e62023-07-03 18:14:07 +02002194 stream_type_t mStreamTypes[AUDIO_STREAM_CNT];
Eric Laurent6acd1d42017-01-04 14:23:29 -08002195 audio_stream_type_t mStreamType;
2196 float mMasterVolume;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002197 bool mMasterMute;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002198 AudioStreamOut* mOutput;
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002199
2200 mediautils::atomic_sp<audio_utils::MelProcessor> mMelProcessor;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002201};
2202
2203class MmapCaptureThread : public MmapThread
2204{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002205public:
2206 MmapCaptureThread(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07002207 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002208
2209 AudioStreamIn* clearInput();
2210
Andy Hung440901d2023-06-29 21:19:25 -07002211 status_t exitStandby_l() REQUIRES(mLock) final;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002212
Andy Hung440901d2023-06-29 21:19:25 -07002213 MetadataUpdate updateMetadata_l() final;
2214 void processVolume_l() final;
2215 void setRecordSilenced(audio_port_handle_t portId, bool silenced) final;
Kevin Rocard069c2712018-03-29 19:09:14 -07002216
Andy Hung440901d2023-06-29 21:19:25 -07002217 void toAudioPortConfig(struct audio_port_config* config) final;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07002218
Andy Hung440901d2023-06-29 21:19:25 -07002219 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) const final;
jiabinb7d8c5a2020-08-26 17:24:52 -07002220
Andy Hung440901d2023-06-29 21:19:25 -07002221 bool isStreamInitialized() const final {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002222 return !(mInput == nullptr || mInput->stream == nullptr);
2223 }
2224
Eric Laurent6acd1d42017-01-04 14:23:29 -08002225protected:
2226
2227 AudioStreamIn* mInput;
2228};
jiabinc658e452022-10-21 20:52:21 +00002229
2230class BitPerfectThread : public MixerThread {
2231public:
2232 BitPerfectThread(const sp<AudioFlinger>& audioflinger, AudioStreamOut *output,
2233 audio_io_handle_t id, bool systemReady);
2234
2235protected:
Andy Hung440901d2023-06-29 21:19:25 -07002236 mixer_state prepareTracks_l(Vector<sp<IAfTrack>>* tracksToRemove) final;
2237 void threadLoop_mix() final;
jiabinc658e452022-10-21 20:52:21 +00002238
2239private:
2240 bool mIsBitPerfect;
jiabin76d94692022-12-15 21:51:21 +00002241 float mVolumeLeft = 0.f;
2242 float mVolumeRight = 0.f;
jiabinc658e452022-10-21 20:52:21 +00002243};
Andy Hunga5a7fc92023-06-23 19:27:19 -07002244
Andy Hung440901d2023-06-29 21:19:25 -07002245private: