blob: 18cb361d3b89de23b563ed1902a75c2b8ebf116f [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
22class ThreadBase : public Thread {
23public:
24
25#include "TrackBase.h"
26
27 enum type_t {
28 MIXER, // Thread class is MixerThread
29 DIRECT, // Thread class is DirectOutputThread
30 DUPLICATING, // Thread class is DuplicatingThread
Eric Laurentbfb1b832013-01-07 09:53:42 -080031 RECORD, // Thread class is RecordThread
Eric Laurent6acd1d42017-01-04 14:23:29 -080032 OFFLOAD, // Thread class is OffloadThread
33 MMAP // control thread for MMAP stream
Glenn Kasten1bfe09a2017-02-21 13:05:56 -080034 // If you add any values here, also update ThreadBase::threadTypeToString()
Eric Laurent81784c32012-11-19 14:55:58 -080035 };
36
Glenn Kasten97b7b752014-09-28 13:04:24 -070037 static const char *threadTypeToString(type_t type);
38
Eric Laurent81784c32012-11-19 14:55:58 -080039 ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -070040 audio_devices_t outDevice, audio_devices_t inDevice, type_t type,
41 bool systemReady);
Eric Laurent81784c32012-11-19 14:55:58 -080042 virtual ~ThreadBase();
43
Glenn Kastencf04c2c2013-08-06 07:41:16 -070044 virtual status_t readyToRun();
45
Eric Laurent81784c32012-11-19 14:55:58 -080046 void clearPowerManager();
47
48 // base for record and playback
49 enum {
50 CFG_EVENT_IO,
Eric Laurent10351942014-05-08 18:49:52 -070051 CFG_EVENT_PRIO,
52 CFG_EVENT_SET_PARAMETER,
Eric Laurent1c333e22014-05-20 10:48:17 -070053 CFG_EVENT_CREATE_AUDIO_PATCH,
54 CFG_EVENT_RELEASE_AUDIO_PATCH,
Eric Laurent81784c32012-11-19 14:55:58 -080055 };
56
Eric Laurent10351942014-05-08 18:49:52 -070057 class ConfigEventData: public RefBase {
Eric Laurent81784c32012-11-19 14:55:58 -080058 public:
Eric Laurent10351942014-05-08 18:49:52 -070059 virtual ~ConfigEventData() {}
Eric Laurent81784c32012-11-19 14:55:58 -080060
61 virtual void dump(char *buffer, size_t size) = 0;
Eric Laurent10351942014-05-08 18:49:52 -070062 protected:
63 ConfigEventData() {}
Eric Laurent81784c32012-11-19 14:55:58 -080064 };
65
Eric Laurent10351942014-05-08 18:49:52 -070066 // Config event sequence by client if status needed (e.g binder thread calling setParameters()):
67 // 1. create SetParameterConfigEvent. This sets mWaitStatus in config event
68 // 2. Lock mLock
69 // 3. Call sendConfigEvent_l(): Append to mConfigEvents and mWaitWorkCV.signal
70 // 4. sendConfigEvent_l() reads status from event->mStatus;
71 // 5. sendConfigEvent_l() returns status
72 // 6. Unlock
73 //
74 // Parameter sequence by server: threadLoop calling processConfigEvents_l():
75 // 1. Lock mLock
76 // 2. If there is an entry in mConfigEvents proceed ...
77 // 3. Read first entry in mConfigEvents
78 // 4. Remove first entry from mConfigEvents
79 // 5. Process
80 // 6. Set event->mStatus
81 // 7. event->mCond.signal
82 // 8. Unlock
Eric Laurent81784c32012-11-19 14:55:58 -080083
Eric Laurent10351942014-05-08 18:49:52 -070084 class ConfigEvent: public RefBase {
85 public:
86 virtual ~ConfigEvent() {}
87
88 void dump(char *buffer, size_t size) { mData->dump(buffer, size); }
89
90 const int mType; // event type e.g. CFG_EVENT_IO
91 Mutex mLock; // mutex associated with mCond
92 Condition mCond; // condition for status return
93 status_t mStatus; // status communicated to sender
94 bool mWaitStatus; // true if sender is waiting for status
Eric Laurent72e3f392015-05-20 14:43:50 -070095 bool mRequiresSystemReady; // true if must wait for system ready to enter event queue
Eric Laurent10351942014-05-08 18:49:52 -070096 sp<ConfigEventData> mData; // event specific parameter data
97
98 protected:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -070099 explicit ConfigEvent(int type, bool requiresSystemReady = false) :
Eric Laurent72e3f392015-05-20 14:43:50 -0700100 mType(type), mStatus(NO_ERROR), mWaitStatus(false),
101 mRequiresSystemReady(requiresSystemReady), mData(NULL) {}
Eric Laurent10351942014-05-08 18:49:52 -0700102 };
103
104 class IoConfigEventData : public ConfigEventData {
105 public:
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700106 IoConfigEventData(audio_io_config_event event, pid_t pid) :
107 mEvent(event), mPid(pid) {}
Eric Laurent81784c32012-11-19 14:55:58 -0800108
109 virtual void dump(char *buffer, size_t size) {
Eric Laurent73e26b62015-04-27 16:55:58 -0700110 snprintf(buffer, size, "IO event: event %d\n", mEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800111 }
112
Eric Laurent73e26b62015-04-27 16:55:58 -0700113 const audio_io_config_event mEvent;
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700114 const pid_t mPid;
Eric Laurent81784c32012-11-19 14:55:58 -0800115 };
116
Eric Laurent10351942014-05-08 18:49:52 -0700117 class IoConfigEvent : public ConfigEvent {
Eric Laurent81784c32012-11-19 14:55:58 -0800118 public:
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700119 IoConfigEvent(audio_io_config_event event, pid_t pid) :
Eric Laurent10351942014-05-08 18:49:52 -0700120 ConfigEvent(CFG_EVENT_IO) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700121 mData = new IoConfigEventData(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700122 }
123 virtual ~IoConfigEvent() {}
124 };
Eric Laurent81784c32012-11-19 14:55:58 -0800125
Eric Laurent10351942014-05-08 18:49:52 -0700126 class PrioConfigEventData : public ConfigEventData {
127 public:
Mikhail Naganov83f04272017-02-07 10:45:09 -0800128 PrioConfigEventData(pid_t pid, pid_t tid, int32_t prio, bool forApp) :
129 mPid(pid), mTid(tid), mPrio(prio), mForApp(forApp) {}
Eric Laurent81784c32012-11-19 14:55:58 -0800130
131 virtual void dump(char *buffer, size_t size) {
Mikhail Naganov83f04272017-02-07 10:45:09 -0800132 snprintf(buffer, size, "Prio event: pid %d, tid %d, prio %d, for app? %d\n",
133 mPid, mTid, mPrio, mForApp);
Eric Laurent81784c32012-11-19 14:55:58 -0800134 }
135
Eric Laurent81784c32012-11-19 14:55:58 -0800136 const pid_t mPid;
137 const pid_t mTid;
138 const int32_t mPrio;
Mikhail Naganov83f04272017-02-07 10:45:09 -0800139 const bool mForApp;
Eric Laurent81784c32012-11-19 14:55:58 -0800140 };
141
Eric Laurent10351942014-05-08 18:49:52 -0700142 class PrioConfigEvent : public ConfigEvent {
143 public:
Mikhail Naganov83f04272017-02-07 10:45:09 -0800144 PrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp) :
Eric Laurent72e3f392015-05-20 14:43:50 -0700145 ConfigEvent(CFG_EVENT_PRIO, true) {
Mikhail Naganov83f04272017-02-07 10:45:09 -0800146 mData = new PrioConfigEventData(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700147 }
148 virtual ~PrioConfigEvent() {}
149 };
150
151 class SetParameterConfigEventData : public ConfigEventData {
152 public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700153 explicit SetParameterConfigEventData(String8 keyValuePairs) :
Eric Laurent10351942014-05-08 18:49:52 -0700154 mKeyValuePairs(keyValuePairs) {}
155
156 virtual void dump(char *buffer, size_t size) {
157 snprintf(buffer, size, "KeyValue: %s\n", mKeyValuePairs.string());
158 }
159
160 const String8 mKeyValuePairs;
161 };
162
163 class SetParameterConfigEvent : public ConfigEvent {
164 public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700165 explicit SetParameterConfigEvent(String8 keyValuePairs) :
Eric Laurent10351942014-05-08 18:49:52 -0700166 ConfigEvent(CFG_EVENT_SET_PARAMETER) {
167 mData = new SetParameterConfigEventData(keyValuePairs);
168 mWaitStatus = true;
169 }
170 virtual ~SetParameterConfigEvent() {}
171 };
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) {
180 snprintf(buffer, size, "Patch handle: %u\n", mHandle);
181 }
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 }
195 virtual ~CreateAudioPatchConfigEvent() {}
196 };
197
198 class ReleaseAudioPatchConfigEventData : public ConfigEventData {
199 public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700200 explicit ReleaseAudioPatchConfigEventData(const audio_patch_handle_t handle) :
Eric Laurent1c333e22014-05-20 10:48:17 -0700201 mHandle(handle) {}
202
203 virtual void dump(char *buffer, size_t size) {
204 snprintf(buffer, size, "Patch handle: %u\n", mHandle);
205 }
206
207 audio_patch_handle_t mHandle;
208 };
209
210 class ReleaseAudioPatchConfigEvent : public ConfigEvent {
211 public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700212 explicit ReleaseAudioPatchConfigEvent(const audio_patch_handle_t handle) :
Eric Laurent1c333e22014-05-20 10:48:17 -0700213 ConfigEvent(CFG_EVENT_RELEASE_AUDIO_PATCH) {
214 mData = new ReleaseAudioPatchConfigEventData(handle);
215 mWaitStatus = true;
216 }
217 virtual ~ReleaseAudioPatchConfigEvent() {}
218 };
Eric Laurent81784c32012-11-19 14:55:58 -0800219
220 class PMDeathRecipient : public IBinder::DeathRecipient {
221 public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700222 explicit PMDeathRecipient(const wp<ThreadBase>& thread) : mThread(thread) {}
Eric Laurent81784c32012-11-19 14:55:58 -0800223 virtual ~PMDeathRecipient() {}
224
225 // IBinder::DeathRecipient
226 virtual void binderDied(const wp<IBinder>& who);
227
228 private:
Mikhail Naganovbf493082017-04-17 17:37:12 -0700229 DISALLOW_COPY_AND_ASSIGN(PMDeathRecipient);
Eric Laurent81784c32012-11-19 14:55:58 -0800230
231 wp<ThreadBase> mThread;
232 };
233
234 virtual status_t initCheck() const = 0;
235
236 // static externally-visible
237 type_t type() const { return mType; }
Eric Laurentf6870ae2015-05-08 10:50:03 -0700238 bool isDuplicating() const { return (mType == DUPLICATING); }
239
Eric Laurent81784c32012-11-19 14:55:58 -0800240 audio_io_handle_t id() const { return mId;}
241
242 // dynamic externally-visible
243 uint32_t sampleRate() const { return mSampleRate; }
Eric Laurent81784c32012-11-19 14:55:58 -0800244 audio_channel_mask_t channelMask() const { return mChannelMask; }
Andy Hung463be252014-07-10 16:56:07 -0700245 audio_format_t format() const { return mHALFormat; }
Eric Laurent83b88082014-06-20 18:31:16 -0700246 uint32_t channelCount() const { return mChannelCount; }
Eric Laurent81784c32012-11-19 14:55:58 -0800247 // Called by AudioFlinger::frameCount(audio_io_handle_t output) and effects,
Glenn Kasten9b58f632013-07-16 11:37:48 -0700248 // and returns the [normal mix] buffer's frame count.
249 virtual size_t frameCount() const = 0;
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700250
251 // Return's the HAL's frame count i.e. fast mixer buffer size.
252 size_t frameCountHAL() const { return mFrameCount; }
253
Eric Laurentbfb1b832013-01-07 09:53:42 -0800254 size_t frameSize() const { return mFrameSize; }
Eric Laurent81784c32012-11-19 14:55:58 -0800255
256 // Should be "virtual status_t requestExitAndWait()" and override same
257 // method in Thread, but Thread::requestExitAndWait() is not yet virtual.
258 void exit();
Eric Laurent10351942014-05-08 18:49:52 -0700259 virtual bool checkForNewParameter_l(const String8& keyValuePair,
260 status_t& status) = 0;
Eric Laurent81784c32012-11-19 14:55:58 -0800261 virtual status_t setParameters(const String8& keyValuePairs);
262 virtual String8 getParameters(const String8& keys) = 0;
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700263 virtual void ioConfigChanged(audio_io_config_event event, pid_t pid = 0) = 0;
Eric Laurent10351942014-05-08 18:49:52 -0700264 // sendConfigEvent_l() must be called with ThreadBase::mLock held
265 // Can temporarily release the lock if waiting for a reply from
266 // processConfigEvents_l().
267 status_t sendConfigEvent_l(sp<ConfigEvent>& event);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700268 void sendIoConfigEvent(audio_io_config_event event, pid_t pid = 0);
269 void sendIoConfigEvent_l(audio_io_config_event event, pid_t pid = 0);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800270 void sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp);
271 void sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio, bool forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700272 status_t sendSetParameterConfigEvent_l(const String8& keyValuePair);
Eric Laurent1c333e22014-05-20 10:48:17 -0700273 status_t sendCreateAudioPatchConfigEvent(const struct audio_patch *patch,
274 audio_patch_handle_t *handle);
275 status_t sendReleaseAudioPatchConfigEvent(audio_patch_handle_t handle);
Eric Laurent021cf962014-05-13 10:18:14 -0700276 void processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -0700277 virtual void cacheParameters_l() = 0;
Eric Laurent1c333e22014-05-20 10:48:17 -0700278 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
279 audio_patch_handle_t *handle) = 0;
280 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle) = 0;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700281 virtual void toAudioPortConfig(struct audio_port_config *config) = 0;
Eric Laurent1c333e22014-05-20 10:48:17 -0700282
Eric Laurent81784c32012-11-19 14:55:58 -0800283
284 // see note at declaration of mStandby, mOutDevice and mInDevice
285 bool standby() const { return mStandby; }
286 audio_devices_t outDevice() const { return mOutDevice; }
287 audio_devices_t inDevice() const { return mInDevice; }
Andy Hung293558a2017-03-21 12:19:20 -0700288 audio_devices_t getDevice() const { return isOutput() ? mOutDevice : mInDevice; }
289
290 virtual bool isOutput() const = 0;
Eric Laurent81784c32012-11-19 14:55:58 -0800291
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700292 virtual sp<StreamHalInterface> stream() const = 0;
Eric Laurent81784c32012-11-19 14:55:58 -0800293
294 sp<EffectHandle> createEffect_l(
295 const sp<AudioFlinger::Client>& client,
296 const sp<IEffectClient>& effectClient,
297 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -0800298 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -0800299 effect_descriptor_t *desc,
300 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -0800301 status_t *status /*non-NULL*/,
302 bool pinned);
Eric Laurent81784c32012-11-19 14:55:58 -0800303
304 // return values for hasAudioSession (bit field)
305 enum effect_state {
306 EFFECT_SESSION = 0x1, // the audio session corresponds to at least one
307 // effect
Eric Laurent4c415062016-06-17 16:14:16 -0700308 TRACK_SESSION = 0x2, // the audio session corresponds to at least one
Eric Laurent81784c32012-11-19 14:55:58 -0800309 // track
Eric Laurent4c415062016-06-17 16:14:16 -0700310 FAST_SESSION = 0x4 // the audio session corresponds to at least one
311 // fast track
Eric Laurent81784c32012-11-19 14:55:58 -0800312 };
313
314 // get effect chain corresponding to session Id.
Glenn Kastend848eb42016-03-08 13:42:11 -0800315 sp<EffectChain> getEffectChain(audio_session_t sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800316 // same as getEffectChain() but must be called with ThreadBase mutex locked
Glenn Kastend848eb42016-03-08 13:42:11 -0800317 sp<EffectChain> getEffectChain_l(audio_session_t sessionId) const;
Eric Laurent81784c32012-11-19 14:55:58 -0800318 // add an effect chain to the chain list (mEffectChains)
319 virtual status_t addEffectChain_l(const sp<EffectChain>& chain) = 0;
320 // remove an effect chain from the chain list (mEffectChains)
321 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain) = 0;
322 // lock all effect chains Mutexes. Must be called before releasing the
323 // ThreadBase mutex before processing the mixer and effects. This guarantees the
324 // integrity of the chains during the process.
325 // Also sets the parameter 'effectChains' to current value of mEffectChains.
326 void lockEffectChains_l(Vector< sp<EffectChain> >& effectChains);
327 // unlock effect chains after process
328 void unlockEffectChains(const Vector< sp<EffectChain> >& effectChains);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800329 // get a copy of mEffectChains vector
330 Vector< sp<EffectChain> > getEffectChains_l() const { return mEffectChains; };
Eric Laurent81784c32012-11-19 14:55:58 -0800331 // set audio mode to all effect chains
332 void setMode(audio_mode_t mode);
333 // get effect module with corresponding ID on specified audio session
Glenn Kastend848eb42016-03-08 13:42:11 -0800334 sp<AudioFlinger::EffectModule> getEffect(audio_session_t sessionId, int effectId);
335 sp<AudioFlinger::EffectModule> getEffect_l(audio_session_t sessionId, int effectId);
Eric Laurent81784c32012-11-19 14:55:58 -0800336 // add and effect module. Also creates the effect chain is none exists for
337 // the effects audio session
338 status_t addEffect_l(const sp< EffectModule>& effect);
339 // remove and effect module. Also removes the effect chain is this was the last
340 // effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -0800341 void removeEffect_l(const sp< EffectModule>& effect, bool release = false);
342 // disconnect an effect handle from module and destroy module if last handle
343 void disconnectEffectHandle(EffectHandle *handle, bool unpinIfLast);
Eric Laurent81784c32012-11-19 14:55:58 -0800344 // detach all tracks connected to an auxiliary effect
Glenn Kasten0f11b512014-01-31 16:18:54 -0800345 virtual void detachAuxEffect_l(int effectId __unused) {}
Eric Laurent4c415062016-06-17 16:14:16 -0700346 // returns a combination of:
347 // - EFFECT_SESSION if effects on this audio session exist in one chain
348 // - TRACK_SESSION if tracks on this audio session exist
349 // - FAST_SESSION if fast tracks on this audio session exist
350 virtual uint32_t hasAudioSession_l(audio_session_t sessionId) const = 0;
351 uint32_t hasAudioSession(audio_session_t sessionId) const {
352 Mutex::Autolock _l(mLock);
353 return hasAudioSession_l(sessionId);
354 }
355
Andy Hungc3d62f92019-03-14 13:38:51 -0700356 template <typename T>
357 uint32_t hasAudioSession_l(audio_session_t sessionId, const T& tracks) const {
358 uint32_t result = 0;
359 if (getEffectChain_l(sessionId) != 0) {
360 result = EFFECT_SESSION;
361 }
362 for (size_t i = 0; i < tracks.size(); ++i) {
363 const sp<TrackBase>& track = tracks[i];
364 if (sessionId == track->sessionId()
365 && !track->isInvalid() // not yet removed from tracks.
366 && !track->isTerminated()) {
367 result |= TRACK_SESSION;
368 if (track->isFastTrack()) {
369 result |= FAST_SESSION; // caution, only represents first track.
370 }
371 break;
372 }
373 }
374 return result;
375 }
376
Eric Laurent81784c32012-11-19 14:55:58 -0800377 // the value returned by default implementation is not important as the
378 // strategy is only meaningful for PlaybackThread which implements this method
Glenn Kastend848eb42016-03-08 13:42:11 -0800379 virtual uint32_t getStrategyForSession_l(audio_session_t sessionId __unused)
380 { return 0; }
Eric Laurent81784c32012-11-19 14:55:58 -0800381
Eric Laurent81784c32012-11-19 14:55:58 -0800382 // check if some effects must be suspended/restored when an effect is enabled
383 // or disabled
384 void checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
385 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -0800386 audio_session_t sessionId =
387 AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -0800388 void checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
389 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -0800390 audio_session_t sessionId =
391 AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -0800392
393 virtual status_t setSyncEvent(const sp<SyncEvent>& event) = 0;
394 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const = 0;
395
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700396 // Return a reference to a per-thread heap which can be used to allocate IMemory
397 // objects that will be read-only to client processes, read/write to mediaserver,
398 // and shared by all client processes of the thread.
399 // The heap is per-thread rather than common across all threads, because
400 // clients can't be trusted not to modify the offset of the IMemory they receive.
401 // If a thread does not have such a heap, this method returns 0.
402 virtual sp<MemoryDealer> readOnlyHeap() const { return 0; }
Eric Laurent81784c32012-11-19 14:55:58 -0800403
Glenn Kasten6181ffd2014-05-13 10:41:52 -0700404 virtual sp<IMemory> pipeMemory() const { return 0; }
405
Eric Laurent72e3f392015-05-20 14:43:50 -0700406 void systemReady();
407
Eric Laurent4c415062016-06-17 16:14:16 -0700408 // checkEffectCompatibility_l() must be called with ThreadBase::mLock held
409 virtual status_t checkEffectCompatibility_l(const effect_descriptor_t *desc,
410 audio_session_t sessionId) = 0;
411
Eric Laurent6acd1d42017-01-04 14:23:29 -0800412 void broadcast_l();
413
Andy Hungc8fddf32018-08-08 18:32:37 -0700414 virtual bool isTimestampCorrectionEnabled() const { return false; }
415
416 bool isMsdDevice() const { return mIsMsdDevice; }
417
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700418 void dump(int fd, const Vector<String16>& args);
Andy Hungdc099c22018-09-18 13:46:39 -0700419
Andy Hungd0979812019-02-21 15:51:44 -0800420 // deliver stats to mediametrics.
421 void sendStatistics(bool force);
422
Eric Laurent81784c32012-11-19 14:55:58 -0800423 mutable Mutex mLock;
424
425protected:
426
427 // entry describing an effect being suspended in mSuspendedSessions keyed vector
428 class SuspendedSessionDesc : public RefBase {
429 public:
430 SuspendedSessionDesc() : mRefCount(0) {}
431
432 int mRefCount; // number of active suspend requests
433 effect_uuid_t mType; // effect type UUID
434 };
435
Andy Hungdae27702016-10-31 14:01:16 -0700436 void acquireWakeLock();
437 virtual void acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800438 void releaseWakeLock();
439 void releaseWakeLock_l();
Andy Hungd01b0f12016-11-07 16:10:30 -0800440 void updateWakeLockUids_l(const SortedVector<uid_t> &uids);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800441 void getPowerManager_l();
Eric Laurentd8365c52017-07-16 15:27:05 -0700442 // suspend or restore effects of the specified type (or all if type is NULL)
443 // on a given session. The number of suspend requests is counted and restore
444 // occurs when all suspend requests are cancelled.
Eric Laurent81784c32012-11-19 14:55:58 -0800445 void setEffectSuspended_l(const effect_uuid_t *type,
446 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -0800447 audio_session_t sessionId);
Eric Laurentd8365c52017-07-16 15:27:05 -0700448 // updated mSuspendedSessions when an effect is suspended or restored
Eric Laurent81784c32012-11-19 14:55:58 -0800449 void updateSuspendedSessions_l(const effect_uuid_t *type,
450 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -0800451 audio_session_t sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800452 // check if some effects must be suspended when an effect chain is added
453 void checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain);
454
Kevin Rocard069c2712018-03-29 19:09:14 -0700455 // sends the metadata of the active tracks to the HAL
456 virtual void updateMetadata_l() = 0;
457
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100458 String16 getWakeLockTag();
459
Eric Laurent81784c32012-11-19 14:55:58 -0800460 virtual void preExit() { }
Andy Hung2ddee192015-12-18 17:34:44 -0800461 virtual void setMasterMono_l(bool mono __unused) { }
462 virtual bool requireMonoBlend() { return false; }
Eric Laurent81784c32012-11-19 14:55:58 -0800463
Andy Hung1c86ebe2018-05-29 20:29:08 -0700464 // called within the threadLoop to obtain timestamp from the HAL.
465 virtual status_t threadloop_getHalTimestamp_l(
466 ExtendedTimestamp *timestamp __unused) const {
467 return INVALID_OPERATION;
468 }
469
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700470 virtual void dumpInternals_l(int fd __unused, const Vector<String16>& args __unused)
471 { }
472 virtual void dumpTracks_l(int fd __unused, const Vector<String16>& args __unused) { }
473
474
Eric Laurent81784c32012-11-19 14:55:58 -0800475 friend class AudioFlinger; // for mEffectChains
476
477 const type_t mType;
478
479 // Used by parameters, config events, addTrack_l, exit
480 Condition mWaitWorkCV;
481
482 const sp<AudioFlinger> mAudioFlinger;
Glenn Kasten9b58f632013-07-16 11:37:48 -0700483
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800484 // updated by PlaybackThread::readOutputParameters_l() or
485 // RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800486 uint32_t mSampleRate;
487 size_t mFrameCount; // output HAL, direct output, record
Eric Laurent81784c32012-11-19 14:55:58 -0800488 audio_channel_mask_t mChannelMask;
Glenn Kastenf6ed4232013-07-16 11:16:27 -0700489 uint32_t mChannelCount;
Eric Laurent81784c32012-11-19 14:55:58 -0800490 size_t mFrameSize;
Glenn Kasten97b7b752014-09-28 13:04:24 -0700491 // not HAL frame size, this is for output sink (to pipe to fast mixer)
Andy Hung463be252014-07-10 16:56:07 -0700492 audio_format_t mFormat; // Source format for Recording and
493 // Sink format for Playback.
494 // Sink format may be different than
495 // HAL format if Fastmixer is used.
496 audio_format_t mHALFormat;
Glenn Kasten70949c42013-08-06 07:40:12 -0700497 size_t mBufferSize; // HAL buffer size for read() or write()
Eric Laurent81784c32012-11-19 14:55:58 -0800498
Eric Laurent10351942014-05-08 18:49:52 -0700499 Vector< sp<ConfigEvent> > mConfigEvents;
Eric Laurent72e3f392015-05-20 14:43:50 -0700500 Vector< sp<ConfigEvent> > mPendingConfigEvents; // events awaiting system ready
Eric Laurent81784c32012-11-19 14:55:58 -0800501
502 // These fields are written and read by thread itself without lock or barrier,
Glenn Kasten4944acb2013-08-19 08:39:20 -0700503 // and read by other threads without lock or barrier via standby(), outDevice()
Eric Laurent81784c32012-11-19 14:55:58 -0800504 // and inDevice().
505 // Because of the absence of a lock or barrier, any other thread that reads
506 // these fields must use the information in isolation, or be prepared to deal
507 // with possibility that it might be inconsistent with other information.
Glenn Kasten4944acb2013-08-19 08:39:20 -0700508 bool mStandby; // Whether thread is currently in standby.
Eric Laurent81784c32012-11-19 14:55:58 -0800509 audio_devices_t mOutDevice; // output device
510 audio_devices_t mInDevice; // input device
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700511 audio_devices_t mPrevOutDevice; // previous output device
Eric Laurente8726fe2015-06-26 09:39:24 -0700512 audio_devices_t mPrevInDevice; // previous input device
Eric Laurent296fb132015-05-01 11:38:42 -0700513 struct audio_patch mPatch;
François Gaffie0c280aa2018-07-25 10:02:15 +0200514 /**
515 * @brief mDeviceId current device port unique identifier
516 */
517 audio_port_handle_t mDeviceId = AUDIO_PORT_HANDLE_NONE;
Glenn Kastenf59497b2015-01-26 16:35:47 -0800518 audio_source_t mAudioSource;
Eric Laurent81784c32012-11-19 14:55:58 -0800519
520 const audio_io_handle_t mId;
521 Vector< sp<EffectChain> > mEffectChains;
522
Glenn Kastend7dca052015-03-05 16:05:54 -0800523 static const int kThreadNameLength = 16; // prctl(PR_SET_NAME) limit
524 char mThreadName[kThreadNameLength]; // guaranteed NUL-terminated
Eric Laurent81784c32012-11-19 14:55:58 -0800525 sp<IPowerManager> mPowerManager;
526 sp<IBinder> mWakeLockToken;
527 const sp<PMDeathRecipient> mDeathRecipient;
Glenn Kastend848eb42016-03-08 13:42:11 -0800528 // list of suspended effects per session and per type. The first (outer) vector is
529 // keyed by session ID, the second (inner) by type UUID timeLow field
Eric Laurentd8365c52017-07-16 15:27:05 -0700530 // Updated by updateSuspendedSessions_l() only.
Glenn Kastend848eb42016-03-08 13:42:11 -0800531 KeyedVector< audio_session_t, KeyedVector< int, sp<SuspendedSessionDesc> > >
Eric Laurent81784c32012-11-19 14:55:58 -0800532 mSuspendedSessions;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -0700533 // TODO: add comment and adjust size as needed
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800534 static const size_t kLogSize = 4 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -0800535 sp<NBLog::Writer> mNBLogWriter;
Eric Laurent72e3f392015-05-20 14:43:50 -0700536 bool mSystemReady;
Andy Hung818e7a32016-02-16 18:08:07 -0800537 ExtendedTimestamp mTimestamp;
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700538 TimestampVerifier< // For timestamp statistics.
539 int64_t /* frame count */, int64_t /* time ns */> mTimestampVerifier;
Andy Hungc8fddf32018-08-08 18:32:37 -0700540 audio_devices_t mTimestampCorrectedDevices = AUDIO_DEVICE_NONE;
Andy Hung446f4df2019-02-21 12:26:41 -0800541
542 // ThreadLoop statistics per iteration.
543 int64_t mLastIoBeginNs = -1;
544 int64_t mLastIoEndNs = -1;
545
546 // This should be read under ThreadBase lock (if not on the threadLoop thread).
547 audio_utils::Statistics<double> mIoJitterMs{0.995 /* alpha */};
548 audio_utils::Statistics<double> mProcessTimeMs{0.995 /* alpha */};
Andy Hunge6c37112019-02-26 17:38:10 -0800549 audio_utils::Statistics<double> mLatencyMs{0.995 /* alpha */};
Andy Hung446f4df2019-02-21 12:26:41 -0800550
Andy Hungd0979812019-02-21 15:51:44 -0800551 // Save the last count when we delivered statistics to mediametrics.
552 int64_t mLastRecordedTimestampVerifierN = 0;
553 int64_t mLastRecordedTimeNs = 0; // BOOTTIME to include suspend.
554
Andy Hungc8fddf32018-08-08 18:32:37 -0700555 bool mIsMsdDevice = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800556 // A condition that must be evaluated by the thread loop has changed and
557 // we must not wait for async write callback in the thread loop before evaluating it
558 bool mSignalPending;
Andy Hungdae27702016-10-31 14:01:16 -0700559
Andy Hung8946a282018-04-19 20:04:56 -0700560#ifdef TEE_SINK
561 NBAIO_Tee mTee;
562#endif
Andy Hungdae27702016-10-31 14:01:16 -0700563 // ActiveTracks is a sorted vector of track type T representing the
564 // active tracks of threadLoop() to be considered by the locked prepare portion.
565 // ActiveTracks should be accessed with the ThreadBase lock held.
566 //
567 // During processing and I/O, the threadLoop does not hold the lock;
568 // hence it does not directly use ActiveTracks. Care should be taken
569 // to hold local strong references or defer removal of tracks
570 // if the threadLoop may still be accessing those tracks due to mix, etc.
571 //
572 // This class updates power information appropriately.
573 //
574
575 template <typename T>
576 class ActiveTracks {
577 public:
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700578 explicit ActiveTracks(SimpleLog *localLog = nullptr)
Andy Hungdae27702016-10-31 14:01:16 -0700579 : mActiveTracksGeneration(0)
580 , mLastActiveTracksGeneration(0)
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700581 , mLocalLog(localLog)
Andy Hungdae27702016-10-31 14:01:16 -0700582 { }
583
584 ~ActiveTracks() {
585 ALOGW_IF(!mActiveTracks.isEmpty(),
586 "ActiveTracks should be empty in destructor");
587 }
588 // returns the last track added (even though it may have been
589 // subsequently removed from ActiveTracks).
590 //
591 // Used for DirectOutputThread to ensure a flush is called when transitioning
592 // to a new track (even though it may be on the same session).
593 // Used for OffloadThread to ensure that volume and mixer state is
594 // taken from the latest track added.
595 //
596 // The latest track is saved with a weak pointer to prevent keeping an
597 // otherwise useless track alive. Thus the function will return nullptr
598 // if the latest track has subsequently been removed and destroyed.
599 sp<T> getLatest() {
600 return mLatestActiveTrack.promote();
601 }
602
603 // SortedVector methods
604 ssize_t add(const sp<T> &track);
605 ssize_t remove(const sp<T> &track);
606 size_t size() const {
607 return mActiveTracks.size();
608 }
Eric Tan39ec8d62018-07-24 09:49:29 -0700609 bool isEmpty() const {
610 return mActiveTracks.isEmpty();
611 }
Andy Hungdae27702016-10-31 14:01:16 -0700612 ssize_t indexOf(const sp<T>& item) {
613 return mActiveTracks.indexOf(item);
614 }
615 sp<T> operator[](size_t index) const {
616 return mActiveTracks[index];
617 }
618 typename SortedVector<sp<T>>::iterator begin() {
619 return mActiveTracks.begin();
620 }
621 typename SortedVector<sp<T>>::iterator end() {
622 return mActiveTracks.end();
623 }
624
625 // Due to Binder recursion optimization, clear() and updatePowerState()
626 // cannot be called from a Binder thread because they may call back into
627 // the original calling process (system server) for BatteryNotifier
628 // (which requires a Java environment that may not be present).
629 // Hence, call clear() and updatePowerState() only from the
630 // ThreadBase thread.
631 void clear();
632 // periodically called in the threadLoop() to update power state uids.
633 void updatePowerState(sp<ThreadBase> thread, bool force = false);
634
Kevin Rocardc86a7f72018-04-03 09:00:09 -0700635 /** @return true if one or move active tracks was added or removed since the
636 * last time this function was called or the vector was created. */
Kevin Rocard069c2712018-03-29 19:09:14 -0700637 bool readAndClearHasChanged();
638
Andy Hungdae27702016-10-31 14:01:16 -0700639 private:
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700640 void logTrack(const char *funcName, const sp<T> &track) const;
641
Andy Hungd01b0f12016-11-07 16:10:30 -0800642 SortedVector<uid_t> getWakeLockUids() {
643 SortedVector<uid_t> wakeLockUids;
Andy Hungdae27702016-10-31 14:01:16 -0700644 for (const sp<T> &track : mActiveTracks) {
645 wakeLockUids.add(track->uid());
646 }
647 return wakeLockUids; // moved by underlying SharedBuffer
648 }
649
650 std::map<uid_t, std::pair<ssize_t /* previous */, ssize_t /* current */>>
651 mBatteryCounter;
652 SortedVector<sp<T>> mActiveTracks;
653 int mActiveTracksGeneration;
654 int mLastActiveTracksGeneration;
655 wp<T> mLatestActiveTrack; // latest track added to ActiveTracks
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700656 SimpleLog * const mLocalLog;
Kevin Rocardc86a7f72018-04-03 09:00:09 -0700657 // If the vector has changed since last call to readAndClearHasChanged
Kevin Rocard069c2712018-03-29 19:09:14 -0700658 bool mHasChanged = false;
Andy Hungdae27702016-10-31 14:01:16 -0700659 };
Andy Hung293558a2017-03-21 12:19:20 -0700660
661 SimpleLog mLocalLog;
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700662
663private:
664 void dumpBase_l(int fd, const Vector<String16>& args);
665 void dumpEffectChains_l(int fd, const Vector<String16>& args);
Eric Laurent81784c32012-11-19 14:55:58 -0800666};
667
Eric Laurent6acd1d42017-01-04 14:23:29 -0800668class VolumeInterface {
669 public:
670
671 virtual ~VolumeInterface() {}
672
673 virtual void setMasterVolume(float value) = 0;
674 virtual void setMasterMute(bool muted) = 0;
675 virtual void setStreamVolume(audio_stream_type_t stream, float value) = 0;
676 virtual void setStreamMute(audio_stream_type_t stream, bool muted) = 0;
677 virtual float streamVolume(audio_stream_type_t stream) const = 0;
678
679};
680
Eric Laurent81784c32012-11-19 14:55:58 -0800681// --- PlaybackThread ---
Eric Laurent6acd1d42017-01-04 14:23:29 -0800682class PlaybackThread : public ThreadBase, public StreamOutHalInterfaceCallback,
683 public VolumeInterface {
Eric Laurent81784c32012-11-19 14:55:58 -0800684public:
685
686#include "PlaybackTracks.h"
687
688 enum mixer_state {
689 MIXER_IDLE, // no active tracks
690 MIXER_TRACKS_ENABLED, // at least one active track, but no track has any data ready
Eric Laurentbfb1b832013-01-07 09:53:42 -0800691 MIXER_TRACKS_READY, // at least one active track, and at least one track has data
692 MIXER_DRAIN_TRACK, // drain currently playing track
693 MIXER_DRAIN_ALL, // fully drain the hardware
Eric Laurent81784c32012-11-19 14:55:58 -0800694 // standby mode does not have an enum value
695 // suspend by audio policy manager is orthogonal to mixer state
696 };
697
Eric Laurente93cc032016-05-05 10:15:10 -0700698 // retry count before removing active track in case of underrun on offloaded thread:
699 // we need to make sure that AudioTrack client has enough time to send large buffers
700 //FIXME may be more appropriate if expressed in time units. Need to revise how underrun is
701 // handled for offloaded tracks
702 static const int8_t kMaxTrackRetriesOffload = 20;
703 static const int8_t kMaxTrackStartupRetriesOffload = 100;
704 static const int8_t kMaxTrackStopRetriesOffload = 2;
Andy Hung8ed196a2018-01-05 13:21:11 -0800705 static constexpr uint32_t kMaxTracksPerUid = 40;
Andy Hung1bc088a2018-02-09 15:57:31 -0800706 static constexpr size_t kMaxTracks = 256;
Eric Laurente93cc032016-05-05 10:15:10 -0700707
rago1bb90822017-05-02 18:31:48 -0700708 // Maximum delay (in nanoseconds) for upcoming buffers in suspend mode, otherwise
709 // if delay is greater, the estimated time for timeLoopNextNs is reset.
710 // This allows for catch-up to be done for small delays, while resetting the estimate
711 // for initial conditions or large delays.
712 static const nsecs_t kMaxNextBufferDelayNs = 100000000;
713
Eric Laurent81784c32012-11-19 14:55:58 -0800714 PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurente93cc032016-05-05 10:15:10 -0700715 audio_io_handle_t id, audio_devices_t device, type_t type, bool systemReady);
Eric Laurent81784c32012-11-19 14:55:58 -0800716 virtual ~PlaybackThread();
717
Eric Laurent81784c32012-11-19 14:55:58 -0800718 // Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -0800719 virtual bool threadLoop();
720
721 // RefBase
722 virtual void onFirstRef();
723
Eric Laurent4c415062016-06-17 16:14:16 -0700724 virtual status_t checkEffectCompatibility_l(const effect_descriptor_t *desc,
725 audio_session_t sessionId);
726
Eric Laurent81784c32012-11-19 14:55:58 -0800727protected:
728 // Code snippets that were lifted up out of threadLoop()
729 virtual void threadLoop_mix() = 0;
730 virtual void threadLoop_sleepTime() = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800731 virtual ssize_t threadLoop_write();
732 virtual void threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -0800733 virtual void threadLoop_standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800734 virtual void threadLoop_exit();
Eric Laurent81784c32012-11-19 14:55:58 -0800735 virtual void threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
736
737 // prepareTracks_l reads and writes mActiveTracks, and returns
738 // the pending set of tracks to remove via Vector 'tracksToRemove'. The caller
739 // is responsible for clearing or destroying this Vector later on, when it
740 // is safe to do so. That will drop the final ref count and destroy the tracks.
741 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove) = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800742 void removeTracks_l(const Vector< sp<Track> >& tracksToRemove);
743
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700744 // StreamOutHalInterfaceCallback implementation
745 virtual void onWriteReady();
746 virtual void onDrainReady();
747 virtual void onError();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800748
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700749 void resetWriteBlocked(uint32_t sequence);
750 void resetDraining(uint32_t sequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800751
752 virtual bool waitingAsyncCallback();
753 virtual bool waitingAsyncCallback_l();
754 virtual bool shouldStandby_l();
Haynes Mathew George4c6a4332014-01-15 12:31:39 -0800755 virtual void onAddNewTrack_l();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -0700756 void onAsyncError(); // error reported by AsyncCallbackThread
Eric Laurent81784c32012-11-19 14:55:58 -0800757
758 // ThreadBase virtuals
759 virtual void preExit();
760
Eric Laurent64667972016-03-30 18:19:46 -0700761 virtual bool keepWakeLock() const { return true; }
Andy Hungdae27702016-10-31 14:01:16 -0700762 virtual void acquireWakeLock_l() {
763 ThreadBase::acquireWakeLock_l();
764 mActiveTracks.updatePowerState(this, true /* force */);
765 }
Eric Laurent64667972016-03-30 18:19:46 -0700766
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700767 void dumpInternals_l(int fd, const Vector<String16>& args) override;
768 void dumpTracks_l(int fd, const Vector<String16>& args) override;
769
Eric Laurent81784c32012-11-19 14:55:58 -0800770public:
771
772 virtual status_t initCheck() const { return (mOutput == NULL) ? NO_INIT : NO_ERROR; }
773
774 // return estimated latency in milliseconds, as reported by HAL
775 uint32_t latency() const;
776 // same, but lock must already be held
777 uint32_t latency_l() const;
778
Eric Laurent6acd1d42017-01-04 14:23:29 -0800779 // VolumeInterface
780 virtual void setMasterVolume(float value);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +0100781 virtual void setMasterBalance(float balance);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800782 virtual void setMasterMute(bool muted);
783 virtual void setStreamVolume(audio_stream_type_t stream, float value);
784 virtual void setStreamMute(audio_stream_type_t stream, bool muted);
785 virtual float streamVolume(audio_stream_type_t stream) const;
Eric Laurent81784c32012-11-19 14:55:58 -0800786
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +0900787 void setVolumeForOutput_l(float left, float right) const;
788
Eric Laurent81784c32012-11-19 14:55:58 -0800789 sp<Track> createTrack_l(
790 const sp<AudioFlinger::Client>& client,
791 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700792 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -0800793 uint32_t *sampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -0800794 audio_format_t format,
795 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -0800796 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -0800797 size_t *pNotificationFrameCount,
798 uint32_t notificationsPerBuffer,
799 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -0800800 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -0800801 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -0700802 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -0800803 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -0800804 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800805 status_t *status /*non-NULL*/,
806 audio_port_handle_t portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800807
808 AudioStreamOut* getOutput() const;
809 AudioStreamOut* clearOutput();
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700810 virtual sp<StreamHalInterface> stream() const;
Eric Laurent81784c32012-11-19 14:55:58 -0800811
812 // a very large number of suspend() will eventually wraparound, but unlikely
813 void suspend() { (void) android_atomic_inc(&mSuspended); }
814 void restore()
815 {
816 // if restore() is done without suspend(), get back into
817 // range so that the next suspend() will operate correctly
818 if (android_atomic_dec(&mSuspended) <= 0) {
819 android_atomic_release_store(0, &mSuspended);
820 }
821 }
822 bool isSuspended() const
823 { return android_atomic_acquire_load(&mSuspended) > 0; }
824
825 virtual String8 getParameters(const String8& keys);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700826 virtual void ioConfigChanged(audio_io_config_event event, pid_t pid = 0);
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000827 status_t getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames);
Andy Hung010a1a12014-03-13 13:57:33 -0700828 // Consider also removing and passing an explicit mMainBuffer initialization
829 // parameter to AF::PlaybackThread::Track::Track().
rago94a1ee82017-07-21 15:11:02 -0700830 effect_buffer_t *sinkBuffer() const {
831 return reinterpret_cast<effect_buffer_t *>(mSinkBuffer); };
Eric Laurent81784c32012-11-19 14:55:58 -0800832
833 virtual void detachAuxEffect_l(int effectId);
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700834 status_t attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track>& track,
Eric Laurent81784c32012-11-19 14:55:58 -0800835 int EffectId);
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700836 status_t attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track>& track,
Eric Laurent81784c32012-11-19 14:55:58 -0800837 int EffectId);
838
839 virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
840 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
Andy Hungc3d62f92019-03-14 13:38:51 -0700841 uint32_t hasAudioSession_l(audio_session_t sessionId) const override {
842 return ThreadBase::hasAudioSession_l(sessionId, mTracks);
843 }
Glenn Kastend848eb42016-03-08 13:42:11 -0800844 virtual uint32_t getStrategyForSession_l(audio_session_t sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800845
846
847 virtual status_t setSyncEvent(const sp<SyncEvent>& event);
848 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const;
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700849
850 // called with AudioFlinger lock held
Eric Laurent13084622016-05-17 10:51:49 -0700851 bool invalidateTracks_l(audio_stream_type_t streamType);
Haynes Mathew George05317d22016-05-03 16:34:26 -0700852 virtual void invalidateTracks(audio_stream_type_t streamType);
Eric Laurent81784c32012-11-19 14:55:58 -0800853
Glenn Kasten9b58f632013-07-16 11:37:48 -0700854 virtual size_t frameCount() const { return mNormalFrameCount; }
855
Eric Laurent83b88082014-06-20 18:31:16 -0700856 status_t getTimestamp_l(AudioTimestamp& timestamp);
857
858 void addPatchTrack(const sp<PatchTrack>& track);
859 void deletePatchTrack(const sp<PatchTrack>& track);
860
Mikhail Naganovdc769682018-05-04 15:34:08 -0700861 virtual void toAudioPortConfig(struct audio_port_config *config);
Eric Laurentaccc1472013-09-20 09:36:34 -0700862
Andy Hung10cbff12017-02-21 17:30:14 -0800863 // Return the asynchronous signal wait time.
864 virtual int64_t computeWaitTimeNs_l() const { return INT64_MAX; }
865
Andy Hung293558a2017-03-21 12:19:20 -0700866 virtual bool isOutput() const override { return true; }
867
Andy Hung1bc088a2018-02-09 15:57:31 -0800868 // returns true if the track is allowed to be added to the thread.
869 virtual bool isTrackAllowed_l(
870 audio_channel_mask_t channelMask __unused,
871 audio_format_t format __unused,
872 audio_session_t sessionId __unused,
873 uid_t uid) const {
874 return trackCountForUid_l(uid) < PlaybackThread::kMaxTracksPerUid
875 && mTracks.size() < PlaybackThread::kMaxTracks;
876 }
877
Andy Hungc8fddf32018-08-08 18:32:37 -0700878 bool isTimestampCorrectionEnabled() const override {
879 const audio_devices_t device =
880 mOutDevice & mTimestampCorrectedDevices;
881 return audio_is_output_devices(device) && popcount(device) > 0;
882 }
Eric Laurent81784c32012-11-19 14:55:58 -0800883protected:
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800884 // updated by readOutputParameters_l()
Glenn Kasten9b58f632013-07-16 11:37:48 -0700885 size_t mNormalFrameCount; // normal mixer and effects
886
Andy Hung08fb1742015-05-31 23:22:10 -0700887 bool mThreadThrottle; // throttle the thread processing
Andy Hung40eb1a12015-06-18 13:42:02 -0700888 uint32_t mThreadThrottleTimeMs; // throttle time for MIXER threads
889 uint32_t mThreadThrottleEndMs; // notify once per throttling
Andy Hung08fb1742015-05-31 23:22:10 -0700890 uint32_t mHalfBufferMs; // half the buffer size in milliseconds
891
Andy Hung010a1a12014-03-13 13:57:33 -0700892 void* mSinkBuffer; // frame size aligned sink buffer
Eric Laurent81784c32012-11-19 14:55:58 -0800893
Andy Hung98ef9782014-03-04 14:46:50 -0800894 // TODO:
895 // Rearrange the buffer info into a struct/class with
896 // clear, copy, construction, destruction methods.
897 //
898 // mSinkBuffer also has associated with it:
899 //
900 // mSinkBufferSize: Sink Buffer Size
901 // mFormat: Sink Buffer Format
902
Andy Hung69aed5f2014-02-25 17:24:40 -0800903 // Mixer Buffer (mMixerBuffer*)
904 //
905 // In the case of floating point or multichannel data, which is not in the
906 // sink format, it is required to accumulate in a higher precision or greater channel count
907 // buffer before downmixing or data conversion to the sink buffer.
908
909 // Set to "true" to enable the Mixer Buffer otherwise mixer output goes to sink buffer.
910 bool mMixerBufferEnabled;
911
912 // Storage, 32 byte aligned (may make this alignment a requirement later).
913 // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
914 void* mMixerBuffer;
915
916 // Size of mMixerBuffer in bytes: mNormalFrameCount * #channels * sampsize.
917 size_t mMixerBufferSize;
918
919 // The audio format of mMixerBuffer. Set to AUDIO_FORMAT_PCM_(FLOAT|16_BIT) only.
920 audio_format_t mMixerBufferFormat;
921
922 // An internal flag set to true by MixerThread::prepareTracks_l()
923 // when mMixerBuffer contains valid data after mixing.
924 bool mMixerBufferValid;
925
Andy Hung98ef9782014-03-04 14:46:50 -0800926 // Effects Buffer (mEffectsBuffer*)
927 //
928 // In the case of effects data, which is not in the sink format,
929 // it is required to accumulate in a different buffer before data conversion
930 // to the sink buffer.
931
932 // Set to "true" to enable the Effects Buffer otherwise effects output goes to sink buffer.
933 bool mEffectBufferEnabled;
934
935 // Storage, 32 byte aligned (may make this alignment a requirement later).
936 // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
937 void* mEffectBuffer;
938
939 // Size of mEffectsBuffer in bytes: mNormalFrameCount * #channels * sampsize.
940 size_t mEffectBufferSize;
941
942 // The audio format of mEffectsBuffer. Set to AUDIO_FORMAT_PCM_16_BIT only.
943 audio_format_t mEffectBufferFormat;
944
945 // An internal flag set to true by MixerThread::prepareTracks_l()
946 // when mEffectsBuffer contains valid data after mixing.
947 //
948 // When this is set, all mixer data is routed into the effects buffer
949 // for any processing (including output processing).
950 bool mEffectBufferValid;
951
Eric Laurent81784c32012-11-19 14:55:58 -0800952 // suspend count, > 0 means suspended. While suspended, the thread continues to pull from
953 // tracks and mix, but doesn't write to HAL. A2DP and SCO HAL implementations can't handle
954 // concurrent use of both of them, so Audio Policy Service suspends one of the threads to
955 // workaround that restriction.
956 // 'volatile' means accessed via atomic operations and no lock.
957 volatile int32_t mSuspended;
958
Andy Hung818e7a32016-02-16 18:08:07 -0800959 int64_t mBytesWritten;
Andy Hungc54b1ff2016-02-23 14:07:07 -0800960 int64_t mFramesWritten; // not reset on standby
Andy Hung238fa3d2016-07-28 10:53:22 -0700961 int64_t mSuspendedFrames; // not reset on standby
jiabin245cdd92018-12-07 17:55:15 -0800962
963 // mHapticChannelMask and mHapticChannelCount will only be valid when the thread support
964 // haptic playback.
965 audio_channel_mask_t mHapticChannelMask = AUDIO_CHANNEL_NONE;
966 uint32_t mHapticChannelCount = 0;
Eric Laurent81784c32012-11-19 14:55:58 -0800967private:
968 // mMasterMute is in both PlaybackThread and in AudioFlinger. When a
969 // PlaybackThread needs to find out if master-muted, it checks it's local
970 // copy rather than the one in AudioFlinger. This optimization saves a lock.
971 bool mMasterMute;
972 void setMasterMute_l(bool muted) { mMasterMute = muted; }
973protected:
Andy Hungdae27702016-10-31 14:01:16 -0700974 ActiveTracks<Track> mActiveTracks;
Eric Laurent81784c32012-11-19 14:55:58 -0800975
Eric Laurent81784c32012-11-19 14:55:58 -0800976 // Time to sleep between cycles when:
977 virtual uint32_t activeSleepTimeUs() const; // mixer state MIXER_TRACKS_ENABLED
978 virtual uint32_t idleSleepTimeUs() const = 0; // mixer state MIXER_IDLE
979 virtual uint32_t suspendSleepTimeUs() const = 0; // audio policy manager suspended us
980 // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write()
981 // No sleep in standby mode; waits on a condition
982
983 // Code snippets that are temporarily lifted up out of threadLoop() until the merge
984 void checkSilentMode_l();
985
986 // Non-trivial for DUPLICATING only
987 virtual void saveOutputTracks() { }
988 virtual void clearOutputTracks() { }
989
990 // Cache various calculated values, at threadLoop() entry and after a parameter change
991 virtual void cacheParameters_l();
992
993 virtual uint32_t correctLatency_l(uint32_t latency) const;
994
Eric Laurent1c333e22014-05-20 10:48:17 -0700995 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
996 audio_patch_handle_t *handle);
997 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle);
998
Phil Burk6fc2a7c2015-04-30 16:08:10 -0700999 bool usesHwAvSync() const { return (mType == DIRECT) && (mOutput != NULL)
1000 && mHwSupportsPause
1001 && (mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC); }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08001002
Andy Hung1bc088a2018-02-09 15:57:31 -08001003 uint32_t trackCountForUid_l(uid_t uid) const;
Eric Laurentad7dd962016-09-22 12:38:37 -07001004
Eric Laurent81784c32012-11-19 14:55:58 -08001005private:
1006
1007 friend class AudioFlinger; // for numerous
1008
Mikhail Naganovbf493082017-04-17 17:37:12 -07001009 DISALLOW_COPY_AND_ASSIGN(PlaybackThread);
Eric Laurent81784c32012-11-19 14:55:58 -08001010
1011 status_t addTrack_l(const sp<Track>& track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001012 bool destroyTrack_l(const sp<Track>& track);
Eric Laurent81784c32012-11-19 14:55:58 -08001013 void removeTrack_l(const sp<Track>& track);
1014
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001015 void readOutputParameters_l();
Kevin Rocardc86a7f72018-04-03 09:00:09 -07001016 void updateMetadata_l() final;
1017 virtual void sendMetadataToBackend_l(const StreamOutHalInterface::SourceMetadata& metadata);
Eric Laurent81784c32012-11-19 14:55:58 -08001018
Andy Hungc0691382018-09-12 18:01:57 -07001019 // The Tracks class manages tracks added and removed from the Thread.
Andy Hung1bc088a2018-02-09 15:57:31 -08001020 template <typename T>
1021 class Tracks {
1022 public:
Andy Hungc0691382018-09-12 18:01:57 -07001023 Tracks(bool saveDeletedTrackIds) :
1024 mSaveDeletedTrackIds(saveDeletedTrackIds) { }
Andy Hung1bc088a2018-02-09 15:57:31 -08001025
1026 // SortedVector methods
Andy Hungc0691382018-09-12 18:01:57 -07001027 ssize_t add(const sp<T> &track) {
1028 const ssize_t index = mTracks.add(track);
1029 LOG_ALWAYS_FATAL_IF(index < 0, "cannot add track");
1030 return index;
1031 }
Andy Hung1bc088a2018-02-09 15:57:31 -08001032 ssize_t remove(const sp<T> &track);
1033 size_t size() const {
1034 return mTracks.size();
1035 }
1036 bool isEmpty() const {
1037 return mTracks.isEmpty();
1038 }
1039 ssize_t indexOf(const sp<T> &item) {
1040 return mTracks.indexOf(item);
1041 }
1042 sp<T> operator[](size_t index) const {
1043 return mTracks[index];
1044 }
1045 typename SortedVector<sp<T>>::iterator begin() {
1046 return mTracks.begin();
1047 }
1048 typename SortedVector<sp<T>>::iterator end() {
1049 return mTracks.end();
1050 }
1051
Andy Hungc0691382018-09-12 18:01:57 -07001052 size_t processDeletedTrackIds(std::function<void(int)> f) {
1053 for (const int trackId : mDeletedTrackIds) {
1054 f(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08001055 }
Andy Hungc0691382018-09-12 18:01:57 -07001056 return mDeletedTrackIds.size();
Andy Hung1bc088a2018-02-09 15:57:31 -08001057 }
1058
Andy Hungc0691382018-09-12 18:01:57 -07001059 void clearDeletedTrackIds() { mDeletedTrackIds.clear(); }
Andy Hung1bc088a2018-02-09 15:57:31 -08001060
1061 private:
Andy Hungc0691382018-09-12 18:01:57 -07001062 // Tracks pending deletion for MIXER type threads
1063 const bool mSaveDeletedTrackIds; // true to enable tracking
1064 std::set<int> mDeletedTrackIds;
Andy Hung1bc088a2018-02-09 15:57:31 -08001065
1066 SortedVector<sp<T>> mTracks; // wrapped SortedVector.
1067 };
1068
1069 Tracks<Track> mTracks;
1070
Eric Laurent223fd5c2014-11-11 13:43:36 -08001071 stream_type_t mStreamTypes[AUDIO_STREAM_CNT];
Eric Laurent81784c32012-11-19 14:55:58 -08001072 AudioStreamOut *mOutput;
1073
1074 float mMasterVolume;
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001075 std::atomic<float> mMasterBalance{};
1076 audio_utils::Balance mBalance;
Eric Laurent81784c32012-11-19 14:55:58 -08001077 int mNumWrites;
1078 int mNumDelayedWrites;
1079 bool mInWrite;
1080
1081 // FIXME rename these former local variables of threadLoop to standard "m" names
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001082 nsecs_t mStandbyTimeNs;
Andy Hung25c2dac2014-02-27 14:56:00 -08001083 size_t mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001084
1085 // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l()
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001086 uint32_t mActiveSleepTimeUs;
1087 uint32_t mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08001088
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001089 uint32_t mSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08001090
1091 // mixer status returned by prepareTracks_l()
1092 mixer_state mMixerStatus; // current cycle
1093 // previous cycle when in prepareTracks_l()
1094 mixer_state mMixerStatusIgnoringFastTracks;
1095 // FIXME or a separate ready state per track
1096
1097 // FIXME move these declarations into the specific sub-class that needs them
1098 // MIXER only
1099 uint32_t sleepTimeShift;
1100
1101 // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001102 nsecs_t mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08001103
1104 // MIXER only
1105 nsecs_t maxPeriod;
1106
1107 // DUPLICATING only
1108 uint32_t writeFrames;
1109
Eric Laurentbfb1b832013-01-07 09:53:42 -08001110 size_t mBytesRemaining;
1111 size_t mCurrentWriteLength;
1112 bool mUseAsyncWrite;
Eric Laurent3b4529e2013-09-05 18:09:19 -07001113 // mWriteAckSequence contains current write sequence on bits 31-1. The write sequence is
1114 // incremented each time a write(), a flush() or a standby() occurs.
1115 // Bit 0 is set when a write blocks and indicates a callback is expected.
1116 // Bit 0 is reset by the async callback thread calling resetWriteBlocked(). Out of sequence
1117 // callbacks are ignored.
1118 uint32_t mWriteAckSequence;
1119 // mDrainSequence contains current drain sequence on bits 31-1. The drain sequence is
1120 // incremented each time a drain is requested or a flush() or standby() occurs.
1121 // Bit 0 is set when the drain() command is called at the HAL and indicates a callback is
1122 // expected.
1123 // Bit 0 is reset by the async callback thread calling resetDraining(). Out of sequence
1124 // callbacks are ignored.
1125 uint32_t mDrainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001126 sp<AsyncCallbackThread> mCallbackThread;
1127
Eric Laurent81784c32012-11-19 14:55:58 -08001128private:
1129 // The HAL output sink is treated as non-blocking, but current implementation is blocking
1130 sp<NBAIO_Sink> mOutputSink;
1131 // If a fast mixer is present, the blocking pipe sink, otherwise clear
1132 sp<NBAIO_Sink> mPipeSink;
1133 // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink
1134 sp<NBAIO_Sink> mNormalSink;
Eric Laurent81784c32012-11-19 14:55:58 -08001135 uint32_t mScreenState; // cached copy of gScreenState
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07001136 // TODO: add comment and adjust size as needed
Glenn Kasteneef598c2017-04-03 14:41:13 -07001137 static const size_t kFastMixerLogSize = 8 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -08001138 sp<NBLog::Writer> mFastMixerNBLogWriter;
Andy Hung2148bf02016-11-28 19:01:02 -08001139
Dean Wheatley30d28422018-11-06 10:27:40 +11001140 // Downstream patch latency, available if mDownstreamLatencyStatMs.getN() > 0.
1141 audio_utils::Statistics<double> mDownstreamLatencyStatMs{0.999};
Andy Hung2148bf02016-11-28 19:01:02 -08001142
Eric Laurent81784c32012-11-19 14:55:58 -08001143public:
1144 virtual bool hasFastMixer() const = 0;
Glenn Kasten0f11b512014-01-31 16:18:54 -08001145 virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08001146 { FastTrackUnderruns dummy; return dummy; }
1147
1148protected:
1149 // accessed by both binder threads and within threadLoop(), lock on mutex needed
1150 unsigned mFastTrackAvailMask; // bit i set if fast track [i] is available
Eric Laurentd1f69b02014-12-15 14:33:13 -08001151 bool mHwSupportsPause;
1152 bool mHwPaused;
1153 bool mFlushPending;
Eric Laurent7c29ec92017-09-20 17:54:22 -07001154 // volumes last sent to audio HAL with stream->setVolume()
1155 float mLeftVolFloat;
1156 float mRightVolFloat;
Eric Laurent81784c32012-11-19 14:55:58 -08001157};
1158
1159class MixerThread : public PlaybackThread {
1160public:
1161 MixerThread(const sp<AudioFlinger>& audioFlinger,
1162 AudioStreamOut* output,
1163 audio_io_handle_t id,
1164 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001165 bool systemReady,
Eric Laurent81784c32012-11-19 14:55:58 -08001166 type_t type = MIXER);
1167 virtual ~MixerThread();
1168
1169 // Thread virtuals
1170
Eric Laurent10351942014-05-08 18:49:52 -07001171 virtual bool checkForNewParameter_l(const String8& keyValuePair,
1172 status_t& status);
Eric Laurent81784c32012-11-19 14:55:58 -08001173
Andy Hung1bc088a2018-02-09 15:57:31 -08001174 virtual bool isTrackAllowed_l(
1175 audio_channel_mask_t channelMask, audio_format_t format,
1176 audio_session_t sessionId, uid_t uid) const override;
Eric Laurent81784c32012-11-19 14:55:58 -08001177protected:
1178 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08001179 virtual uint32_t idleSleepTimeUs() const;
1180 virtual uint32_t suspendSleepTimeUs() const;
1181 virtual void cacheParameters_l();
1182
Andy Hungdae27702016-10-31 14:01:16 -07001183 virtual void acquireWakeLock_l() {
1184 PlaybackThread::acquireWakeLock_l();
Andy Hung818e7a32016-02-16 18:08:07 -08001185 if (hasFastMixer()) {
1186 mFastMixer->setBoottimeOffset(
1187 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME]);
1188 }
1189 }
1190
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001191 void dumpInternals_l(int fd, const Vector<String16>& args) override;
1192
Eric Laurent81784c32012-11-19 14:55:58 -08001193 // threadLoop snippets
Eric Laurentbfb1b832013-01-07 09:53:42 -08001194 virtual ssize_t threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08001195 virtual void threadLoop_standby();
1196 virtual void threadLoop_mix();
1197 virtual void threadLoop_sleepTime();
Eric Laurent81784c32012-11-19 14:55:58 -08001198 virtual uint32_t correctLatency_l(uint32_t latency) const;
1199
Eric Laurent054d9d32015-04-24 08:48:48 -07001200 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
1201 audio_patch_handle_t *handle);
1202 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle);
1203
Eric Laurent81784c32012-11-19 14:55:58 -08001204 AudioMixer* mAudioMixer; // normal mixer
1205private:
1206 // one-time initialization, no locks required
Glenn Kasten4d23ca32014-05-13 10:39:51 -07001207 sp<FastMixer> mFastMixer; // non-0 if there is also a fast mixer
Eric Laurent81784c32012-11-19 14:55:58 -08001208 sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread
1209
1210 // contents are not guaranteed to be consistent, no locks required
1211 FastMixerDumpState mFastMixerDumpState;
1212#ifdef STATE_QUEUE_DUMP
1213 StateQueueObserverDump mStateQueueObserverDump;
1214 StateQueueMutatorDump mStateQueueMutatorDump;
1215#endif
1216 AudioWatchdogDump mAudioWatchdogDump;
1217
1218 // accessible only within the threadLoop(), no locks required
1219 // mFastMixer->sq() // for mutating and pushing state
1220 int32_t mFastMixerFutex; // for cold idle
1221
Andy Hung2ddee192015-12-18 17:34:44 -08001222 std::atomic_bool mMasterMono;
Eric Laurent81784c32012-11-19 14:55:58 -08001223public:
Glenn Kasten4d23ca32014-05-13 10:39:51 -07001224 virtual bool hasFastMixer() const { return mFastMixer != 0; }
Eric Laurent81784c32012-11-19 14:55:58 -08001225 virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const {
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001226 ALOG_ASSERT(fastIndex < FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08001227 return mFastMixerDumpState.mTracks[fastIndex].mUnderruns;
1228 }
Eric Laurent83b88082014-06-20 18:31:16 -07001229
Andy Hung1c86ebe2018-05-29 20:29:08 -07001230 status_t threadloop_getHalTimestamp_l(
1231 ExtendedTimestamp *timestamp) const override {
1232 if (mNormalSink.get() != nullptr) {
1233 return mNormalSink->getTimestamp(*timestamp);
1234 }
1235 return INVALID_OPERATION;
1236 }
1237
Andy Hung2ddee192015-12-18 17:34:44 -08001238protected:
1239 virtual void setMasterMono_l(bool mono) {
1240 mMasterMono.store(mono);
1241 if (mFastMixer != nullptr) { /* hasFastMixer() */
1242 mFastMixer->setMasterMono(mMasterMono);
1243 }
1244 }
1245 // the FastMixer performs mono blend if it exists.
Glenn Kasten03c48d52016-01-27 17:25:17 -08001246 // Blending with limiter is not idempotent,
1247 // and blending without limiter is idempotent but inefficient to do twice.
Andy Hung2ddee192015-12-18 17:34:44 -08001248 virtual bool requireMonoBlend() { return mMasterMono.load() && !hasFastMixer(); }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001249
1250 void setMasterBalance(float balance) override {
1251 mMasterBalance.store(balance);
1252 if (hasFastMixer()) {
1253 mFastMixer->setMasterBalance(balance);
1254 }
1255 }
Eric Laurent81784c32012-11-19 14:55:58 -08001256};
1257
1258class DirectOutputThread : public PlaybackThread {
1259public:
1260
1261 DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Andy Hung48f59ed2019-01-28 15:06:59 -08001262 audio_io_handle_t id, audio_devices_t device, bool systemReady)
1263 : DirectOutputThread(audioFlinger, output, id, device, DIRECT, systemReady) { }
1264
Eric Laurent81784c32012-11-19 14:55:58 -08001265 virtual ~DirectOutputThread();
1266
Mikhail Naganovac917ac2018-11-28 14:03:52 -08001267 status_t selectPresentation(int presentationId, int programId);
1268
Eric Laurent81784c32012-11-19 14:55:58 -08001269 // Thread virtuals
1270
Eric Laurent10351942014-05-08 18:49:52 -07001271 virtual bool checkForNewParameter_l(const String8& keyValuePair,
1272 status_t& status);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001273
Eric Laurente659ef42014-09-29 13:06:46 -07001274 virtual void flushHw_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001275
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001276 void setMasterBalance(float balance) override;
1277
Eric Laurent81784c32012-11-19 14:55:58 -08001278protected:
Eric Laurent81784c32012-11-19 14:55:58 -08001279 virtual uint32_t activeSleepTimeUs() const;
1280 virtual uint32_t idleSleepTimeUs() const;
1281 virtual uint32_t suspendSleepTimeUs() const;
1282 virtual void cacheParameters_l();
1283
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001284 void dumpInternals_l(int fd, const Vector<String16>& args) override;
1285
Eric Laurent81784c32012-11-19 14:55:58 -08001286 // threadLoop snippets
1287 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
1288 virtual void threadLoop_mix();
1289 virtual void threadLoop_sleepTime();
Eric Laurentd1f69b02014-12-15 14:33:13 -08001290 virtual void threadLoop_exit();
1291 virtual bool shouldStandby_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001292
Phil Burk43b4dcc2015-06-09 16:53:44 -07001293 virtual void onAddNewTrack_l();
1294
Andy Hung48f59ed2019-01-28 15:06:59 -08001295 bool mVolumeShaperActive = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001296
Eric Laurentbfb1b832013-01-07 09:53:42 -08001297 DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Andy Hung48f59ed2019-01-28 15:06:59 -08001298 audio_io_handle_t id, audio_devices_t device, ThreadBase::type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001299 bool systemReady);
Eric Laurent5850c4c2016-11-10 13:04:31 -08001300 void processVolume_l(Track *track, bool lastTrack);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001301
Eric Laurent81784c32012-11-19 14:55:58 -08001302 // prepareTracks_l() tells threadLoop_mix() the name of the single active track
1303 sp<Track> mActiveTrack;
Phil Burk43b4dcc2015-06-09 16:53:44 -07001304
1305 wp<Track> mPreviousTrack; // used to detect track switch
1306
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001307 // This must be initialized for initial condition of mMasterBalance = 0 (disabled).
1308 float mMasterBalanceLeft = 1.f;
1309 float mMasterBalanceRight = 1.f;
1310
Eric Laurent81784c32012-11-19 14:55:58 -08001311public:
1312 virtual bool hasFastMixer() const { return false; }
Andy Hung10cbff12017-02-21 17:30:14 -08001313
1314 virtual int64_t computeWaitTimeNs_l() const override;
Andy Hungf3234512018-07-03 14:51:47 -07001315
1316 status_t threadloop_getHalTimestamp_l(ExtendedTimestamp *timestamp) const override {
1317 // For DIRECT and OFFLOAD threads, query the output sink directly.
1318 if (mOutput != nullptr) {
1319 uint64_t uposition64;
1320 struct timespec time;
1321 if (mOutput->getPresentationPosition(
1322 &uposition64, &time) == OK) {
1323 timestamp->mPosition[ExtendedTimestamp::LOCATION_KERNEL]
1324 = (int64_t)uposition64;
1325 timestamp->mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
1326 = audio_utils_ns_from_timespec(&time);
1327 return NO_ERROR;
1328 }
1329 }
1330 return INVALID_OPERATION;
1331 }
Eric Laurent81784c32012-11-19 14:55:58 -08001332};
1333
Eric Laurentbfb1b832013-01-07 09:53:42 -08001334class OffloadThread : public DirectOutputThread {
1335public:
1336
1337 OffloadThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurente93cc032016-05-05 10:15:10 -07001338 audio_io_handle_t id, uint32_t device, bool systemReady);
Eric Laurent6a51d7e2013-10-17 18:59:26 -07001339 virtual ~OffloadThread() {};
Eric Laurente659ef42014-09-29 13:06:46 -07001340 virtual void flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001341
1342protected:
1343 // threadLoop snippets
1344 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
1345 virtual void threadLoop_exit();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001346
1347 virtual bool waitingAsyncCallback();
1348 virtual bool waitingAsyncCallback_l();
Haynes Mathew George05317d22016-05-03 16:34:26 -07001349 virtual void invalidateTracks(audio_stream_type_t streamType);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001350
Eric Laurentde0613d2016-07-22 18:19:11 -07001351 virtual bool keepWakeLock() const { return (mKeepWakeLock || (mDrainSequence & 1)); }
Eric Laurent64667972016-03-30 18:19:46 -07001352
Eric Laurentbfb1b832013-01-07 09:53:42 -08001353private:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001354 size_t mPausedWriteLength; // length in bytes of write interrupted by pause
1355 size_t mPausedBytesRemaining; // bytes still waiting in mixbuffer after resume
Eric Laurent64667972016-03-30 18:19:46 -07001356 bool mKeepWakeLock; // keep wake lock while waiting for write callback
Andy Hungf8044752016-07-27 14:58:11 -07001357 uint64_t mOffloadUnderrunPosition; // Current frame position for offloaded playback
1358 // used and valid only during underrun. ~0 if
1359 // no underrun has occurred during playback and
1360 // is not reset on standby.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001361};
1362
1363class AsyncCallbackThread : public Thread {
1364public:
1365
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001366 explicit AsyncCallbackThread(const wp<PlaybackThread>& playbackThread);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001367
1368 virtual ~AsyncCallbackThread();
1369
1370 // Thread virtuals
1371 virtual bool threadLoop();
1372
1373 // RefBase
1374 virtual void onFirstRef();
1375
1376 void exit();
Eric Laurent3b4529e2013-09-05 18:09:19 -07001377 void setWriteBlocked(uint32_t sequence);
1378 void resetWriteBlocked();
1379 void setDraining(uint32_t sequence);
1380 void resetDraining();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07001381 void setAsyncError();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001382
1383private:
Eric Laurent4de95592013-09-26 15:28:21 -07001384 const wp<PlaybackThread> mPlaybackThread;
Eric Laurent3b4529e2013-09-05 18:09:19 -07001385 // mWriteAckSequence corresponds to the last write sequence passed by the offload thread via
1386 // setWriteBlocked(). The sequence is shifted one bit to the left and the lsb is used
1387 // to indicate that the callback has been received via resetWriteBlocked()
Eric Laurent4de95592013-09-26 15:28:21 -07001388 uint32_t mWriteAckSequence;
Eric Laurent3b4529e2013-09-05 18:09:19 -07001389 // mDrainSequence corresponds to the last drain sequence passed by the offload thread via
1390 // setDraining(). The sequence is shifted one bit to the left and the lsb is used
1391 // to indicate that the callback has been received via resetDraining()
Eric Laurent4de95592013-09-26 15:28:21 -07001392 uint32_t mDrainSequence;
1393 Condition mWaitWorkCV;
1394 Mutex mLock;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07001395 bool mAsyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001396};
1397
Eric Laurent81784c32012-11-19 14:55:58 -08001398class DuplicatingThread : public MixerThread {
1399public:
1400 DuplicatingThread(const sp<AudioFlinger>& audioFlinger, MixerThread* mainThread,
Eric Laurent72e3f392015-05-20 14:43:50 -07001401 audio_io_handle_t id, bool systemReady);
Eric Laurent81784c32012-11-19 14:55:58 -08001402 virtual ~DuplicatingThread();
1403
1404 // Thread virtuals
1405 void addOutputTrack(MixerThread* thread);
1406 void removeOutputTrack(MixerThread* thread);
1407 uint32_t waitTimeMs() const { return mWaitTimeMs; }
Kevin Rocard069c2712018-03-29 19:09:14 -07001408
Kevin Rocardc86a7f72018-04-03 09:00:09 -07001409 void sendMetadataToBackend_l(
1410 const StreamOutHalInterface::SourceMetadata& metadata) override;
Eric Laurent81784c32012-11-19 14:55:58 -08001411protected:
1412 virtual uint32_t activeSleepTimeUs() const;
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001413 void dumpInternals_l(int fd, const Vector<String16>& args) override;
Eric Laurent81784c32012-11-19 14:55:58 -08001414
1415private:
1416 bool outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks);
1417protected:
1418 // threadLoop snippets
1419 virtual void threadLoop_mix();
1420 virtual void threadLoop_sleepTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001421 virtual ssize_t threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08001422 virtual void threadLoop_standby();
1423 virtual void cacheParameters_l();
1424
1425private:
1426 // called from threadLoop, addOutputTrack, removeOutputTrack
1427 virtual void updateWaitTime_l();
1428protected:
1429 virtual void saveOutputTracks();
1430 virtual void clearOutputTracks();
1431private:
1432
1433 uint32_t mWaitTimeMs;
1434 SortedVector < sp<OutputTrack> > outputTracks;
1435 SortedVector < sp<OutputTrack> > mOutputTracks;
1436public:
1437 virtual bool hasFastMixer() const { return false; }
Andy Hung1c86ebe2018-05-29 20:29:08 -07001438 status_t threadloop_getHalTimestamp_l(
1439 ExtendedTimestamp *timestamp) const override {
1440 if (mOutputTracks.size() > 0) {
1441 // forward the first OutputTrack's kernel information for timestamp.
1442 const ExtendedTimestamp trackTimestamp =
1443 mOutputTracks[0]->getClientProxyTimestamp();
1444 if (trackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] > 0) {
1445 timestamp->mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
1446 trackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
1447 timestamp->mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
1448 trackTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
1449 return OK; // discard server timestamp - that's ignored.
1450 }
1451 }
1452 return INVALID_OPERATION;
1453 }
Eric Laurent81784c32012-11-19 14:55:58 -08001454};
1455
Eric Laurent81784c32012-11-19 14:55:58 -08001456// record thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001457class RecordThread : public ThreadBase
Eric Laurent81784c32012-11-19 14:55:58 -08001458{
1459public:
1460
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001461 class RecordTrack;
Andy Hung73c02e42015-03-29 01:13:58 -07001462
1463 /* The ResamplerBufferProvider is used to retrieve recorded input data from the
1464 * RecordThread. It maintains local state on the relative position of the read
1465 * position of the RecordTrack compared with the RecordThread.
1466 */
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001467 class ResamplerBufferProvider : public AudioBufferProvider
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001468 {
1469 public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001470 explicit ResamplerBufferProvider(RecordTrack* recordTrack) :
Andy Hung73c02e42015-03-29 01:13:58 -07001471 mRecordTrack(recordTrack),
1472 mRsmpInUnrel(0), mRsmpInFront(0) { }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001473 virtual ~ResamplerBufferProvider() { }
Andy Hung73c02e42015-03-29 01:13:58 -07001474
1475 // called to set the ResamplerBufferProvider to head of the RecordThread data buffer,
1476 // skipping any previous data read from the hal.
1477 virtual void reset();
1478
1479 /* Synchronizes RecordTrack position with the RecordThread.
1480 * Calculates available frames and handle overruns if the RecordThread
1481 * has advanced faster than the ResamplerBufferProvider has retrieved data.
1482 * TODO: why not do this for every getNextBuffer?
1483 *
1484 * Parameters
1485 * framesAvailable: pointer to optional output size_t to store record track
1486 * frames available.
1487 * hasOverrun: pointer to optional boolean, returns true if track has overrun.
1488 */
1489
1490 virtual void sync(size_t *framesAvailable = NULL, bool *hasOverrun = NULL);
1491
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001492 // AudioBufferProvider interface
Glenn Kastend79072e2016-01-06 08:41:20 -08001493 virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001494 virtual void releaseBuffer(AudioBufferProvider::Buffer* buffer);
1495 private:
1496 RecordTrack * const mRecordTrack;
Andy Hung73c02e42015-03-29 01:13:58 -07001497 size_t mRsmpInUnrel; // unreleased frames remaining from
1498 // most recent getNextBuffer
1499 // for debug only
1500 int32_t mRsmpInFront; // next available frame
1501 // rolling counter that is never cleared
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001502 };
1503
Eric Laurent81784c32012-11-19 14:55:58 -08001504#include "RecordTracks.h"
1505
1506 RecordThread(const sp<AudioFlinger>& audioFlinger,
1507 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08001508 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08001509 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07001510 audio_devices_t inDevice,
1511 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08001512 );
Eric Laurent81784c32012-11-19 14:55:58 -08001513 virtual ~RecordThread();
1514
1515 // no addTrack_l ?
1516 void destroyTrack_l(const sp<RecordTrack>& track);
1517 void removeTrack_l(const sp<RecordTrack>& track);
1518
Eric Laurent81784c32012-11-19 14:55:58 -08001519 // Thread virtuals
1520 virtual bool threadLoop();
Eric Laurent555530a2017-02-07 18:17:24 -08001521 virtual void preExit();
Eric Laurent81784c32012-11-19 14:55:58 -08001522
1523 // RefBase
1524 virtual void onFirstRef();
1525
1526 virtual status_t initCheck() const { return (mInput == NULL) ? NO_INIT : NO_ERROR; }
Glenn Kastene198c362013-08-13 09:13:36 -07001527
Glenn Kastenb880f5e2014-05-07 08:43:45 -07001528 virtual sp<MemoryDealer> readOnlyHeap() const { return mReadOnlyHeap; }
1529
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001530 virtual sp<IMemory> pipeMemory() const { return mPipeMemory; }
1531
Eric Laurent81784c32012-11-19 14:55:58 -08001532 sp<AudioFlinger::RecordThread::RecordTrack> createRecordTrack_l(
1533 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001534 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001535 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001536 audio_format_t format,
1537 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001538 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08001539 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001540 size_t *pNotificationFrameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001541 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07001542 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001543 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001544 status_t *status /*non-NULL*/,
1545 audio_port_handle_t portId);
Eric Laurent81784c32012-11-19 14:55:58 -08001546
1547 status_t start(RecordTrack* recordTrack,
1548 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001549 audio_session_t triggerSession);
Eric Laurent81784c32012-11-19 14:55:58 -08001550
1551 // ask the thread to stop the specified track, and
1552 // return true if the caller should then do it's part of the stopping process
Glenn Kastena8356f62013-07-25 14:37:52 -07001553 bool stop(RecordTrack* recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08001554
Eric Laurent81784c32012-11-19 14:55:58 -08001555 AudioStreamIn* clearInput();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001556 virtual sp<StreamHalInterface> stream() const;
Eric Laurent81784c32012-11-19 14:55:58 -08001557
Eric Laurent81784c32012-11-19 14:55:58 -08001558
Eric Laurent10351942014-05-08 18:49:52 -07001559 virtual bool checkForNewParameter_l(const String8& keyValuePair,
1560 status_t& status);
1561 virtual void cacheParameters_l() {}
Eric Laurent81784c32012-11-19 14:55:58 -08001562 virtual String8 getParameters(const String8& keys);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001563 virtual void ioConfigChanged(audio_io_config_event event, pid_t pid = 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07001564 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
1565 audio_patch_handle_t *handle);
1566 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle);
Eric Laurent83b88082014-06-20 18:31:16 -07001567
Mikhail Naganov444ecc32018-05-01 17:40:05 -07001568 void addPatchTrack(const sp<PatchRecord>& record);
1569 void deletePatchTrack(const sp<PatchRecord>& record);
Eric Laurent83b88082014-06-20 18:31:16 -07001570
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001571 void readInputParameters_l();
Glenn Kasten5f972c02014-01-13 09:59:31 -08001572 virtual uint32_t getInputFramesLost();
Eric Laurent81784c32012-11-19 14:55:58 -08001573
1574 virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
1575 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
Andy Hungc3d62f92019-03-14 13:38:51 -07001576 uint32_t hasAudioSession_l(audio_session_t sessionId) const override {
1577 return ThreadBase::hasAudioSession_l(sessionId, mTracks);
1578 }
Eric Laurent81784c32012-11-19 14:55:58 -08001579
1580 // Return the set of unique session IDs across all tracks.
1581 // The keys are the session IDs, and the associated values are meaningless.
1582 // FIXME replace by Set [and implement Bag/Multiset for other uses].
Glenn Kastend848eb42016-03-08 13:42:11 -08001583 KeyedVector<audio_session_t, bool> sessionIds() const;
Eric Laurent81784c32012-11-19 14:55:58 -08001584
1585 virtual status_t setSyncEvent(const sp<SyncEvent>& event);
1586 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const;
1587
1588 static void syncStartEventCallback(const wp<SyncEvent>& event);
Eric Laurent81784c32012-11-19 14:55:58 -08001589
Glenn Kasten9b58f632013-07-16 11:37:48 -07001590 virtual size_t frameCount() const { return mFrameCount; }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001591 bool hasFastCapture() const { return mFastCapture != 0; }
Mikhail Naganovdc769682018-05-04 15:34:08 -07001592 virtual void toAudioPortConfig(struct audio_port_config *config);
Glenn Kasten9b58f632013-07-16 11:37:48 -07001593
Eric Laurent4c415062016-06-17 16:14:16 -07001594 virtual status_t checkEffectCompatibility_l(const effect_descriptor_t *desc,
1595 audio_session_t sessionId);
1596
Andy Hungdae27702016-10-31 14:01:16 -07001597 virtual void acquireWakeLock_l() {
1598 ThreadBase::acquireWakeLock_l();
1599 mActiveTracks.updatePowerState(this, true /* force */);
1600 }
Andy Hung293558a2017-03-21 12:19:20 -07001601 virtual bool isOutput() const override { return false; }
Andy Hungdae27702016-10-31 14:01:16 -07001602
Eric Laurentd8365c52017-07-16 15:27:05 -07001603 void checkBtNrec();
1604
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001605 // Sets the UID records silence
1606 void setRecordSilenced(uid_t uid, bool silenced);
1607
jiabin653cc0a2018-01-17 17:54:10 -08001608 status_t getActiveMicrophones(std::vector<media::MicrophoneInfo>* activeMicrophones);
1609
Paul McLean12340082019-03-19 09:35:05 -06001610 status_t setPreferredMicrophoneDirection(audio_microphone_direction_t direction);
1611 status_t setPreferredMicrophoneFieldDimension(float zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07001612
Kevin Rocard069c2712018-03-29 19:09:14 -07001613 void updateMetadata_l() override;
1614
jiabin01c8f562018-07-19 17:47:28 -07001615 bool fastTrackAvailable() const { return mFastTrackAvail; }
1616
Andy Hungc8fddf32018-08-08 18:32:37 -07001617 bool isTimestampCorrectionEnabled() const override {
1618 // checks popcount for exactly one device.
1619 return audio_is_input_device(
1620 mInDevice & mTimestampCorrectedDevices);
1621 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001622
1623protected:
1624 void dumpInternals_l(int fd, const Vector<String16>& args) override;
1625 void dumpTracks_l(int fd, const Vector<String16>& args) override;
1626
Eric Laurent81784c32012-11-19 14:55:58 -08001627private:
Eric Laurent81784c32012-11-19 14:55:58 -08001628 // Enter standby if not already in standby, and set mStandby flag
Glenn Kasten93e471f2013-08-19 08:40:07 -07001629 void standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08001630
1631 // Call the HAL standby method unconditionally, and don't change mStandby flag
Glenn Kastene198c362013-08-13 09:13:36 -07001632 void inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08001633
Eric Laurentd8365c52017-07-16 15:27:05 -07001634 void checkBtNrec_l();
1635
Eric Laurent81784c32012-11-19 14:55:58 -08001636 AudioStreamIn *mInput;
1637 SortedVector < sp<RecordTrack> > mTracks;
Glenn Kasten2b806402013-11-20 16:37:38 -08001638 // mActiveTracks has dual roles: it indicates the current active track(s), and
Eric Laurent81784c32012-11-19 14:55:58 -08001639 // is used together with mStartStopCond to indicate start()/stop() progress
Andy Hungdae27702016-10-31 14:01:16 -07001640 ActiveTracks<RecordTrack> mActiveTracks;
1641
Eric Laurent81784c32012-11-19 14:55:58 -08001642 Condition mStartStopCond;
Glenn Kasten9b58f632013-07-16 11:37:48 -07001643
Glenn Kasten85948432013-08-19 12:09:05 -07001644 // resampler converts input at HAL Hz to output at AudioRecord client Hz
Glenn Kasten1b291842016-07-18 14:55:21 -07001645 void *mRsmpInBuffer; // size = mRsmpInFramesOA
Glenn Kasten85948432013-08-19 12:09:05 -07001646 size_t mRsmpInFrames; // size of resampler input in frames
1647 size_t mRsmpInFramesP2;// size rounded up to a power-of-2
Glenn Kasten1b291842016-07-18 14:55:21 -07001648 size_t mRsmpInFramesOA;// mRsmpInFramesP2 + over-allocation
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001649
1650 // rolling index that is never cleared
Glenn Kasten85948432013-08-19 12:09:05 -07001651 int32_t mRsmpInRear; // last filled frame + 1
Glenn Kasten85948432013-08-19 12:09:05 -07001652
Eric Laurent81784c32012-11-19 14:55:58 -08001653 // For dumpsys
Glenn Kastenb880f5e2014-05-07 08:43:45 -07001654 const sp<MemoryDealer> mReadOnlyHeap;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001655
1656 // one-time initialization, no locks required
Glenn Kastenb187de12014-12-30 08:18:15 -08001657 sp<FastCapture> mFastCapture; // non-0 if there is also
1658 // a fast capture
Eric Laurent72e3f392015-05-20 14:43:50 -07001659
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001660 // FIXME audio watchdog thread
1661
1662 // contents are not guaranteed to be consistent, no locks required
1663 FastCaptureDumpState mFastCaptureDumpState;
1664#ifdef STATE_QUEUE_DUMP
1665 // FIXME StateQueue observer and mutator dump fields
1666#endif
1667 // FIXME audio watchdog dump
1668
1669 // accessible only within the threadLoop(), no locks required
1670 // mFastCapture->sq() // for mutating and pushing state
1671 int32_t mFastCaptureFutex; // for cold idle
1672
1673 // The HAL input source is treated as non-blocking,
1674 // but current implementation is blocking
1675 sp<NBAIO_Source> mInputSource;
1676 // The source for the normal capture thread to read from: mInputSource or mPipeSource
1677 sp<NBAIO_Source> mNormalSource;
1678 // If a fast capture is present, the non-blocking pipe sink written to by fast capture,
1679 // otherwise clear
1680 sp<NBAIO_Sink> mPipeSink;
1681 // If a fast capture is present, the non-blocking pipe source read by normal thread,
1682 // otherwise clear
1683 sp<NBAIO_Source> mPipeSource;
1684 // Depth of pipe from fast capture to normal thread and fast clients, always power of 2
1685 size_t mPipeFramesP2;
1686 // If a fast capture is present, the Pipe as IMemory, otherwise clear
1687 sp<IMemory> mPipeMemory;
1688
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07001689 // TODO: add comment and adjust size as needed
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001690 static const size_t kFastCaptureLogSize = 4 * 1024;
1691 sp<NBLog::Writer> mFastCaptureNBLogWriter;
1692
1693 bool mFastTrackAvail; // true if fast track available
Eric Laurentd8365c52017-07-16 15:27:05 -07001694 // common state to all record threads
1695 std::atomic_bool mBtNrecSuspended;
Andy Hung6427e442018-08-09 12:51:02 -07001696
1697 int64_t mFramesRead = 0; // continuous running counter.
Eric Laurent81784c32012-11-19 14:55:58 -08001698};
Eric Laurent6acd1d42017-01-04 14:23:29 -08001699
1700class MmapThread : public ThreadBase
1701{
1702 public:
1703
1704#include "MmapTracks.h"
1705
1706 MmapThread(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1707 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
1708 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady);
1709 virtual ~MmapThread();
1710
1711 virtual void configure(const audio_attributes_t *attr,
1712 audio_stream_type_t streamType,
1713 audio_session_t sessionId,
1714 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07001715 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08001716 audio_port_handle_t portId);
1717
1718 void disconnect();
1719
1720 // MmapStreamInterface
1721 status_t createMmapBuffer(int32_t minSizeFrames,
1722 struct audio_mmap_buffer_info *info);
1723 status_t getMmapPosition(struct audio_mmap_position *position);
Eric Laurenta54f1282017-07-01 19:39:32 -07001724 status_t start(const AudioClient& client, audio_port_handle_t *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001725 status_t stop(audio_port_handle_t handle);
Eric Laurent18b57012017-02-13 16:23:52 -08001726 status_t standby();
Eric Laurent6acd1d42017-01-04 14:23:29 -08001727
1728 // RefBase
1729 virtual void onFirstRef();
1730
1731 // Thread virtuals
1732 virtual bool threadLoop();
1733
1734 virtual void threadLoop_exit();
1735 virtual void threadLoop_standby();
Eric Laurent18b57012017-02-13 16:23:52 -08001736 virtual bool shouldStandby_l() { return false; }
Eric Laurent331679c2018-04-16 17:03:16 -07001737 virtual status_t exitStandby();
Eric Laurent6acd1d42017-01-04 14:23:29 -08001738
1739 virtual status_t initCheck() const { return (mHalStream == 0) ? NO_INIT : NO_ERROR; }
1740 virtual size_t frameCount() const { return mFrameCount; }
1741 virtual bool checkForNewParameter_l(const String8& keyValuePair,
1742 status_t& status);
1743 virtual String8 getParameters(const String8& keys);
1744 virtual void ioConfigChanged(audio_io_config_event event, pid_t pid = 0);
1745 void readHalParameters_l();
1746 virtual void cacheParameters_l() {}
1747 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
1748 audio_patch_handle_t *handle);
1749 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07001750 virtual void toAudioPortConfig(struct audio_port_config *config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001751
1752 virtual sp<StreamHalInterface> stream() const { return mHalStream; }
1753 virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
1754 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
1755 virtual status_t checkEffectCompatibility_l(const effect_descriptor_t *desc,
1756 audio_session_t sessionId);
1757
Andy Hungc3d62f92019-03-14 13:38:51 -07001758 uint32_t hasAudioSession_l(audio_session_t sessionId) const override {
1759 // Note: using mActiveTracks as no mTracks here.
1760 return ThreadBase::hasAudioSession_l(sessionId, mActiveTracks);
1761 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001762 virtual status_t setSyncEvent(const sp<SyncEvent>& event);
1763 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const;
1764
1765 virtual void checkSilentMode_l() {}
1766 virtual void processVolume_l() {}
1767 void checkInvalidTracks_l();
1768
1769 virtual audio_stream_type_t streamType() { return AUDIO_STREAM_DEFAULT; }
1770
1771 virtual void invalidateTracks(audio_stream_type_t streamType __unused) {}
1772
Eric Laurent331679c2018-04-16 17:03:16 -07001773 // Sets the UID records silence
1774 virtual void setRecordSilenced(uid_t uid __unused, bool silenced __unused) {}
1775
Eric Laurent6acd1d42017-01-04 14:23:29 -08001776 protected:
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001777 void dumpInternals_l(int fd, const Vector<String16>& args) override;
1778 void dumpTracks_l(int fd, const Vector<String16>& args) override;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001779
1780 audio_attributes_t mAttr;
1781 audio_session_t mSessionId;
1782 audio_port_handle_t mPortId;
1783
Phil Burk7f6b40d2017-02-09 13:18:38 -08001784 wp<MmapStreamCallback> mCallback;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001785 sp<StreamHalInterface> mHalStream;
1786 sp<DeviceHalInterface> mHalDevice;
1787 AudioHwDevice* const mAudioHwDev;
1788 ActiveTracks<MmapTrack> mActiveTracks;
Eric Laurent67f97292018-04-20 18:05:41 -07001789 float mHalVolFloat;
Eric Laurent331679c2018-04-16 17:03:16 -07001790
1791 int32_t mNoCallbackWarningCount;
1792 static constexpr int32_t kMaxNoCallbackWarnings = 5;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001793};
1794
1795class MmapPlaybackThread : public MmapThread, public VolumeInterface
1796{
1797
1798public:
1799 MmapPlaybackThread(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1800 AudioHwDevice *hwDev, AudioStreamOut *output,
1801 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady);
1802 virtual ~MmapPlaybackThread() {}
1803
1804 virtual void configure(const audio_attributes_t *attr,
1805 audio_stream_type_t streamType,
1806 audio_session_t sessionId,
1807 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07001808 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08001809 audio_port_handle_t portId);
1810
1811 AudioStreamOut* clearOutput();
1812
1813 // VolumeInterface
1814 virtual void setMasterVolume(float value);
1815 virtual void setMasterMute(bool muted);
1816 virtual void setStreamVolume(audio_stream_type_t stream, float value);
1817 virtual void setStreamMute(audio_stream_type_t stream, bool muted);
1818 virtual float streamVolume(audio_stream_type_t stream) const;
1819
1820 void setMasterMute_l(bool muted) { mMasterMute = muted; }
1821
1822 virtual void invalidateTracks(audio_stream_type_t streamType);
1823
1824 virtual audio_stream_type_t streamType() { return mStreamType; }
1825 virtual void checkSilentMode_l();
Eric Laurent331679c2018-04-16 17:03:16 -07001826 void processVolume_l() override;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001827
Andy Hung293558a2017-03-21 12:19:20 -07001828 virtual bool isOutput() const override { return true; }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001829
Kevin Rocard069c2712018-03-29 19:09:14 -07001830 void updateMetadata_l() override;
1831
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07001832 virtual void toAudioPortConfig(struct audio_port_config *config);
1833
Eric Laurent6acd1d42017-01-04 14:23:29 -08001834protected:
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001835 void dumpInternals_l(int fd, const Vector<String16>& args) override;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001836
1837 audio_stream_type_t mStreamType;
1838 float mMasterVolume;
1839 float mStreamVolume;
1840 bool mMasterMute;
1841 bool mStreamMute;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001842 AudioStreamOut* mOutput;
1843};
1844
1845class MmapCaptureThread : public MmapThread
1846{
1847
1848public:
1849 MmapCaptureThread(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1850 AudioHwDevice *hwDev, AudioStreamIn *input,
1851 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady);
1852 virtual ~MmapCaptureThread() {}
1853
1854 AudioStreamIn* clearInput();
1855
Eric Laurent331679c2018-04-16 17:03:16 -07001856 status_t exitStandby() override;
Andy Hung293558a2017-03-21 12:19:20 -07001857 virtual bool isOutput() const override { return false; }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001858
Kevin Rocard069c2712018-03-29 19:09:14 -07001859 void updateMetadata_l() override;
Eric Laurent331679c2018-04-16 17:03:16 -07001860 void processVolume_l() override;
1861 void setRecordSilenced(uid_t uid, bool silenced) override;
Kevin Rocard069c2712018-03-29 19:09:14 -07001862
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07001863 virtual void toAudioPortConfig(struct audio_port_config *config);
1864
Eric Laurent6acd1d42017-01-04 14:23:29 -08001865protected:
1866
1867 AudioStreamIn* mInput;
1868};