blob: 37b2d08ca3568516eda893164b090eb85bf80318 [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 Laurent6c796322019-04-09 14:13:17 -0700318 std::vector<int> getEffectIds_l(audio_session_t sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800319 // add an effect chain to the chain list (mEffectChains)
320 virtual status_t addEffectChain_l(const sp<EffectChain>& chain) = 0;
321 // remove an effect chain from the chain list (mEffectChains)
322 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain) = 0;
323 // lock all effect chains Mutexes. Must be called before releasing the
324 // ThreadBase mutex before processing the mixer and effects. This guarantees the
325 // integrity of the chains during the process.
326 // Also sets the parameter 'effectChains' to current value of mEffectChains.
327 void lockEffectChains_l(Vector< sp<EffectChain> >& effectChains);
328 // unlock effect chains after process
329 void unlockEffectChains(const Vector< sp<EffectChain> >& effectChains);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800330 // get a copy of mEffectChains vector
331 Vector< sp<EffectChain> > getEffectChains_l() const { return mEffectChains; };
Eric Laurent81784c32012-11-19 14:55:58 -0800332 // set audio mode to all effect chains
333 void setMode(audio_mode_t mode);
334 // get effect module with corresponding ID on specified audio session
Glenn Kastend848eb42016-03-08 13:42:11 -0800335 sp<AudioFlinger::EffectModule> getEffect(audio_session_t sessionId, int effectId);
336 sp<AudioFlinger::EffectModule> getEffect_l(audio_session_t sessionId, int effectId);
Eric Laurent81784c32012-11-19 14:55:58 -0800337 // add and effect module. Also creates the effect chain is none exists for
Eric Laurent6c796322019-04-09 14:13:17 -0700338 // the effects audio session. Only called in a context of moving an effect
339 // from one thread to another
Eric Laurent81784c32012-11-19 14:55:58 -0800340 status_t addEffect_l(const sp< EffectModule>& effect);
341 // remove and effect module. Also removes the effect chain is this was the last
342 // effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -0800343 void removeEffect_l(const sp< EffectModule>& effect, bool release = false);
344 // disconnect an effect handle from module and destroy module if last handle
345 void disconnectEffectHandle(EffectHandle *handle, bool unpinIfLast);
Eric Laurent81784c32012-11-19 14:55:58 -0800346 // detach all tracks connected to an auxiliary effect
Glenn Kasten0f11b512014-01-31 16:18:54 -0800347 virtual void detachAuxEffect_l(int effectId __unused) {}
Eric Laurent4c415062016-06-17 16:14:16 -0700348 // returns a combination of:
349 // - EFFECT_SESSION if effects on this audio session exist in one chain
350 // - TRACK_SESSION if tracks on this audio session exist
351 // - FAST_SESSION if fast tracks on this audio session exist
352 virtual uint32_t hasAudioSession_l(audio_session_t sessionId) const = 0;
353 uint32_t hasAudioSession(audio_session_t sessionId) const {
354 Mutex::Autolock _l(mLock);
355 return hasAudioSession_l(sessionId);
356 }
357
Andy Hungc3d62f92019-03-14 13:38:51 -0700358 template <typename T>
359 uint32_t hasAudioSession_l(audio_session_t sessionId, const T& tracks) const {
360 uint32_t result = 0;
361 if (getEffectChain_l(sessionId) != 0) {
362 result = EFFECT_SESSION;
363 }
364 for (size_t i = 0; i < tracks.size(); ++i) {
365 const sp<TrackBase>& track = tracks[i];
366 if (sessionId == track->sessionId()
367 && !track->isInvalid() // not yet removed from tracks.
368 && !track->isTerminated()) {
369 result |= TRACK_SESSION;
370 if (track->isFastTrack()) {
371 result |= FAST_SESSION; // caution, only represents first track.
372 }
373 break;
374 }
375 }
376 return result;
377 }
378
Eric Laurent81784c32012-11-19 14:55:58 -0800379 // the value returned by default implementation is not important as the
380 // strategy is only meaningful for PlaybackThread which implements this method
Glenn Kastend848eb42016-03-08 13:42:11 -0800381 virtual uint32_t getStrategyForSession_l(audio_session_t sessionId __unused)
382 { return 0; }
Eric Laurent81784c32012-11-19 14:55:58 -0800383
Eric Laurent81784c32012-11-19 14:55:58 -0800384 // check if some effects must be suspended/restored when an effect is enabled
385 // or disabled
386 void checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
387 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -0800388 audio_session_t sessionId =
389 AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -0800390 void checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
391 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -0800392 audio_session_t sessionId =
393 AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -0800394
395 virtual status_t setSyncEvent(const sp<SyncEvent>& event) = 0;
396 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const = 0;
397
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700398 // Return a reference to a per-thread heap which can be used to allocate IMemory
399 // objects that will be read-only to client processes, read/write to mediaserver,
400 // and shared by all client processes of the thread.
401 // The heap is per-thread rather than common across all threads, because
402 // clients can't be trusted not to modify the offset of the IMemory they receive.
403 // If a thread does not have such a heap, this method returns 0.
404 virtual sp<MemoryDealer> readOnlyHeap() const { return 0; }
Eric Laurent81784c32012-11-19 14:55:58 -0800405
Glenn Kasten6181ffd2014-05-13 10:41:52 -0700406 virtual sp<IMemory> pipeMemory() const { return 0; }
407
Eric Laurent72e3f392015-05-20 14:43:50 -0700408 void systemReady();
409
Eric Laurent4c415062016-06-17 16:14:16 -0700410 // checkEffectCompatibility_l() must be called with ThreadBase::mLock held
411 virtual status_t checkEffectCompatibility_l(const effect_descriptor_t *desc,
412 audio_session_t sessionId) = 0;
413
Eric Laurent6acd1d42017-01-04 14:23:29 -0800414 void broadcast_l();
415
Andy Hungc8fddf32018-08-08 18:32:37 -0700416 virtual bool isTimestampCorrectionEnabled() const { return false; }
417
418 bool isMsdDevice() const { return mIsMsdDevice; }
419
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700420 void dump(int fd, const Vector<String16>& args);
Andy Hungdc099c22018-09-18 13:46:39 -0700421
Andy Hungd0979812019-02-21 15:51:44 -0800422 // deliver stats to mediametrics.
423 void sendStatistics(bool force);
424
Eric Laurent81784c32012-11-19 14:55:58 -0800425 mutable Mutex mLock;
426
427protected:
428
429 // entry describing an effect being suspended in mSuspendedSessions keyed vector
430 class SuspendedSessionDesc : public RefBase {
431 public:
432 SuspendedSessionDesc() : mRefCount(0) {}
433
434 int mRefCount; // number of active suspend requests
435 effect_uuid_t mType; // effect type UUID
436 };
437
Andy Hungdae27702016-10-31 14:01:16 -0700438 void acquireWakeLock();
439 virtual void acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800440 void releaseWakeLock();
441 void releaseWakeLock_l();
Andy Hungd01b0f12016-11-07 16:10:30 -0800442 void updateWakeLockUids_l(const SortedVector<uid_t> &uids);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800443 void getPowerManager_l();
Eric Laurentd8365c52017-07-16 15:27:05 -0700444 // suspend or restore effects of the specified type (or all if type is NULL)
445 // on a given session. The number of suspend requests is counted and restore
446 // occurs when all suspend requests are cancelled.
Eric Laurent81784c32012-11-19 14:55:58 -0800447 void setEffectSuspended_l(const effect_uuid_t *type,
448 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -0800449 audio_session_t sessionId);
Eric Laurentd8365c52017-07-16 15:27:05 -0700450 // updated mSuspendedSessions when an effect is suspended or restored
Eric Laurent81784c32012-11-19 14:55:58 -0800451 void updateSuspendedSessions_l(const effect_uuid_t *type,
452 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -0800453 audio_session_t sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800454 // check if some effects must be suspended when an effect chain is added
455 void checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain);
456
Kevin Rocard069c2712018-03-29 19:09:14 -0700457 // sends the metadata of the active tracks to the HAL
458 virtual void updateMetadata_l() = 0;
459
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100460 String16 getWakeLockTag();
461
Eric Laurent81784c32012-11-19 14:55:58 -0800462 virtual void preExit() { }
Andy Hung2ddee192015-12-18 17:34:44 -0800463 virtual void setMasterMono_l(bool mono __unused) { }
464 virtual bool requireMonoBlend() { return false; }
Eric Laurent81784c32012-11-19 14:55:58 -0800465
Andy Hung1c86ebe2018-05-29 20:29:08 -0700466 // called within the threadLoop to obtain timestamp from the HAL.
467 virtual status_t threadloop_getHalTimestamp_l(
468 ExtendedTimestamp *timestamp __unused) const {
469 return INVALID_OPERATION;
470 }
471
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700472 virtual void dumpInternals_l(int fd __unused, const Vector<String16>& args __unused)
473 { }
474 virtual void dumpTracks_l(int fd __unused, const Vector<String16>& args __unused) { }
475
476
Eric Laurent81784c32012-11-19 14:55:58 -0800477 friend class AudioFlinger; // for mEffectChains
478
479 const type_t mType;
480
481 // Used by parameters, config events, addTrack_l, exit
482 Condition mWaitWorkCV;
483
484 const sp<AudioFlinger> mAudioFlinger;
Glenn Kasten9b58f632013-07-16 11:37:48 -0700485
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800486 // updated by PlaybackThread::readOutputParameters_l() or
487 // RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800488 uint32_t mSampleRate;
489 size_t mFrameCount; // output HAL, direct output, record
Eric Laurent81784c32012-11-19 14:55:58 -0800490 audio_channel_mask_t mChannelMask;
Glenn Kastenf6ed4232013-07-16 11:16:27 -0700491 uint32_t mChannelCount;
Eric Laurent81784c32012-11-19 14:55:58 -0800492 size_t mFrameSize;
Glenn Kasten97b7b752014-09-28 13:04:24 -0700493 // not HAL frame size, this is for output sink (to pipe to fast mixer)
Andy Hung463be252014-07-10 16:56:07 -0700494 audio_format_t mFormat; // Source format for Recording and
495 // Sink format for Playback.
496 // Sink format may be different than
497 // HAL format if Fastmixer is used.
498 audio_format_t mHALFormat;
Glenn Kasten70949c42013-08-06 07:40:12 -0700499 size_t mBufferSize; // HAL buffer size for read() or write()
Eric Laurent81784c32012-11-19 14:55:58 -0800500
Eric Laurent10351942014-05-08 18:49:52 -0700501 Vector< sp<ConfigEvent> > mConfigEvents;
Eric Laurent72e3f392015-05-20 14:43:50 -0700502 Vector< sp<ConfigEvent> > mPendingConfigEvents; // events awaiting system ready
Eric Laurent81784c32012-11-19 14:55:58 -0800503
504 // These fields are written and read by thread itself without lock or barrier,
Glenn Kasten4944acb2013-08-19 08:39:20 -0700505 // and read by other threads without lock or barrier via standby(), outDevice()
Eric Laurent81784c32012-11-19 14:55:58 -0800506 // and inDevice().
507 // Because of the absence of a lock or barrier, any other thread that reads
508 // these fields must use the information in isolation, or be prepared to deal
509 // with possibility that it might be inconsistent with other information.
Glenn Kasten4944acb2013-08-19 08:39:20 -0700510 bool mStandby; // Whether thread is currently in standby.
Eric Laurent81784c32012-11-19 14:55:58 -0800511 audio_devices_t mOutDevice; // output device
512 audio_devices_t mInDevice; // input device
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700513 audio_devices_t mPrevOutDevice; // previous output device
Eric Laurente8726fe2015-06-26 09:39:24 -0700514 audio_devices_t mPrevInDevice; // previous input device
Eric Laurent296fb132015-05-01 11:38:42 -0700515 struct audio_patch mPatch;
François Gaffie0c280aa2018-07-25 10:02:15 +0200516 /**
517 * @brief mDeviceId current device port unique identifier
518 */
519 audio_port_handle_t mDeviceId = AUDIO_PORT_HANDLE_NONE;
Glenn Kastenf59497b2015-01-26 16:35:47 -0800520 audio_source_t mAudioSource;
Eric Laurent81784c32012-11-19 14:55:58 -0800521
522 const audio_io_handle_t mId;
523 Vector< sp<EffectChain> > mEffectChains;
524
Glenn Kastend7dca052015-03-05 16:05:54 -0800525 static const int kThreadNameLength = 16; // prctl(PR_SET_NAME) limit
526 char mThreadName[kThreadNameLength]; // guaranteed NUL-terminated
Eric Laurent81784c32012-11-19 14:55:58 -0800527 sp<IPowerManager> mPowerManager;
528 sp<IBinder> mWakeLockToken;
529 const sp<PMDeathRecipient> mDeathRecipient;
Glenn Kastend848eb42016-03-08 13:42:11 -0800530 // list of suspended effects per session and per type. The first (outer) vector is
531 // keyed by session ID, the second (inner) by type UUID timeLow field
Eric Laurentd8365c52017-07-16 15:27:05 -0700532 // Updated by updateSuspendedSessions_l() only.
Glenn Kastend848eb42016-03-08 13:42:11 -0800533 KeyedVector< audio_session_t, KeyedVector< int, sp<SuspendedSessionDesc> > >
Eric Laurent81784c32012-11-19 14:55:58 -0800534 mSuspendedSessions;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -0700535 // TODO: add comment and adjust size as needed
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800536 static const size_t kLogSize = 4 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -0800537 sp<NBLog::Writer> mNBLogWriter;
Eric Laurent72e3f392015-05-20 14:43:50 -0700538 bool mSystemReady;
Andy Hung818e7a32016-02-16 18:08:07 -0800539 ExtendedTimestamp mTimestamp;
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700540 TimestampVerifier< // For timestamp statistics.
541 int64_t /* frame count */, int64_t /* time ns */> mTimestampVerifier;
Andy Hungc8fddf32018-08-08 18:32:37 -0700542 audio_devices_t mTimestampCorrectedDevices = AUDIO_DEVICE_NONE;
Andy Hung446f4df2019-02-21 12:26:41 -0800543
544 // ThreadLoop statistics per iteration.
545 int64_t mLastIoBeginNs = -1;
546 int64_t mLastIoEndNs = -1;
547
548 // This should be read under ThreadBase lock (if not on the threadLoop thread).
549 audio_utils::Statistics<double> mIoJitterMs{0.995 /* alpha */};
550 audio_utils::Statistics<double> mProcessTimeMs{0.995 /* alpha */};
Andy Hunge6c37112019-02-26 17:38:10 -0800551 audio_utils::Statistics<double> mLatencyMs{0.995 /* alpha */};
Andy Hung446f4df2019-02-21 12:26:41 -0800552
Andy Hungd0979812019-02-21 15:51:44 -0800553 // Save the last count when we delivered statistics to mediametrics.
554 int64_t mLastRecordedTimestampVerifierN = 0;
555 int64_t mLastRecordedTimeNs = 0; // BOOTTIME to include suspend.
556
Andy Hungc8fddf32018-08-08 18:32:37 -0700557 bool mIsMsdDevice = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800558 // A condition that must be evaluated by the thread loop has changed and
559 // we must not wait for async write callback in the thread loop before evaluating it
560 bool mSignalPending;
Andy Hungdae27702016-10-31 14:01:16 -0700561
Andy Hung8946a282018-04-19 20:04:56 -0700562#ifdef TEE_SINK
563 NBAIO_Tee mTee;
564#endif
Andy Hungdae27702016-10-31 14:01:16 -0700565 // ActiveTracks is a sorted vector of track type T representing the
566 // active tracks of threadLoop() to be considered by the locked prepare portion.
567 // ActiveTracks should be accessed with the ThreadBase lock held.
568 //
569 // During processing and I/O, the threadLoop does not hold the lock;
570 // hence it does not directly use ActiveTracks. Care should be taken
571 // to hold local strong references or defer removal of tracks
572 // if the threadLoop may still be accessing those tracks due to mix, etc.
573 //
574 // This class updates power information appropriately.
575 //
576
577 template <typename T>
578 class ActiveTracks {
579 public:
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700580 explicit ActiveTracks(SimpleLog *localLog = nullptr)
Andy Hungdae27702016-10-31 14:01:16 -0700581 : mActiveTracksGeneration(0)
582 , mLastActiveTracksGeneration(0)
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700583 , mLocalLog(localLog)
Andy Hungdae27702016-10-31 14:01:16 -0700584 { }
585
586 ~ActiveTracks() {
587 ALOGW_IF(!mActiveTracks.isEmpty(),
588 "ActiveTracks should be empty in destructor");
589 }
590 // returns the last track added (even though it may have been
591 // subsequently removed from ActiveTracks).
592 //
593 // Used for DirectOutputThread to ensure a flush is called when transitioning
594 // to a new track (even though it may be on the same session).
595 // Used for OffloadThread to ensure that volume and mixer state is
596 // taken from the latest track added.
597 //
598 // The latest track is saved with a weak pointer to prevent keeping an
599 // otherwise useless track alive. Thus the function will return nullptr
600 // if the latest track has subsequently been removed and destroyed.
601 sp<T> getLatest() {
602 return mLatestActiveTrack.promote();
603 }
604
605 // SortedVector methods
606 ssize_t add(const sp<T> &track);
607 ssize_t remove(const sp<T> &track);
608 size_t size() const {
609 return mActiveTracks.size();
610 }
Eric Tan39ec8d62018-07-24 09:49:29 -0700611 bool isEmpty() const {
612 return mActiveTracks.isEmpty();
613 }
Andy Hungdae27702016-10-31 14:01:16 -0700614 ssize_t indexOf(const sp<T>& item) {
615 return mActiveTracks.indexOf(item);
616 }
617 sp<T> operator[](size_t index) const {
618 return mActiveTracks[index];
619 }
620 typename SortedVector<sp<T>>::iterator begin() {
621 return mActiveTracks.begin();
622 }
623 typename SortedVector<sp<T>>::iterator end() {
624 return mActiveTracks.end();
625 }
626
627 // Due to Binder recursion optimization, clear() and updatePowerState()
628 // cannot be called from a Binder thread because they may call back into
629 // the original calling process (system server) for BatteryNotifier
630 // (which requires a Java environment that may not be present).
631 // Hence, call clear() and updatePowerState() only from the
632 // ThreadBase thread.
633 void clear();
634 // periodically called in the threadLoop() to update power state uids.
635 void updatePowerState(sp<ThreadBase> thread, bool force = false);
636
Kevin Rocardc86a7f72018-04-03 09:00:09 -0700637 /** @return true if one or move active tracks was added or removed since the
638 * last time this function was called or the vector was created. */
Kevin Rocard069c2712018-03-29 19:09:14 -0700639 bool readAndClearHasChanged();
640
Andy Hungdae27702016-10-31 14:01:16 -0700641 private:
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700642 void logTrack(const char *funcName, const sp<T> &track) const;
643
Andy Hungd01b0f12016-11-07 16:10:30 -0800644 SortedVector<uid_t> getWakeLockUids() {
645 SortedVector<uid_t> wakeLockUids;
Andy Hungdae27702016-10-31 14:01:16 -0700646 for (const sp<T> &track : mActiveTracks) {
647 wakeLockUids.add(track->uid());
648 }
649 return wakeLockUids; // moved by underlying SharedBuffer
650 }
651
652 std::map<uid_t, std::pair<ssize_t /* previous */, ssize_t /* current */>>
653 mBatteryCounter;
654 SortedVector<sp<T>> mActiveTracks;
655 int mActiveTracksGeneration;
656 int mLastActiveTracksGeneration;
657 wp<T> mLatestActiveTrack; // latest track added to ActiveTracks
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700658 SimpleLog * const mLocalLog;
Kevin Rocardc86a7f72018-04-03 09:00:09 -0700659 // If the vector has changed since last call to readAndClearHasChanged
Kevin Rocard069c2712018-03-29 19:09:14 -0700660 bool mHasChanged = false;
Andy Hungdae27702016-10-31 14:01:16 -0700661 };
Andy Hung293558a2017-03-21 12:19:20 -0700662
663 SimpleLog mLocalLog;
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700664
665private:
666 void dumpBase_l(int fd, const Vector<String16>& args);
667 void dumpEffectChains_l(int fd, const Vector<String16>& args);
Eric Laurent81784c32012-11-19 14:55:58 -0800668};
669
Eric Laurent6acd1d42017-01-04 14:23:29 -0800670class VolumeInterface {
671 public:
672
673 virtual ~VolumeInterface() {}
674
675 virtual void setMasterVolume(float value) = 0;
676 virtual void setMasterMute(bool muted) = 0;
677 virtual void setStreamVolume(audio_stream_type_t stream, float value) = 0;
678 virtual void setStreamMute(audio_stream_type_t stream, bool muted) = 0;
679 virtual float streamVolume(audio_stream_type_t stream) const = 0;
680
681};
682
Eric Laurent81784c32012-11-19 14:55:58 -0800683// --- PlaybackThread ---
Eric Laurent6acd1d42017-01-04 14:23:29 -0800684class PlaybackThread : public ThreadBase, public StreamOutHalInterfaceCallback,
685 public VolumeInterface {
Eric Laurent81784c32012-11-19 14:55:58 -0800686public:
687
688#include "PlaybackTracks.h"
689
690 enum mixer_state {
691 MIXER_IDLE, // no active tracks
692 MIXER_TRACKS_ENABLED, // at least one active track, but no track has any data ready
Eric Laurentbfb1b832013-01-07 09:53:42 -0800693 MIXER_TRACKS_READY, // at least one active track, and at least one track has data
694 MIXER_DRAIN_TRACK, // drain currently playing track
695 MIXER_DRAIN_ALL, // fully drain the hardware
Eric Laurent81784c32012-11-19 14:55:58 -0800696 // standby mode does not have an enum value
697 // suspend by audio policy manager is orthogonal to mixer state
698 };
699
Eric Laurente93cc032016-05-05 10:15:10 -0700700 // retry count before removing active track in case of underrun on offloaded thread:
701 // we need to make sure that AudioTrack client has enough time to send large buffers
702 //FIXME may be more appropriate if expressed in time units. Need to revise how underrun is
703 // handled for offloaded tracks
704 static const int8_t kMaxTrackRetriesOffload = 20;
705 static const int8_t kMaxTrackStartupRetriesOffload = 100;
706 static const int8_t kMaxTrackStopRetriesOffload = 2;
Andy Hung8ed196a2018-01-05 13:21:11 -0800707 static constexpr uint32_t kMaxTracksPerUid = 40;
Andy Hung1bc088a2018-02-09 15:57:31 -0800708 static constexpr size_t kMaxTracks = 256;
Eric Laurente93cc032016-05-05 10:15:10 -0700709
rago1bb90822017-05-02 18:31:48 -0700710 // Maximum delay (in nanoseconds) for upcoming buffers in suspend mode, otherwise
711 // if delay is greater, the estimated time for timeLoopNextNs is reset.
712 // This allows for catch-up to be done for small delays, while resetting the estimate
713 // for initial conditions or large delays.
714 static const nsecs_t kMaxNextBufferDelayNs = 100000000;
715
Eric Laurent81784c32012-11-19 14:55:58 -0800716 PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurente93cc032016-05-05 10:15:10 -0700717 audio_io_handle_t id, audio_devices_t device, type_t type, bool systemReady);
Eric Laurent81784c32012-11-19 14:55:58 -0800718 virtual ~PlaybackThread();
719
Eric Laurent81784c32012-11-19 14:55:58 -0800720 // Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -0800721 virtual bool threadLoop();
722
723 // RefBase
724 virtual void onFirstRef();
725
Eric Laurent4c415062016-06-17 16:14:16 -0700726 virtual status_t checkEffectCompatibility_l(const effect_descriptor_t *desc,
727 audio_session_t sessionId);
728
Eric Laurent81784c32012-11-19 14:55:58 -0800729protected:
730 // Code snippets that were lifted up out of threadLoop()
731 virtual void threadLoop_mix() = 0;
732 virtual void threadLoop_sleepTime() = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800733 virtual ssize_t threadLoop_write();
734 virtual void threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -0800735 virtual void threadLoop_standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800736 virtual void threadLoop_exit();
Eric Laurent81784c32012-11-19 14:55:58 -0800737 virtual void threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
738
739 // prepareTracks_l reads and writes mActiveTracks, and returns
740 // the pending set of tracks to remove via Vector 'tracksToRemove'. The caller
741 // is responsible for clearing or destroying this Vector later on, when it
742 // is safe to do so. That will drop the final ref count and destroy the tracks.
743 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove) = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800744 void removeTracks_l(const Vector< sp<Track> >& tracksToRemove);
745
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700746 // StreamOutHalInterfaceCallback implementation
747 virtual void onWriteReady();
748 virtual void onDrainReady();
749 virtual void onError();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800750
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700751 void resetWriteBlocked(uint32_t sequence);
752 void resetDraining(uint32_t sequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800753
754 virtual bool waitingAsyncCallback();
755 virtual bool waitingAsyncCallback_l();
756 virtual bool shouldStandby_l();
Haynes Mathew George4c6a4332014-01-15 12:31:39 -0800757 virtual void onAddNewTrack_l();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -0700758 void onAsyncError(); // error reported by AsyncCallbackThread
Eric Laurent81784c32012-11-19 14:55:58 -0800759
760 // ThreadBase virtuals
761 virtual void preExit();
762
Eric Laurent64667972016-03-30 18:19:46 -0700763 virtual bool keepWakeLock() const { return true; }
Andy Hungdae27702016-10-31 14:01:16 -0700764 virtual void acquireWakeLock_l() {
765 ThreadBase::acquireWakeLock_l();
766 mActiveTracks.updatePowerState(this, true /* force */);
767 }
Eric Laurent64667972016-03-30 18:19:46 -0700768
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700769 void dumpInternals_l(int fd, const Vector<String16>& args) override;
770 void dumpTracks_l(int fd, const Vector<String16>& args) override;
771
Eric Laurent81784c32012-11-19 14:55:58 -0800772public:
773
774 virtual status_t initCheck() const { return (mOutput == NULL) ? NO_INIT : NO_ERROR; }
775
776 // return estimated latency in milliseconds, as reported by HAL
777 uint32_t latency() const;
778 // same, but lock must already be held
779 uint32_t latency_l() const;
780
Eric Laurent6acd1d42017-01-04 14:23:29 -0800781 // VolumeInterface
782 virtual void setMasterVolume(float value);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +0100783 virtual void setMasterBalance(float balance);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800784 virtual void setMasterMute(bool muted);
785 virtual void setStreamVolume(audio_stream_type_t stream, float value);
786 virtual void setStreamMute(audio_stream_type_t stream, bool muted);
787 virtual float streamVolume(audio_stream_type_t stream) const;
Eric Laurent81784c32012-11-19 14:55:58 -0800788
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +0900789 void setVolumeForOutput_l(float left, float right) const;
790
Eric Laurent81784c32012-11-19 14:55:58 -0800791 sp<Track> createTrack_l(
792 const sp<AudioFlinger::Client>& client,
793 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700794 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -0800795 uint32_t *sampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -0800796 audio_format_t format,
797 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -0800798 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -0800799 size_t *pNotificationFrameCount,
800 uint32_t notificationsPerBuffer,
801 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -0800802 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -0800803 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -0700804 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -0800805 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -0800806 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800807 status_t *status /*non-NULL*/,
808 audio_port_handle_t portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800809
810 AudioStreamOut* getOutput() const;
811 AudioStreamOut* clearOutput();
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700812 virtual sp<StreamHalInterface> stream() const;
Eric Laurent81784c32012-11-19 14:55:58 -0800813
814 // a very large number of suspend() will eventually wraparound, but unlikely
815 void suspend() { (void) android_atomic_inc(&mSuspended); }
816 void restore()
817 {
818 // if restore() is done without suspend(), get back into
819 // range so that the next suspend() will operate correctly
820 if (android_atomic_dec(&mSuspended) <= 0) {
821 android_atomic_release_store(0, &mSuspended);
822 }
823 }
824 bool isSuspended() const
825 { return android_atomic_acquire_load(&mSuspended) > 0; }
826
827 virtual String8 getParameters(const String8& keys);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700828 virtual void ioConfigChanged(audio_io_config_event event, pid_t pid = 0);
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000829 status_t getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames);
Andy Hung010a1a12014-03-13 13:57:33 -0700830 // Consider also removing and passing an explicit mMainBuffer initialization
831 // parameter to AF::PlaybackThread::Track::Track().
rago94a1ee82017-07-21 15:11:02 -0700832 effect_buffer_t *sinkBuffer() const {
833 return reinterpret_cast<effect_buffer_t *>(mSinkBuffer); };
Eric Laurent81784c32012-11-19 14:55:58 -0800834
835 virtual void detachAuxEffect_l(int effectId);
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700836 status_t attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track>& track,
Eric Laurent81784c32012-11-19 14:55:58 -0800837 int EffectId);
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700838 status_t attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track>& track,
Eric Laurent81784c32012-11-19 14:55:58 -0800839 int EffectId);
840
841 virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
842 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
Andy Hungc3d62f92019-03-14 13:38:51 -0700843 uint32_t hasAudioSession_l(audio_session_t sessionId) const override {
844 return ThreadBase::hasAudioSession_l(sessionId, mTracks);
845 }
Glenn Kastend848eb42016-03-08 13:42:11 -0800846 virtual uint32_t getStrategyForSession_l(audio_session_t sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800847
848
849 virtual status_t setSyncEvent(const sp<SyncEvent>& event);
850 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const;
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700851
852 // called with AudioFlinger lock held
Eric Laurent13084622016-05-17 10:51:49 -0700853 bool invalidateTracks_l(audio_stream_type_t streamType);
Haynes Mathew George05317d22016-05-03 16:34:26 -0700854 virtual void invalidateTracks(audio_stream_type_t streamType);
Eric Laurent81784c32012-11-19 14:55:58 -0800855
Glenn Kasten9b58f632013-07-16 11:37:48 -0700856 virtual size_t frameCount() const { return mNormalFrameCount; }
857
Eric Laurent83b88082014-06-20 18:31:16 -0700858 status_t getTimestamp_l(AudioTimestamp& timestamp);
859
860 void addPatchTrack(const sp<PatchTrack>& track);
861 void deletePatchTrack(const sp<PatchTrack>& track);
862
Mikhail Naganovdc769682018-05-04 15:34:08 -0700863 virtual void toAudioPortConfig(struct audio_port_config *config);
Eric Laurentaccc1472013-09-20 09:36:34 -0700864
Andy Hung10cbff12017-02-21 17:30:14 -0800865 // Return the asynchronous signal wait time.
866 virtual int64_t computeWaitTimeNs_l() const { return INT64_MAX; }
867
Andy Hung293558a2017-03-21 12:19:20 -0700868 virtual bool isOutput() const override { return true; }
869
Andy Hung1bc088a2018-02-09 15:57:31 -0800870 // returns true if the track is allowed to be added to the thread.
871 virtual bool isTrackAllowed_l(
872 audio_channel_mask_t channelMask __unused,
873 audio_format_t format __unused,
874 audio_session_t sessionId __unused,
875 uid_t uid) const {
876 return trackCountForUid_l(uid) < PlaybackThread::kMaxTracksPerUid
877 && mTracks.size() < PlaybackThread::kMaxTracks;
878 }
879
Andy Hungc8fddf32018-08-08 18:32:37 -0700880 bool isTimestampCorrectionEnabled() const override {
881 const audio_devices_t device =
882 mOutDevice & mTimestampCorrectedDevices;
883 return audio_is_output_devices(device) && popcount(device) > 0;
884 }
Eric Laurent81784c32012-11-19 14:55:58 -0800885protected:
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800886 // updated by readOutputParameters_l()
Glenn Kasten9b58f632013-07-16 11:37:48 -0700887 size_t mNormalFrameCount; // normal mixer and effects
888
Andy Hung08fb1742015-05-31 23:22:10 -0700889 bool mThreadThrottle; // throttle the thread processing
Andy Hung40eb1a12015-06-18 13:42:02 -0700890 uint32_t mThreadThrottleTimeMs; // throttle time for MIXER threads
891 uint32_t mThreadThrottleEndMs; // notify once per throttling
Andy Hung08fb1742015-05-31 23:22:10 -0700892 uint32_t mHalfBufferMs; // half the buffer size in milliseconds
893
Andy Hung010a1a12014-03-13 13:57:33 -0700894 void* mSinkBuffer; // frame size aligned sink buffer
Eric Laurent81784c32012-11-19 14:55:58 -0800895
Andy Hung98ef9782014-03-04 14:46:50 -0800896 // TODO:
897 // Rearrange the buffer info into a struct/class with
898 // clear, copy, construction, destruction methods.
899 //
900 // mSinkBuffer also has associated with it:
901 //
902 // mSinkBufferSize: Sink Buffer Size
903 // mFormat: Sink Buffer Format
904
Andy Hung69aed5f2014-02-25 17:24:40 -0800905 // Mixer Buffer (mMixerBuffer*)
906 //
907 // In the case of floating point or multichannel data, which is not in the
908 // sink format, it is required to accumulate in a higher precision or greater channel count
909 // buffer before downmixing or data conversion to the sink buffer.
910
911 // Set to "true" to enable the Mixer Buffer otherwise mixer output goes to sink buffer.
912 bool mMixerBufferEnabled;
913
914 // Storage, 32 byte aligned (may make this alignment a requirement later).
915 // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
916 void* mMixerBuffer;
917
918 // Size of mMixerBuffer in bytes: mNormalFrameCount * #channels * sampsize.
919 size_t mMixerBufferSize;
920
921 // The audio format of mMixerBuffer. Set to AUDIO_FORMAT_PCM_(FLOAT|16_BIT) only.
922 audio_format_t mMixerBufferFormat;
923
924 // An internal flag set to true by MixerThread::prepareTracks_l()
925 // when mMixerBuffer contains valid data after mixing.
926 bool mMixerBufferValid;
927
Andy Hung98ef9782014-03-04 14:46:50 -0800928 // Effects Buffer (mEffectsBuffer*)
929 //
930 // In the case of effects data, which is not in the sink format,
931 // it is required to accumulate in a different buffer before data conversion
932 // to the sink buffer.
933
934 // Set to "true" to enable the Effects Buffer otherwise effects output goes to sink buffer.
935 bool mEffectBufferEnabled;
936
937 // Storage, 32 byte aligned (may make this alignment a requirement later).
938 // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
939 void* mEffectBuffer;
940
941 // Size of mEffectsBuffer in bytes: mNormalFrameCount * #channels * sampsize.
942 size_t mEffectBufferSize;
943
944 // The audio format of mEffectsBuffer. Set to AUDIO_FORMAT_PCM_16_BIT only.
945 audio_format_t mEffectBufferFormat;
946
947 // An internal flag set to true by MixerThread::prepareTracks_l()
948 // when mEffectsBuffer contains valid data after mixing.
949 //
950 // When this is set, all mixer data is routed into the effects buffer
951 // for any processing (including output processing).
952 bool mEffectBufferValid;
953
Eric Laurent81784c32012-11-19 14:55:58 -0800954 // suspend count, > 0 means suspended. While suspended, the thread continues to pull from
955 // tracks and mix, but doesn't write to HAL. A2DP and SCO HAL implementations can't handle
956 // concurrent use of both of them, so Audio Policy Service suspends one of the threads to
957 // workaround that restriction.
958 // 'volatile' means accessed via atomic operations and no lock.
959 volatile int32_t mSuspended;
960
Andy Hung818e7a32016-02-16 18:08:07 -0800961 int64_t mBytesWritten;
Andy Hungc54b1ff2016-02-23 14:07:07 -0800962 int64_t mFramesWritten; // not reset on standby
Andy Hung238fa3d2016-07-28 10:53:22 -0700963 int64_t mSuspendedFrames; // not reset on standby
jiabin245cdd92018-12-07 17:55:15 -0800964
965 // mHapticChannelMask and mHapticChannelCount will only be valid when the thread support
966 // haptic playback.
967 audio_channel_mask_t mHapticChannelMask = AUDIO_CHANNEL_NONE;
968 uint32_t mHapticChannelCount = 0;
Eric Laurent81784c32012-11-19 14:55:58 -0800969private:
970 // mMasterMute is in both PlaybackThread and in AudioFlinger. When a
971 // PlaybackThread needs to find out if master-muted, it checks it's local
972 // copy rather than the one in AudioFlinger. This optimization saves a lock.
973 bool mMasterMute;
974 void setMasterMute_l(bool muted) { mMasterMute = muted; }
975protected:
Andy Hungdae27702016-10-31 14:01:16 -0700976 ActiveTracks<Track> mActiveTracks;
Eric Laurent81784c32012-11-19 14:55:58 -0800977
Eric Laurent81784c32012-11-19 14:55:58 -0800978 // Time to sleep between cycles when:
979 virtual uint32_t activeSleepTimeUs() const; // mixer state MIXER_TRACKS_ENABLED
980 virtual uint32_t idleSleepTimeUs() const = 0; // mixer state MIXER_IDLE
981 virtual uint32_t suspendSleepTimeUs() const = 0; // audio policy manager suspended us
982 // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write()
983 // No sleep in standby mode; waits on a condition
984
985 // Code snippets that are temporarily lifted up out of threadLoop() until the merge
986 void checkSilentMode_l();
987
988 // Non-trivial for DUPLICATING only
989 virtual void saveOutputTracks() { }
990 virtual void clearOutputTracks() { }
991
992 // Cache various calculated values, at threadLoop() entry and after a parameter change
993 virtual void cacheParameters_l();
994
995 virtual uint32_t correctLatency_l(uint32_t latency) const;
996
Eric Laurent1c333e22014-05-20 10:48:17 -0700997 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
998 audio_patch_handle_t *handle);
999 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle);
1000
Phil Burk6fc2a7c2015-04-30 16:08:10 -07001001 bool usesHwAvSync() const { return (mType == DIRECT) && (mOutput != NULL)
1002 && mHwSupportsPause
1003 && (mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC); }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08001004
Andy Hung1bc088a2018-02-09 15:57:31 -08001005 uint32_t trackCountForUid_l(uid_t uid) const;
Eric Laurentad7dd962016-09-22 12:38:37 -07001006
Eric Laurent81784c32012-11-19 14:55:58 -08001007private:
1008
1009 friend class AudioFlinger; // for numerous
1010
Mikhail Naganovbf493082017-04-17 17:37:12 -07001011 DISALLOW_COPY_AND_ASSIGN(PlaybackThread);
Eric Laurent81784c32012-11-19 14:55:58 -08001012
1013 status_t addTrack_l(const sp<Track>& track);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001014 bool destroyTrack_l(const sp<Track>& track);
Eric Laurent81784c32012-11-19 14:55:58 -08001015 void removeTrack_l(const sp<Track>& track);
1016
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001017 void readOutputParameters_l();
Kevin Rocardc86a7f72018-04-03 09:00:09 -07001018 void updateMetadata_l() final;
1019 virtual void sendMetadataToBackend_l(const StreamOutHalInterface::SourceMetadata& metadata);
Eric Laurent81784c32012-11-19 14:55:58 -08001020
Andy Hungc0691382018-09-12 18:01:57 -07001021 // The Tracks class manages tracks added and removed from the Thread.
Andy Hung1bc088a2018-02-09 15:57:31 -08001022 template <typename T>
1023 class Tracks {
1024 public:
Andy Hungc0691382018-09-12 18:01:57 -07001025 Tracks(bool saveDeletedTrackIds) :
1026 mSaveDeletedTrackIds(saveDeletedTrackIds) { }
Andy Hung1bc088a2018-02-09 15:57:31 -08001027
1028 // SortedVector methods
Andy Hungc0691382018-09-12 18:01:57 -07001029 ssize_t add(const sp<T> &track) {
1030 const ssize_t index = mTracks.add(track);
1031 LOG_ALWAYS_FATAL_IF(index < 0, "cannot add track");
1032 return index;
1033 }
Andy Hung1bc088a2018-02-09 15:57:31 -08001034 ssize_t remove(const sp<T> &track);
1035 size_t size() const {
1036 return mTracks.size();
1037 }
1038 bool isEmpty() const {
1039 return mTracks.isEmpty();
1040 }
1041 ssize_t indexOf(const sp<T> &item) {
1042 return mTracks.indexOf(item);
1043 }
1044 sp<T> operator[](size_t index) const {
1045 return mTracks[index];
1046 }
1047 typename SortedVector<sp<T>>::iterator begin() {
1048 return mTracks.begin();
1049 }
1050 typename SortedVector<sp<T>>::iterator end() {
1051 return mTracks.end();
1052 }
1053
Andy Hungc0691382018-09-12 18:01:57 -07001054 size_t processDeletedTrackIds(std::function<void(int)> f) {
1055 for (const int trackId : mDeletedTrackIds) {
1056 f(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08001057 }
Andy Hungc0691382018-09-12 18:01:57 -07001058 return mDeletedTrackIds.size();
Andy Hung1bc088a2018-02-09 15:57:31 -08001059 }
1060
Andy Hungc0691382018-09-12 18:01:57 -07001061 void clearDeletedTrackIds() { mDeletedTrackIds.clear(); }
Andy Hung1bc088a2018-02-09 15:57:31 -08001062
1063 private:
Andy Hungc0691382018-09-12 18:01:57 -07001064 // Tracks pending deletion for MIXER type threads
1065 const bool mSaveDeletedTrackIds; // true to enable tracking
1066 std::set<int> mDeletedTrackIds;
Andy Hung1bc088a2018-02-09 15:57:31 -08001067
1068 SortedVector<sp<T>> mTracks; // wrapped SortedVector.
1069 };
1070
1071 Tracks<Track> mTracks;
1072
Eric Laurent223fd5c2014-11-11 13:43:36 -08001073 stream_type_t mStreamTypes[AUDIO_STREAM_CNT];
Eric Laurent81784c32012-11-19 14:55:58 -08001074 AudioStreamOut *mOutput;
1075
1076 float mMasterVolume;
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001077 std::atomic<float> mMasterBalance{};
1078 audio_utils::Balance mBalance;
Eric Laurent81784c32012-11-19 14:55:58 -08001079 int mNumWrites;
1080 int mNumDelayedWrites;
1081 bool mInWrite;
1082
1083 // FIXME rename these former local variables of threadLoop to standard "m" names
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001084 nsecs_t mStandbyTimeNs;
Andy Hung25c2dac2014-02-27 14:56:00 -08001085 size_t mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08001086
1087 // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l()
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001088 uint32_t mActiveSleepTimeUs;
1089 uint32_t mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08001090
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001091 uint32_t mSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08001092
1093 // mixer status returned by prepareTracks_l()
1094 mixer_state mMixerStatus; // current cycle
1095 // previous cycle when in prepareTracks_l()
1096 mixer_state mMixerStatusIgnoringFastTracks;
1097 // FIXME or a separate ready state per track
1098
1099 // FIXME move these declarations into the specific sub-class that needs them
1100 // MIXER only
1101 uint32_t sleepTimeShift;
1102
1103 // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001104 nsecs_t mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08001105
1106 // MIXER only
1107 nsecs_t maxPeriod;
1108
1109 // DUPLICATING only
1110 uint32_t writeFrames;
1111
Eric Laurentbfb1b832013-01-07 09:53:42 -08001112 size_t mBytesRemaining;
1113 size_t mCurrentWriteLength;
1114 bool mUseAsyncWrite;
Eric Laurent3b4529e2013-09-05 18:09:19 -07001115 // mWriteAckSequence contains current write sequence on bits 31-1. The write sequence is
1116 // incremented each time a write(), a flush() or a standby() occurs.
1117 // Bit 0 is set when a write blocks and indicates a callback is expected.
1118 // Bit 0 is reset by the async callback thread calling resetWriteBlocked(). Out of sequence
1119 // callbacks are ignored.
1120 uint32_t mWriteAckSequence;
1121 // mDrainSequence contains current drain sequence on bits 31-1. The drain sequence is
1122 // incremented each time a drain is requested or a flush() or standby() occurs.
1123 // Bit 0 is set when the drain() command is called at the HAL and indicates a callback is
1124 // expected.
1125 // Bit 0 is reset by the async callback thread calling resetDraining(). Out of sequence
1126 // callbacks are ignored.
1127 uint32_t mDrainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001128 sp<AsyncCallbackThread> mCallbackThread;
1129
Eric Laurent81784c32012-11-19 14:55:58 -08001130private:
1131 // The HAL output sink is treated as non-blocking, but current implementation is blocking
1132 sp<NBAIO_Sink> mOutputSink;
1133 // If a fast mixer is present, the blocking pipe sink, otherwise clear
1134 sp<NBAIO_Sink> mPipeSink;
1135 // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink
1136 sp<NBAIO_Sink> mNormalSink;
Eric Laurent81784c32012-11-19 14:55:58 -08001137 uint32_t mScreenState; // cached copy of gScreenState
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07001138 // TODO: add comment and adjust size as needed
Glenn Kasteneef598c2017-04-03 14:41:13 -07001139 static const size_t kFastMixerLogSize = 8 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -08001140 sp<NBLog::Writer> mFastMixerNBLogWriter;
Andy Hung2148bf02016-11-28 19:01:02 -08001141
Dean Wheatley30d28422018-11-06 10:27:40 +11001142 // Downstream patch latency, available if mDownstreamLatencyStatMs.getN() > 0.
1143 audio_utils::Statistics<double> mDownstreamLatencyStatMs{0.999};
Andy Hung2148bf02016-11-28 19:01:02 -08001144
Eric Laurent81784c32012-11-19 14:55:58 -08001145public:
1146 virtual bool hasFastMixer() const = 0;
Glenn Kasten0f11b512014-01-31 16:18:54 -08001147 virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08001148 { FastTrackUnderruns dummy; return dummy; }
1149
1150protected:
1151 // accessed by both binder threads and within threadLoop(), lock on mutex needed
1152 unsigned mFastTrackAvailMask; // bit i set if fast track [i] is available
Eric Laurentd1f69b02014-12-15 14:33:13 -08001153 bool mHwSupportsPause;
1154 bool mHwPaused;
1155 bool mFlushPending;
Eric Laurent7c29ec92017-09-20 17:54:22 -07001156 // volumes last sent to audio HAL with stream->setVolume()
1157 float mLeftVolFloat;
1158 float mRightVolFloat;
Eric Laurent81784c32012-11-19 14:55:58 -08001159};
1160
1161class MixerThread : public PlaybackThread {
1162public:
1163 MixerThread(const sp<AudioFlinger>& audioFlinger,
1164 AudioStreamOut* output,
1165 audio_io_handle_t id,
1166 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001167 bool systemReady,
Eric Laurent81784c32012-11-19 14:55:58 -08001168 type_t type = MIXER);
1169 virtual ~MixerThread();
1170
1171 // Thread virtuals
1172
Eric Laurent10351942014-05-08 18:49:52 -07001173 virtual bool checkForNewParameter_l(const String8& keyValuePair,
1174 status_t& status);
Eric Laurent81784c32012-11-19 14:55:58 -08001175
Andy Hung1bc088a2018-02-09 15:57:31 -08001176 virtual bool isTrackAllowed_l(
1177 audio_channel_mask_t channelMask, audio_format_t format,
1178 audio_session_t sessionId, uid_t uid) const override;
Eric Laurent81784c32012-11-19 14:55:58 -08001179protected:
1180 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08001181 virtual uint32_t idleSleepTimeUs() const;
1182 virtual uint32_t suspendSleepTimeUs() const;
1183 virtual void cacheParameters_l();
1184
Andy Hungdae27702016-10-31 14:01:16 -07001185 virtual void acquireWakeLock_l() {
1186 PlaybackThread::acquireWakeLock_l();
Andy Hung818e7a32016-02-16 18:08:07 -08001187 if (hasFastMixer()) {
1188 mFastMixer->setBoottimeOffset(
1189 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME]);
1190 }
1191 }
1192
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001193 void dumpInternals_l(int fd, const Vector<String16>& args) override;
1194
Eric Laurent81784c32012-11-19 14:55:58 -08001195 // threadLoop snippets
Eric Laurentbfb1b832013-01-07 09:53:42 -08001196 virtual ssize_t threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08001197 virtual void threadLoop_standby();
1198 virtual void threadLoop_mix();
1199 virtual void threadLoop_sleepTime();
Eric Laurent81784c32012-11-19 14:55:58 -08001200 virtual uint32_t correctLatency_l(uint32_t latency) const;
1201
Eric Laurent054d9d32015-04-24 08:48:48 -07001202 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
1203 audio_patch_handle_t *handle);
1204 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle);
1205
Eric Laurent81784c32012-11-19 14:55:58 -08001206 AudioMixer* mAudioMixer; // normal mixer
1207private:
1208 // one-time initialization, no locks required
Glenn Kasten4d23ca32014-05-13 10:39:51 -07001209 sp<FastMixer> mFastMixer; // non-0 if there is also a fast mixer
Eric Laurent81784c32012-11-19 14:55:58 -08001210 sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread
1211
1212 // contents are not guaranteed to be consistent, no locks required
1213 FastMixerDumpState mFastMixerDumpState;
1214#ifdef STATE_QUEUE_DUMP
1215 StateQueueObserverDump mStateQueueObserverDump;
1216 StateQueueMutatorDump mStateQueueMutatorDump;
1217#endif
1218 AudioWatchdogDump mAudioWatchdogDump;
1219
1220 // accessible only within the threadLoop(), no locks required
1221 // mFastMixer->sq() // for mutating and pushing state
1222 int32_t mFastMixerFutex; // for cold idle
1223
Andy Hung2ddee192015-12-18 17:34:44 -08001224 std::atomic_bool mMasterMono;
Eric Laurent81784c32012-11-19 14:55:58 -08001225public:
Glenn Kasten4d23ca32014-05-13 10:39:51 -07001226 virtual bool hasFastMixer() const { return mFastMixer != 0; }
Eric Laurent81784c32012-11-19 14:55:58 -08001227 virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const {
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001228 ALOG_ASSERT(fastIndex < FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08001229 return mFastMixerDumpState.mTracks[fastIndex].mUnderruns;
1230 }
Eric Laurent83b88082014-06-20 18:31:16 -07001231
Andy Hung1c86ebe2018-05-29 20:29:08 -07001232 status_t threadloop_getHalTimestamp_l(
1233 ExtendedTimestamp *timestamp) const override {
1234 if (mNormalSink.get() != nullptr) {
1235 return mNormalSink->getTimestamp(*timestamp);
1236 }
1237 return INVALID_OPERATION;
1238 }
1239
Andy Hung2ddee192015-12-18 17:34:44 -08001240protected:
1241 virtual void setMasterMono_l(bool mono) {
1242 mMasterMono.store(mono);
1243 if (mFastMixer != nullptr) { /* hasFastMixer() */
1244 mFastMixer->setMasterMono(mMasterMono);
1245 }
1246 }
1247 // the FastMixer performs mono blend if it exists.
Glenn Kasten03c48d52016-01-27 17:25:17 -08001248 // Blending with limiter is not idempotent,
1249 // and blending without limiter is idempotent but inefficient to do twice.
Andy Hung2ddee192015-12-18 17:34:44 -08001250 virtual bool requireMonoBlend() { return mMasterMono.load() && !hasFastMixer(); }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001251
1252 void setMasterBalance(float balance) override {
1253 mMasterBalance.store(balance);
1254 if (hasFastMixer()) {
1255 mFastMixer->setMasterBalance(balance);
1256 }
1257 }
Eric Laurent81784c32012-11-19 14:55:58 -08001258};
1259
1260class DirectOutputThread : public PlaybackThread {
1261public:
1262
1263 DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Andy Hung48f59ed2019-01-28 15:06:59 -08001264 audio_io_handle_t id, audio_devices_t device, bool systemReady)
1265 : DirectOutputThread(audioFlinger, output, id, device, DIRECT, systemReady) { }
1266
Eric Laurent81784c32012-11-19 14:55:58 -08001267 virtual ~DirectOutputThread();
1268
Mikhail Naganovac917ac2018-11-28 14:03:52 -08001269 status_t selectPresentation(int presentationId, int programId);
1270
Eric Laurent81784c32012-11-19 14:55:58 -08001271 // Thread virtuals
1272
Eric Laurent10351942014-05-08 18:49:52 -07001273 virtual bool checkForNewParameter_l(const String8& keyValuePair,
1274 status_t& status);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001275
Eric Laurente659ef42014-09-29 13:06:46 -07001276 virtual void flushHw_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001277
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001278 void setMasterBalance(float balance) override;
1279
Eric Laurent81784c32012-11-19 14:55:58 -08001280protected:
Eric Laurent81784c32012-11-19 14:55:58 -08001281 virtual uint32_t activeSleepTimeUs() const;
1282 virtual uint32_t idleSleepTimeUs() const;
1283 virtual uint32_t suspendSleepTimeUs() const;
1284 virtual void cacheParameters_l();
1285
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001286 void dumpInternals_l(int fd, const Vector<String16>& args) override;
1287
Eric Laurent81784c32012-11-19 14:55:58 -08001288 // threadLoop snippets
1289 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
1290 virtual void threadLoop_mix();
1291 virtual void threadLoop_sleepTime();
Eric Laurentd1f69b02014-12-15 14:33:13 -08001292 virtual void threadLoop_exit();
1293 virtual bool shouldStandby_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001294
Phil Burk43b4dcc2015-06-09 16:53:44 -07001295 virtual void onAddNewTrack_l();
1296
Andy Hung48f59ed2019-01-28 15:06:59 -08001297 bool mVolumeShaperActive = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001298
Eric Laurentbfb1b832013-01-07 09:53:42 -08001299 DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Andy Hung48f59ed2019-01-28 15:06:59 -08001300 audio_io_handle_t id, audio_devices_t device, ThreadBase::type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001301 bool systemReady);
Eric Laurent5850c4c2016-11-10 13:04:31 -08001302 void processVolume_l(Track *track, bool lastTrack);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001303
Eric Laurent81784c32012-11-19 14:55:58 -08001304 // prepareTracks_l() tells threadLoop_mix() the name of the single active track
1305 sp<Track> mActiveTrack;
Phil Burk43b4dcc2015-06-09 16:53:44 -07001306
1307 wp<Track> mPreviousTrack; // used to detect track switch
1308
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001309 // This must be initialized for initial condition of mMasterBalance = 0 (disabled).
1310 float mMasterBalanceLeft = 1.f;
1311 float mMasterBalanceRight = 1.f;
1312
Eric Laurent81784c32012-11-19 14:55:58 -08001313public:
1314 virtual bool hasFastMixer() const { return false; }
Andy Hung10cbff12017-02-21 17:30:14 -08001315
1316 virtual int64_t computeWaitTimeNs_l() const override;
Andy Hungf3234512018-07-03 14:51:47 -07001317
1318 status_t threadloop_getHalTimestamp_l(ExtendedTimestamp *timestamp) const override {
1319 // For DIRECT and OFFLOAD threads, query the output sink directly.
1320 if (mOutput != nullptr) {
1321 uint64_t uposition64;
1322 struct timespec time;
1323 if (mOutput->getPresentationPosition(
1324 &uposition64, &time) == OK) {
1325 timestamp->mPosition[ExtendedTimestamp::LOCATION_KERNEL]
1326 = (int64_t)uposition64;
1327 timestamp->mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
1328 = audio_utils_ns_from_timespec(&time);
1329 return NO_ERROR;
1330 }
1331 }
1332 return INVALID_OPERATION;
1333 }
Eric Laurent81784c32012-11-19 14:55:58 -08001334};
1335
Eric Laurentbfb1b832013-01-07 09:53:42 -08001336class OffloadThread : public DirectOutputThread {
1337public:
1338
1339 OffloadThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurente93cc032016-05-05 10:15:10 -07001340 audio_io_handle_t id, uint32_t device, bool systemReady);
Eric Laurent6a51d7e2013-10-17 18:59:26 -07001341 virtual ~OffloadThread() {};
Eric Laurente659ef42014-09-29 13:06:46 -07001342 virtual void flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001343
1344protected:
1345 // threadLoop snippets
1346 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
1347 virtual void threadLoop_exit();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001348
1349 virtual bool waitingAsyncCallback();
1350 virtual bool waitingAsyncCallback_l();
Haynes Mathew George05317d22016-05-03 16:34:26 -07001351 virtual void invalidateTracks(audio_stream_type_t streamType);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001352
Eric Laurentde0613d2016-07-22 18:19:11 -07001353 virtual bool keepWakeLock() const { return (mKeepWakeLock || (mDrainSequence & 1)); }
Eric Laurent64667972016-03-30 18:19:46 -07001354
Eric Laurentbfb1b832013-01-07 09:53:42 -08001355private:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001356 size_t mPausedWriteLength; // length in bytes of write interrupted by pause
1357 size_t mPausedBytesRemaining; // bytes still waiting in mixbuffer after resume
Eric Laurent64667972016-03-30 18:19:46 -07001358 bool mKeepWakeLock; // keep wake lock while waiting for write callback
Andy Hungf8044752016-07-27 14:58:11 -07001359 uint64_t mOffloadUnderrunPosition; // Current frame position for offloaded playback
1360 // used and valid only during underrun. ~0 if
1361 // no underrun has occurred during playback and
1362 // is not reset on standby.
Eric Laurentbfb1b832013-01-07 09:53:42 -08001363};
1364
1365class AsyncCallbackThread : public Thread {
1366public:
1367
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001368 explicit AsyncCallbackThread(const wp<PlaybackThread>& playbackThread);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001369
1370 virtual ~AsyncCallbackThread();
1371
1372 // Thread virtuals
1373 virtual bool threadLoop();
1374
1375 // RefBase
1376 virtual void onFirstRef();
1377
1378 void exit();
Eric Laurent3b4529e2013-09-05 18:09:19 -07001379 void setWriteBlocked(uint32_t sequence);
1380 void resetWriteBlocked();
1381 void setDraining(uint32_t sequence);
1382 void resetDraining();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07001383 void setAsyncError();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001384
1385private:
Eric Laurent4de95592013-09-26 15:28:21 -07001386 const wp<PlaybackThread> mPlaybackThread;
Eric Laurent3b4529e2013-09-05 18:09:19 -07001387 // mWriteAckSequence corresponds to the last write sequence passed by the offload thread via
1388 // setWriteBlocked(). The sequence is shifted one bit to the left and the lsb is used
1389 // to indicate that the callback has been received via resetWriteBlocked()
Eric Laurent4de95592013-09-26 15:28:21 -07001390 uint32_t mWriteAckSequence;
Eric Laurent3b4529e2013-09-05 18:09:19 -07001391 // mDrainSequence corresponds to the last drain sequence passed by the offload thread via
1392 // setDraining(). The sequence is shifted one bit to the left and the lsb is used
1393 // to indicate that the callback has been received via resetDraining()
Eric Laurent4de95592013-09-26 15:28:21 -07001394 uint32_t mDrainSequence;
1395 Condition mWaitWorkCV;
1396 Mutex mLock;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07001397 bool mAsyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001398};
1399
Eric Laurent81784c32012-11-19 14:55:58 -08001400class DuplicatingThread : public MixerThread {
1401public:
1402 DuplicatingThread(const sp<AudioFlinger>& audioFlinger, MixerThread* mainThread,
Eric Laurent72e3f392015-05-20 14:43:50 -07001403 audio_io_handle_t id, bool systemReady);
Eric Laurent81784c32012-11-19 14:55:58 -08001404 virtual ~DuplicatingThread();
1405
1406 // Thread virtuals
1407 void addOutputTrack(MixerThread* thread);
1408 void removeOutputTrack(MixerThread* thread);
1409 uint32_t waitTimeMs() const { return mWaitTimeMs; }
Kevin Rocard069c2712018-03-29 19:09:14 -07001410
Kevin Rocardc86a7f72018-04-03 09:00:09 -07001411 void sendMetadataToBackend_l(
1412 const StreamOutHalInterface::SourceMetadata& metadata) override;
Eric Laurent81784c32012-11-19 14:55:58 -08001413protected:
1414 virtual uint32_t activeSleepTimeUs() const;
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001415 void dumpInternals_l(int fd, const Vector<String16>& args) override;
Eric Laurent81784c32012-11-19 14:55:58 -08001416
1417private:
1418 bool outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks);
1419protected:
1420 // threadLoop snippets
1421 virtual void threadLoop_mix();
1422 virtual void threadLoop_sleepTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001423 virtual ssize_t threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08001424 virtual void threadLoop_standby();
1425 virtual void cacheParameters_l();
1426
1427private:
1428 // called from threadLoop, addOutputTrack, removeOutputTrack
1429 virtual void updateWaitTime_l();
1430protected:
1431 virtual void saveOutputTracks();
1432 virtual void clearOutputTracks();
1433private:
1434
1435 uint32_t mWaitTimeMs;
1436 SortedVector < sp<OutputTrack> > outputTracks;
1437 SortedVector < sp<OutputTrack> > mOutputTracks;
1438public:
1439 virtual bool hasFastMixer() const { return false; }
Andy Hung1c86ebe2018-05-29 20:29:08 -07001440 status_t threadloop_getHalTimestamp_l(
1441 ExtendedTimestamp *timestamp) const override {
1442 if (mOutputTracks.size() > 0) {
1443 // forward the first OutputTrack's kernel information for timestamp.
1444 const ExtendedTimestamp trackTimestamp =
1445 mOutputTracks[0]->getClientProxyTimestamp();
1446 if (trackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] > 0) {
1447 timestamp->mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
1448 trackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
1449 timestamp->mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
1450 trackTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
1451 return OK; // discard server timestamp - that's ignored.
1452 }
1453 }
1454 return INVALID_OPERATION;
1455 }
Eric Laurent81784c32012-11-19 14:55:58 -08001456};
1457
Eric Laurent81784c32012-11-19 14:55:58 -08001458// record thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001459class RecordThread : public ThreadBase
Eric Laurent81784c32012-11-19 14:55:58 -08001460{
1461public:
1462
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001463 class RecordTrack;
Andy Hung73c02e42015-03-29 01:13:58 -07001464
1465 /* The ResamplerBufferProvider is used to retrieve recorded input data from the
1466 * RecordThread. It maintains local state on the relative position of the read
1467 * position of the RecordTrack compared with the RecordThread.
1468 */
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001469 class ResamplerBufferProvider : public AudioBufferProvider
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001470 {
1471 public:
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001472 explicit ResamplerBufferProvider(RecordTrack* recordTrack) :
Andy Hung73c02e42015-03-29 01:13:58 -07001473 mRecordTrack(recordTrack),
1474 mRsmpInUnrel(0), mRsmpInFront(0) { }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001475 virtual ~ResamplerBufferProvider() { }
Andy Hung73c02e42015-03-29 01:13:58 -07001476
1477 // called to set the ResamplerBufferProvider to head of the RecordThread data buffer,
1478 // skipping any previous data read from the hal.
1479 virtual void reset();
1480
1481 /* Synchronizes RecordTrack position with the RecordThread.
1482 * Calculates available frames and handle overruns if the RecordThread
1483 * has advanced faster than the ResamplerBufferProvider has retrieved data.
1484 * TODO: why not do this for every getNextBuffer?
1485 *
1486 * Parameters
1487 * framesAvailable: pointer to optional output size_t to store record track
1488 * frames available.
1489 * hasOverrun: pointer to optional boolean, returns true if track has overrun.
1490 */
1491
1492 virtual void sync(size_t *framesAvailable = NULL, bool *hasOverrun = NULL);
1493
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001494 // AudioBufferProvider interface
Glenn Kastend79072e2016-01-06 08:41:20 -08001495 virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001496 virtual void releaseBuffer(AudioBufferProvider::Buffer* buffer);
1497 private:
1498 RecordTrack * const mRecordTrack;
Andy Hung73c02e42015-03-29 01:13:58 -07001499 size_t mRsmpInUnrel; // unreleased frames remaining from
1500 // most recent getNextBuffer
1501 // for debug only
1502 int32_t mRsmpInFront; // next available frame
1503 // rolling counter that is never cleared
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001504 };
1505
Eric Laurent81784c32012-11-19 14:55:58 -08001506#include "RecordTracks.h"
1507
1508 RecordThread(const sp<AudioFlinger>& audioFlinger,
1509 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08001510 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08001511 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07001512 audio_devices_t inDevice,
1513 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08001514 );
Eric Laurent81784c32012-11-19 14:55:58 -08001515 virtual ~RecordThread();
1516
1517 // no addTrack_l ?
1518 void destroyTrack_l(const sp<RecordTrack>& track);
1519 void removeTrack_l(const sp<RecordTrack>& track);
1520
Eric Laurent81784c32012-11-19 14:55:58 -08001521 // Thread virtuals
1522 virtual bool threadLoop();
Eric Laurent555530a2017-02-07 18:17:24 -08001523 virtual void preExit();
Eric Laurent81784c32012-11-19 14:55:58 -08001524
1525 // RefBase
1526 virtual void onFirstRef();
1527
1528 virtual status_t initCheck() const { return (mInput == NULL) ? NO_INIT : NO_ERROR; }
Glenn Kastene198c362013-08-13 09:13:36 -07001529
Glenn Kastenb880f5e2014-05-07 08:43:45 -07001530 virtual sp<MemoryDealer> readOnlyHeap() const { return mReadOnlyHeap; }
1531
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001532 virtual sp<IMemory> pipeMemory() const { return mPipeMemory; }
1533
Eric Laurent81784c32012-11-19 14:55:58 -08001534 sp<AudioFlinger::RecordThread::RecordTrack> createRecordTrack_l(
1535 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001536 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001537 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001538 audio_format_t format,
1539 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001540 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08001541 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001542 size_t *pNotificationFrameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001543 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07001544 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001545 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001546 status_t *status /*non-NULL*/,
1547 audio_port_handle_t portId);
Eric Laurent81784c32012-11-19 14:55:58 -08001548
1549 status_t start(RecordTrack* recordTrack,
1550 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08001551 audio_session_t triggerSession);
Eric Laurent81784c32012-11-19 14:55:58 -08001552
1553 // ask the thread to stop the specified track, and
1554 // return true if the caller should then do it's part of the stopping process
Glenn Kastena8356f62013-07-25 14:37:52 -07001555 bool stop(RecordTrack* recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08001556
Eric Laurent81784c32012-11-19 14:55:58 -08001557 AudioStreamIn* clearInput();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001558 virtual sp<StreamHalInterface> stream() const;
Eric Laurent81784c32012-11-19 14:55:58 -08001559
Eric Laurent81784c32012-11-19 14:55:58 -08001560
Eric Laurent10351942014-05-08 18:49:52 -07001561 virtual bool checkForNewParameter_l(const String8& keyValuePair,
1562 status_t& status);
1563 virtual void cacheParameters_l() {}
Eric Laurent81784c32012-11-19 14:55:58 -08001564 virtual String8 getParameters(const String8& keys);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001565 virtual void ioConfigChanged(audio_io_config_event event, pid_t pid = 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07001566 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
1567 audio_patch_handle_t *handle);
1568 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle);
Eric Laurent83b88082014-06-20 18:31:16 -07001569
Mikhail Naganov444ecc32018-05-01 17:40:05 -07001570 void addPatchTrack(const sp<PatchRecord>& record);
1571 void deletePatchTrack(const sp<PatchRecord>& record);
Eric Laurent83b88082014-06-20 18:31:16 -07001572
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001573 void readInputParameters_l();
Glenn Kasten5f972c02014-01-13 09:59:31 -08001574 virtual uint32_t getInputFramesLost();
Eric Laurent81784c32012-11-19 14:55:58 -08001575
1576 virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
1577 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
Andy Hungc3d62f92019-03-14 13:38:51 -07001578 uint32_t hasAudioSession_l(audio_session_t sessionId) const override {
1579 return ThreadBase::hasAudioSession_l(sessionId, mTracks);
1580 }
Eric Laurent81784c32012-11-19 14:55:58 -08001581
1582 // Return the set of unique session IDs across all tracks.
1583 // The keys are the session IDs, and the associated values are meaningless.
1584 // FIXME replace by Set [and implement Bag/Multiset for other uses].
Glenn Kastend848eb42016-03-08 13:42:11 -08001585 KeyedVector<audio_session_t, bool> sessionIds() const;
Eric Laurent81784c32012-11-19 14:55:58 -08001586
1587 virtual status_t setSyncEvent(const sp<SyncEvent>& event);
1588 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const;
1589
1590 static void syncStartEventCallback(const wp<SyncEvent>& event);
Eric Laurent81784c32012-11-19 14:55:58 -08001591
Glenn Kasten9b58f632013-07-16 11:37:48 -07001592 virtual size_t frameCount() const { return mFrameCount; }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001593 bool hasFastCapture() const { return mFastCapture != 0; }
Mikhail Naganovdc769682018-05-04 15:34:08 -07001594 virtual void toAudioPortConfig(struct audio_port_config *config);
Glenn Kasten9b58f632013-07-16 11:37:48 -07001595
Eric Laurent4c415062016-06-17 16:14:16 -07001596 virtual status_t checkEffectCompatibility_l(const effect_descriptor_t *desc,
1597 audio_session_t sessionId);
1598
Andy Hungdae27702016-10-31 14:01:16 -07001599 virtual void acquireWakeLock_l() {
1600 ThreadBase::acquireWakeLock_l();
1601 mActiveTracks.updatePowerState(this, true /* force */);
1602 }
Andy Hung293558a2017-03-21 12:19:20 -07001603 virtual bool isOutput() const override { return false; }
Andy Hungdae27702016-10-31 14:01:16 -07001604
Eric Laurentd8365c52017-07-16 15:27:05 -07001605 void checkBtNrec();
1606
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001607 // Sets the UID records silence
1608 void setRecordSilenced(uid_t uid, bool silenced);
1609
jiabin653cc0a2018-01-17 17:54:10 -08001610 status_t getActiveMicrophones(std::vector<media::MicrophoneInfo>* activeMicrophones);
1611
Paul McLean12340082019-03-19 09:35:05 -06001612 status_t setPreferredMicrophoneDirection(audio_microphone_direction_t direction);
1613 status_t setPreferredMicrophoneFieldDimension(float zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07001614
Kevin Rocard069c2712018-03-29 19:09:14 -07001615 void updateMetadata_l() override;
1616
jiabin01c8f562018-07-19 17:47:28 -07001617 bool fastTrackAvailable() const { return mFastTrackAvail; }
1618
Andy Hungc8fddf32018-08-08 18:32:37 -07001619 bool isTimestampCorrectionEnabled() const override {
1620 // checks popcount for exactly one device.
1621 return audio_is_input_device(
1622 mInDevice & mTimestampCorrectedDevices);
1623 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001624
1625protected:
1626 void dumpInternals_l(int fd, const Vector<String16>& args) override;
1627 void dumpTracks_l(int fd, const Vector<String16>& args) override;
1628
Eric Laurent81784c32012-11-19 14:55:58 -08001629private:
Eric Laurent81784c32012-11-19 14:55:58 -08001630 // Enter standby if not already in standby, and set mStandby flag
Glenn Kasten93e471f2013-08-19 08:40:07 -07001631 void standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08001632
1633 // Call the HAL standby method unconditionally, and don't change mStandby flag
Glenn Kastene198c362013-08-13 09:13:36 -07001634 void inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08001635
Eric Laurentd8365c52017-07-16 15:27:05 -07001636 void checkBtNrec_l();
1637
Eric Laurent81784c32012-11-19 14:55:58 -08001638 AudioStreamIn *mInput;
1639 SortedVector < sp<RecordTrack> > mTracks;
Glenn Kasten2b806402013-11-20 16:37:38 -08001640 // mActiveTracks has dual roles: it indicates the current active track(s), and
Eric Laurent81784c32012-11-19 14:55:58 -08001641 // is used together with mStartStopCond to indicate start()/stop() progress
Andy Hungdae27702016-10-31 14:01:16 -07001642 ActiveTracks<RecordTrack> mActiveTracks;
1643
Eric Laurent81784c32012-11-19 14:55:58 -08001644 Condition mStartStopCond;
Glenn Kasten9b58f632013-07-16 11:37:48 -07001645
Glenn Kasten85948432013-08-19 12:09:05 -07001646 // resampler converts input at HAL Hz to output at AudioRecord client Hz
Glenn Kasten1b291842016-07-18 14:55:21 -07001647 void *mRsmpInBuffer; // size = mRsmpInFramesOA
Glenn Kasten85948432013-08-19 12:09:05 -07001648 size_t mRsmpInFrames; // size of resampler input in frames
1649 size_t mRsmpInFramesP2;// size rounded up to a power-of-2
Glenn Kasten1b291842016-07-18 14:55:21 -07001650 size_t mRsmpInFramesOA;// mRsmpInFramesP2 + over-allocation
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001651
1652 // rolling index that is never cleared
Glenn Kasten85948432013-08-19 12:09:05 -07001653 int32_t mRsmpInRear; // last filled frame + 1
Glenn Kasten85948432013-08-19 12:09:05 -07001654
Eric Laurent81784c32012-11-19 14:55:58 -08001655 // For dumpsys
Glenn Kastenb880f5e2014-05-07 08:43:45 -07001656 const sp<MemoryDealer> mReadOnlyHeap;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001657
1658 // one-time initialization, no locks required
Glenn Kastenb187de12014-12-30 08:18:15 -08001659 sp<FastCapture> mFastCapture; // non-0 if there is also
1660 // a fast capture
Eric Laurent72e3f392015-05-20 14:43:50 -07001661
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001662 // FIXME audio watchdog thread
1663
1664 // contents are not guaranteed to be consistent, no locks required
1665 FastCaptureDumpState mFastCaptureDumpState;
1666#ifdef STATE_QUEUE_DUMP
1667 // FIXME StateQueue observer and mutator dump fields
1668#endif
1669 // FIXME audio watchdog dump
1670
1671 // accessible only within the threadLoop(), no locks required
1672 // mFastCapture->sq() // for mutating and pushing state
1673 int32_t mFastCaptureFutex; // for cold idle
1674
1675 // The HAL input source is treated as non-blocking,
1676 // but current implementation is blocking
1677 sp<NBAIO_Source> mInputSource;
1678 // The source for the normal capture thread to read from: mInputSource or mPipeSource
1679 sp<NBAIO_Source> mNormalSource;
1680 // If a fast capture is present, the non-blocking pipe sink written to by fast capture,
1681 // otherwise clear
1682 sp<NBAIO_Sink> mPipeSink;
1683 // If a fast capture is present, the non-blocking pipe source read by normal thread,
1684 // otherwise clear
1685 sp<NBAIO_Source> mPipeSource;
1686 // Depth of pipe from fast capture to normal thread and fast clients, always power of 2
1687 size_t mPipeFramesP2;
1688 // If a fast capture is present, the Pipe as IMemory, otherwise clear
1689 sp<IMemory> mPipeMemory;
1690
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07001691 // TODO: add comment and adjust size as needed
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001692 static const size_t kFastCaptureLogSize = 4 * 1024;
1693 sp<NBLog::Writer> mFastCaptureNBLogWriter;
1694
1695 bool mFastTrackAvail; // true if fast track available
Eric Laurentd8365c52017-07-16 15:27:05 -07001696 // common state to all record threads
1697 std::atomic_bool mBtNrecSuspended;
Andy Hung6427e442018-08-09 12:51:02 -07001698
1699 int64_t mFramesRead = 0; // continuous running counter.
Eric Laurent81784c32012-11-19 14:55:58 -08001700};
Eric Laurent6acd1d42017-01-04 14:23:29 -08001701
1702class MmapThread : public ThreadBase
1703{
1704 public:
1705
1706#include "MmapTracks.h"
1707
1708 MmapThread(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1709 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
1710 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady);
1711 virtual ~MmapThread();
1712
1713 virtual void configure(const audio_attributes_t *attr,
1714 audio_stream_type_t streamType,
1715 audio_session_t sessionId,
1716 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07001717 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08001718 audio_port_handle_t portId);
1719
1720 void disconnect();
1721
1722 // MmapStreamInterface
1723 status_t createMmapBuffer(int32_t minSizeFrames,
1724 struct audio_mmap_buffer_info *info);
1725 status_t getMmapPosition(struct audio_mmap_position *position);
Eric Laurenta54f1282017-07-01 19:39:32 -07001726 status_t start(const AudioClient& client, audio_port_handle_t *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001727 status_t stop(audio_port_handle_t handle);
Eric Laurent18b57012017-02-13 16:23:52 -08001728 status_t standby();
Eric Laurent6acd1d42017-01-04 14:23:29 -08001729
1730 // RefBase
1731 virtual void onFirstRef();
1732
1733 // Thread virtuals
1734 virtual bool threadLoop();
1735
1736 virtual void threadLoop_exit();
1737 virtual void threadLoop_standby();
Eric Laurent18b57012017-02-13 16:23:52 -08001738 virtual bool shouldStandby_l() { return false; }
Eric Laurent331679c2018-04-16 17:03:16 -07001739 virtual status_t exitStandby();
Eric Laurent6acd1d42017-01-04 14:23:29 -08001740
1741 virtual status_t initCheck() const { return (mHalStream == 0) ? NO_INIT : NO_ERROR; }
1742 virtual size_t frameCount() const { return mFrameCount; }
1743 virtual bool checkForNewParameter_l(const String8& keyValuePair,
1744 status_t& status);
1745 virtual String8 getParameters(const String8& keys);
1746 virtual void ioConfigChanged(audio_io_config_event event, pid_t pid = 0);
1747 void readHalParameters_l();
1748 virtual void cacheParameters_l() {}
1749 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
1750 audio_patch_handle_t *handle);
1751 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07001752 virtual void toAudioPortConfig(struct audio_port_config *config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001753
1754 virtual sp<StreamHalInterface> stream() const { return mHalStream; }
1755 virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
1756 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
1757 virtual status_t checkEffectCompatibility_l(const effect_descriptor_t *desc,
1758 audio_session_t sessionId);
1759
Andy Hungc3d62f92019-03-14 13:38:51 -07001760 uint32_t hasAudioSession_l(audio_session_t sessionId) const override {
1761 // Note: using mActiveTracks as no mTracks here.
1762 return ThreadBase::hasAudioSession_l(sessionId, mActiveTracks);
1763 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001764 virtual status_t setSyncEvent(const sp<SyncEvent>& event);
1765 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const;
1766
1767 virtual void checkSilentMode_l() {}
1768 virtual void processVolume_l() {}
1769 void checkInvalidTracks_l();
1770
1771 virtual audio_stream_type_t streamType() { return AUDIO_STREAM_DEFAULT; }
1772
1773 virtual void invalidateTracks(audio_stream_type_t streamType __unused) {}
1774
Eric Laurent331679c2018-04-16 17:03:16 -07001775 // Sets the UID records silence
1776 virtual void setRecordSilenced(uid_t uid __unused, bool silenced __unused) {}
1777
Eric Laurent6acd1d42017-01-04 14:23:29 -08001778 protected:
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001779 void dumpInternals_l(int fd, const Vector<String16>& args) override;
1780 void dumpTracks_l(int fd, const Vector<String16>& args) override;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001781
1782 audio_attributes_t mAttr;
1783 audio_session_t mSessionId;
1784 audio_port_handle_t mPortId;
1785
Phil Burk7f6b40d2017-02-09 13:18:38 -08001786 wp<MmapStreamCallback> mCallback;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001787 sp<StreamHalInterface> mHalStream;
1788 sp<DeviceHalInterface> mHalDevice;
1789 AudioHwDevice* const mAudioHwDev;
1790 ActiveTracks<MmapTrack> mActiveTracks;
Eric Laurent67f97292018-04-20 18:05:41 -07001791 float mHalVolFloat;
Eric Laurent331679c2018-04-16 17:03:16 -07001792
1793 int32_t mNoCallbackWarningCount;
1794 static constexpr int32_t kMaxNoCallbackWarnings = 5;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001795};
1796
1797class MmapPlaybackThread : public MmapThread, public VolumeInterface
1798{
1799
1800public:
1801 MmapPlaybackThread(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1802 AudioHwDevice *hwDev, AudioStreamOut *output,
1803 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady);
1804 virtual ~MmapPlaybackThread() {}
1805
1806 virtual void configure(const audio_attributes_t *attr,
1807 audio_stream_type_t streamType,
1808 audio_session_t sessionId,
1809 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07001810 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08001811 audio_port_handle_t portId);
1812
1813 AudioStreamOut* clearOutput();
1814
1815 // VolumeInterface
1816 virtual void setMasterVolume(float value);
1817 virtual void setMasterMute(bool muted);
1818 virtual void setStreamVolume(audio_stream_type_t stream, float value);
1819 virtual void setStreamMute(audio_stream_type_t stream, bool muted);
1820 virtual float streamVolume(audio_stream_type_t stream) const;
1821
1822 void setMasterMute_l(bool muted) { mMasterMute = muted; }
1823
1824 virtual void invalidateTracks(audio_stream_type_t streamType);
1825
1826 virtual audio_stream_type_t streamType() { return mStreamType; }
1827 virtual void checkSilentMode_l();
Eric Laurent331679c2018-04-16 17:03:16 -07001828 void processVolume_l() override;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001829
Andy Hung293558a2017-03-21 12:19:20 -07001830 virtual bool isOutput() const override { return true; }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001831
Kevin Rocard069c2712018-03-29 19:09:14 -07001832 void updateMetadata_l() override;
1833
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07001834 virtual void toAudioPortConfig(struct audio_port_config *config);
1835
Eric Laurent6acd1d42017-01-04 14:23:29 -08001836protected:
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001837 void dumpInternals_l(int fd, const Vector<String16>& args) override;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001838
1839 audio_stream_type_t mStreamType;
1840 float mMasterVolume;
1841 float mStreamVolume;
1842 bool mMasterMute;
1843 bool mStreamMute;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001844 AudioStreamOut* mOutput;
1845};
1846
1847class MmapCaptureThread : public MmapThread
1848{
1849
1850public:
1851 MmapCaptureThread(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1852 AudioHwDevice *hwDev, AudioStreamIn *input,
1853 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady);
1854 virtual ~MmapCaptureThread() {}
1855
1856 AudioStreamIn* clearInput();
1857
Eric Laurent331679c2018-04-16 17:03:16 -07001858 status_t exitStandby() override;
Andy Hung293558a2017-03-21 12:19:20 -07001859 virtual bool isOutput() const override { return false; }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001860
Kevin Rocard069c2712018-03-29 19:09:14 -07001861 void updateMetadata_l() override;
Eric Laurent331679c2018-04-16 17:03:16 -07001862 void processVolume_l() override;
1863 void setRecordSilenced(uid_t uid, bool silenced) override;
Kevin Rocard069c2712018-03-29 19:09:14 -07001864
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07001865 virtual void toAudioPortConfig(struct audio_port_config *config);
1866
Eric Laurent6acd1d42017-01-04 14:23:29 -08001867protected:
1868
1869 AudioStreamIn* mInput;
1870};