blob: 2ed2915b40adf7147b0cf538b149862451c89fe4 [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
32 OFFLOAD // Thread class is OffloadThread
Eric Laurent81784c32012-11-19 14:55:58 -080033 };
34
35 ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
36 audio_devices_t outDevice, audio_devices_t inDevice, type_t type);
37 virtual ~ThreadBase();
38
Glenn Kastencf04c2c2013-08-06 07:41:16 -070039 virtual status_t readyToRun();
40
Eric Laurent81784c32012-11-19 14:55:58 -080041 void dumpBase(int fd, const Vector<String16>& args);
42 void dumpEffectChains(int fd, const Vector<String16>& args);
43
44 void clearPowerManager();
45
46 // base for record and playback
47 enum {
48 CFG_EVENT_IO,
Eric Laurent10351942014-05-08 18:49:52 -070049 CFG_EVENT_PRIO,
50 CFG_EVENT_SET_PARAMETER,
Eric Laurent1c333e22014-05-20 10:48:17 -070051 CFG_EVENT_CREATE_AUDIO_PATCH,
52 CFG_EVENT_RELEASE_AUDIO_PATCH,
Eric Laurent81784c32012-11-19 14:55:58 -080053 };
54
Eric Laurent10351942014-05-08 18:49:52 -070055 class ConfigEventData: public RefBase {
Eric Laurent81784c32012-11-19 14:55:58 -080056 public:
Eric Laurent10351942014-05-08 18:49:52 -070057 virtual ~ConfigEventData() {}
Eric Laurent81784c32012-11-19 14:55:58 -080058
59 virtual void dump(char *buffer, size_t size) = 0;
Eric Laurent10351942014-05-08 18:49:52 -070060 protected:
61 ConfigEventData() {}
Eric Laurent81784c32012-11-19 14:55:58 -080062 };
63
Eric Laurent10351942014-05-08 18:49:52 -070064 // Config event sequence by client if status needed (e.g binder thread calling setParameters()):
65 // 1. create SetParameterConfigEvent. This sets mWaitStatus in config event
66 // 2. Lock mLock
67 // 3. Call sendConfigEvent_l(): Append to mConfigEvents and mWaitWorkCV.signal
68 // 4. sendConfigEvent_l() reads status from event->mStatus;
69 // 5. sendConfigEvent_l() returns status
70 // 6. Unlock
71 //
72 // Parameter sequence by server: threadLoop calling processConfigEvents_l():
73 // 1. Lock mLock
74 // 2. If there is an entry in mConfigEvents proceed ...
75 // 3. Read first entry in mConfigEvents
76 // 4. Remove first entry from mConfigEvents
77 // 5. Process
78 // 6. Set event->mStatus
79 // 7. event->mCond.signal
80 // 8. Unlock
Eric Laurent81784c32012-11-19 14:55:58 -080081
Eric Laurent10351942014-05-08 18:49:52 -070082 class ConfigEvent: public RefBase {
83 public:
84 virtual ~ConfigEvent() {}
85
86 void dump(char *buffer, size_t size) { mData->dump(buffer, size); }
87
88 const int mType; // event type e.g. CFG_EVENT_IO
89 Mutex mLock; // mutex associated with mCond
90 Condition mCond; // condition for status return
91 status_t mStatus; // status communicated to sender
92 bool mWaitStatus; // true if sender is waiting for status
93 sp<ConfigEventData> mData; // event specific parameter data
94
95 protected:
96 ConfigEvent(int type) : mType(type), mStatus(NO_ERROR), mWaitStatus(false), mData(NULL) {}
97 };
98
99 class IoConfigEventData : public ConfigEventData {
100 public:
101 IoConfigEventData(int event, int param) :
102 mEvent(event), mParam(param) {}
Eric Laurent81784c32012-11-19 14:55:58 -0800103
104 virtual void dump(char *buffer, size_t size) {
105 snprintf(buffer, size, "IO event: event %d, param %d\n", mEvent, mParam);
106 }
107
Eric Laurent81784c32012-11-19 14:55:58 -0800108 const int mEvent;
109 const int mParam;
110 };
111
Eric Laurent10351942014-05-08 18:49:52 -0700112 class IoConfigEvent : public ConfigEvent {
Eric Laurent81784c32012-11-19 14:55:58 -0800113 public:
Eric Laurent10351942014-05-08 18:49:52 -0700114 IoConfigEvent(int event, int param) :
115 ConfigEvent(CFG_EVENT_IO) {
116 mData = new IoConfigEventData(event, param);
117 }
118 virtual ~IoConfigEvent() {}
119 };
Eric Laurent81784c32012-11-19 14:55:58 -0800120
Eric Laurent10351942014-05-08 18:49:52 -0700121 class PrioConfigEventData : public ConfigEventData {
122 public:
123 PrioConfigEventData(pid_t pid, pid_t tid, int32_t prio) :
124 mPid(pid), mTid(tid), mPrio(prio) {}
Eric Laurent81784c32012-11-19 14:55:58 -0800125
126 virtual void dump(char *buffer, size_t size) {
127 snprintf(buffer, size, "Prio event: pid %d, tid %d, prio %d\n", mPid, mTid, mPrio);
128 }
129
Eric Laurent81784c32012-11-19 14:55:58 -0800130 const pid_t mPid;
131 const pid_t mTid;
132 const int32_t mPrio;
133 };
134
Eric Laurent10351942014-05-08 18:49:52 -0700135 class PrioConfigEvent : public ConfigEvent {
136 public:
137 PrioConfigEvent(pid_t pid, pid_t tid, int32_t prio) :
138 ConfigEvent(CFG_EVENT_PRIO) {
139 mData = new PrioConfigEventData(pid, tid, prio);
140 }
141 virtual ~PrioConfigEvent() {}
142 };
143
144 class SetParameterConfigEventData : public ConfigEventData {
145 public:
146 SetParameterConfigEventData(String8 keyValuePairs) :
147 mKeyValuePairs(keyValuePairs) {}
148
149 virtual void dump(char *buffer, size_t size) {
150 snprintf(buffer, size, "KeyValue: %s\n", mKeyValuePairs.string());
151 }
152
153 const String8 mKeyValuePairs;
154 };
155
156 class SetParameterConfigEvent : public ConfigEvent {
157 public:
158 SetParameterConfigEvent(String8 keyValuePairs) :
159 ConfigEvent(CFG_EVENT_SET_PARAMETER) {
160 mData = new SetParameterConfigEventData(keyValuePairs);
161 mWaitStatus = true;
162 }
163 virtual ~SetParameterConfigEvent() {}
164 };
165
Eric Laurent1c333e22014-05-20 10:48:17 -0700166 class CreateAudioPatchConfigEventData : public ConfigEventData {
167 public:
168 CreateAudioPatchConfigEventData(const struct audio_patch patch,
169 audio_patch_handle_t handle) :
170 mPatch(patch), mHandle(handle) {}
171
172 virtual void dump(char *buffer, size_t size) {
173 snprintf(buffer, size, "Patch handle: %u\n", mHandle);
174 }
175
176 const struct audio_patch mPatch;
177 audio_patch_handle_t mHandle;
178 };
179
180 class CreateAudioPatchConfigEvent : public ConfigEvent {
181 public:
182 CreateAudioPatchConfigEvent(const struct audio_patch patch,
183 audio_patch_handle_t handle) :
184 ConfigEvent(CFG_EVENT_CREATE_AUDIO_PATCH) {
185 mData = new CreateAudioPatchConfigEventData(patch, handle);
186 mWaitStatus = true;
187 }
188 virtual ~CreateAudioPatchConfigEvent() {}
189 };
190
191 class ReleaseAudioPatchConfigEventData : public ConfigEventData {
192 public:
193 ReleaseAudioPatchConfigEventData(const audio_patch_handle_t handle) :
194 mHandle(handle) {}
195
196 virtual void dump(char *buffer, size_t size) {
197 snprintf(buffer, size, "Patch handle: %u\n", mHandle);
198 }
199
200 audio_patch_handle_t mHandle;
201 };
202
203 class ReleaseAudioPatchConfigEvent : public ConfigEvent {
204 public:
205 ReleaseAudioPatchConfigEvent(const audio_patch_handle_t handle) :
206 ConfigEvent(CFG_EVENT_RELEASE_AUDIO_PATCH) {
207 mData = new ReleaseAudioPatchConfigEventData(handle);
208 mWaitStatus = true;
209 }
210 virtual ~ReleaseAudioPatchConfigEvent() {}
211 };
Eric Laurent81784c32012-11-19 14:55:58 -0800212
213 class PMDeathRecipient : public IBinder::DeathRecipient {
214 public:
215 PMDeathRecipient(const wp<ThreadBase>& thread) : mThread(thread) {}
216 virtual ~PMDeathRecipient() {}
217
218 // IBinder::DeathRecipient
219 virtual void binderDied(const wp<IBinder>& who);
220
221 private:
222 PMDeathRecipient(const PMDeathRecipient&);
223 PMDeathRecipient& operator = (const PMDeathRecipient&);
224
225 wp<ThreadBase> mThread;
226 };
227
228 virtual status_t initCheck() const = 0;
229
230 // static externally-visible
231 type_t type() const { return mType; }
Eric Laurentb97ee932015-05-08 10:50:03 -0700232 bool isDuplicating() const { return (mType == DUPLICATING); }
233
Eric Laurent81784c32012-11-19 14:55:58 -0800234 audio_io_handle_t id() const { return mId;}
235
236 // dynamic externally-visible
237 uint32_t sampleRate() const { return mSampleRate; }
Eric Laurent81784c32012-11-19 14:55:58 -0800238 audio_channel_mask_t channelMask() const { return mChannelMask; }
Andy Hung463be252014-07-10 16:56:07 -0700239 audio_format_t format() const { return mHALFormat; }
Eric Laurent83b88082014-06-20 18:31:16 -0700240 uint32_t channelCount() const { return mChannelCount; }
Eric Laurent81784c32012-11-19 14:55:58 -0800241 // Called by AudioFlinger::frameCount(audio_io_handle_t output) and effects,
Glenn Kasten9b58f632013-07-16 11:37:48 -0700242 // and returns the [normal mix] buffer's frame count.
243 virtual size_t frameCount() const = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800244 size_t frameSize() const { return mFrameSize; }
Eric Laurent81784c32012-11-19 14:55:58 -0800245
246 // Should be "virtual status_t requestExitAndWait()" and override same
247 // method in Thread, but Thread::requestExitAndWait() is not yet virtual.
248 void exit();
Eric Laurent10351942014-05-08 18:49:52 -0700249 virtual bool checkForNewParameter_l(const String8& keyValuePair,
250 status_t& status) = 0;
Eric Laurent81784c32012-11-19 14:55:58 -0800251 virtual status_t setParameters(const String8& keyValuePairs);
252 virtual String8 getParameters(const String8& keys) = 0;
Eric Laurent021cf962014-05-13 10:18:14 -0700253 virtual void audioConfigChanged(int event, int param = 0) = 0;
Eric Laurent10351942014-05-08 18:49:52 -0700254 // sendConfigEvent_l() must be called with ThreadBase::mLock held
255 // Can temporarily release the lock if waiting for a reply from
256 // processConfigEvents_l().
257 status_t sendConfigEvent_l(sp<ConfigEvent>& event);
Eric Laurent81784c32012-11-19 14:55:58 -0800258 void sendIoConfigEvent(int event, int param = 0);
259 void sendIoConfigEvent_l(int event, int param = 0);
260 void sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio);
Eric Laurent10351942014-05-08 18:49:52 -0700261 status_t sendSetParameterConfigEvent_l(const String8& keyValuePair);
Eric Laurent1c333e22014-05-20 10:48:17 -0700262 status_t sendCreateAudioPatchConfigEvent(const struct audio_patch *patch,
263 audio_patch_handle_t *handle);
264 status_t sendReleaseAudioPatchConfigEvent(audio_patch_handle_t handle);
Eric Laurent021cf962014-05-13 10:18:14 -0700265 void processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -0700266 virtual void cacheParameters_l() = 0;
Eric Laurent1c333e22014-05-20 10:48:17 -0700267 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
268 audio_patch_handle_t *handle) = 0;
269 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle) = 0;
Eric Laurent83b88082014-06-20 18:31:16 -0700270 virtual void getAudioPortConfig(struct audio_port_config *config) = 0;
Eric Laurent1c333e22014-05-20 10:48:17 -0700271
Eric Laurent81784c32012-11-19 14:55:58 -0800272
273 // see note at declaration of mStandby, mOutDevice and mInDevice
274 bool standby() const { return mStandby; }
275 audio_devices_t outDevice() const { return mOutDevice; }
276 audio_devices_t inDevice() const { return mInDevice; }
277
278 virtual audio_stream_t* stream() const = 0;
279
280 sp<EffectHandle> createEffect_l(
281 const sp<AudioFlinger::Client>& client,
282 const sp<IEffectClient>& effectClient,
283 int32_t priority,
284 int sessionId,
285 effect_descriptor_t *desc,
286 int *enabled,
Eric Laurent7da83aa2016-12-01 15:28:29 -0800287 status_t *status /*non-NULL*/,
288 bool pinned);
Eric Laurent81784c32012-11-19 14:55:58 -0800289
290 // return values for hasAudioSession (bit field)
291 enum effect_state {
292 EFFECT_SESSION = 0x1, // the audio session corresponds to at least one
293 // effect
294 TRACK_SESSION = 0x2 // the audio session corresponds to at least one
295 // track
296 };
297
298 // get effect chain corresponding to session Id.
299 sp<EffectChain> getEffectChain(int sessionId);
300 // same as getEffectChain() but must be called with ThreadBase mutex locked
301 sp<EffectChain> getEffectChain_l(int sessionId) const;
302 // add an effect chain to the chain list (mEffectChains)
303 virtual status_t addEffectChain_l(const sp<EffectChain>& chain) = 0;
304 // remove an effect chain from the chain list (mEffectChains)
305 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain) = 0;
306 // lock all effect chains Mutexes. Must be called before releasing the
307 // ThreadBase mutex before processing the mixer and effects. This guarantees the
308 // integrity of the chains during the process.
309 // Also sets the parameter 'effectChains' to current value of mEffectChains.
310 void lockEffectChains_l(Vector< sp<EffectChain> >& effectChains);
311 // unlock effect chains after process
312 void unlockEffectChains(const Vector< sp<EffectChain> >& effectChains);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800313 // get a copy of mEffectChains vector
314 Vector< sp<EffectChain> > getEffectChains_l() const { return mEffectChains; };
Eric Laurent81784c32012-11-19 14:55:58 -0800315 // set audio mode to all effect chains
316 void setMode(audio_mode_t mode);
317 // get effect module with corresponding ID on specified audio session
318 sp<AudioFlinger::EffectModule> getEffect(int sessionId, int effectId);
319 sp<AudioFlinger::EffectModule> getEffect_l(int sessionId, int effectId);
320 // add and effect module. Also creates the effect chain is none exists for
321 // the effects audio session
322 status_t addEffect_l(const sp< EffectModule>& effect);
323 // remove and effect module. Also removes the effect chain is this was the last
324 // effect
Eric Laurent7da83aa2016-12-01 15:28:29 -0800325 void removeEffect_l(const sp< EffectModule>& effect, bool release = false);
326 // disconnect an effect handle from module and destroy module if last handle
327 void disconnectEffectHandle(EffectHandle *handle, bool unpinIfLast);
Eric Laurent81784c32012-11-19 14:55:58 -0800328 // detach all tracks connected to an auxiliary effect
Glenn Kasten0f11b512014-01-31 16:18:54 -0800329 virtual void detachAuxEffect_l(int effectId __unused) {}
Eric Laurent81784c32012-11-19 14:55:58 -0800330 // returns either EFFECT_SESSION if effects on this audio session exist in one
331 // chain, or TRACK_SESSION if tracks on this audio session exist, or both
332 virtual uint32_t hasAudioSession(int sessionId) const = 0;
333 // the value returned by default implementation is not important as the
334 // strategy is only meaningful for PlaybackThread which implements this method
Glenn Kasten0f11b512014-01-31 16:18:54 -0800335 virtual uint32_t getStrategyForSession_l(int sessionId __unused) { return 0; }
Eric Laurent81784c32012-11-19 14:55:58 -0800336
337 // suspend or restore effect according to the type of effect passed. a NULL
338 // type pointer means suspend all effects in the session
339 void setEffectSuspended(const effect_uuid_t *type,
340 bool suspend,
341 int sessionId = AUDIO_SESSION_OUTPUT_MIX);
342 // check if some effects must be suspended/restored when an effect is enabled
343 // or disabled
344 void checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
345 bool enabled,
346 int sessionId = AUDIO_SESSION_OUTPUT_MIX);
347 void checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
348 bool enabled,
349 int sessionId = AUDIO_SESSION_OUTPUT_MIX);
350
351 virtual status_t setSyncEvent(const sp<SyncEvent>& event) = 0;
352 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const = 0;
353
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700354 // Return a reference to a per-thread heap which can be used to allocate IMemory
355 // objects that will be read-only to client processes, read/write to mediaserver,
356 // and shared by all client processes of the thread.
357 // The heap is per-thread rather than common across all threads, because
358 // clients can't be trusted not to modify the offset of the IMemory they receive.
359 // If a thread does not have such a heap, this method returns 0.
360 virtual sp<MemoryDealer> readOnlyHeap() const { return 0; }
Eric Laurent81784c32012-11-19 14:55:58 -0800361
Glenn Kasten6181ffd2014-05-13 10:41:52 -0700362 virtual sp<IMemory> pipeMemory() const { return 0; }
363
Eric Laurent81784c32012-11-19 14:55:58 -0800364 mutable Mutex mLock;
365
366protected:
367
368 // entry describing an effect being suspended in mSuspendedSessions keyed vector
369 class SuspendedSessionDesc : public RefBase {
370 public:
371 SuspendedSessionDesc() : mRefCount(0) {}
372
373 int mRefCount; // number of active suspend requests
374 effect_uuid_t mType; // effect type UUID
375 };
376
Marco Nelissene14a5d62013-10-03 08:51:24 -0700377 void acquireWakeLock(int uid = -1);
378 void acquireWakeLock_l(int uid = -1);
Eric Laurent81784c32012-11-19 14:55:58 -0800379 void releaseWakeLock();
380 void releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800381 void updateWakeLockUids(const SortedVector<int> &uids);
382 void updateWakeLockUids_l(const SortedVector<int> &uids);
383 void getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800384 void setEffectSuspended_l(const effect_uuid_t *type,
385 bool suspend,
386 int sessionId);
387 // updated mSuspendedSessions when an effect suspended or restored
388 void updateSuspendedSessions_l(const effect_uuid_t *type,
389 bool suspend,
390 int sessionId);
391 // check if some effects must be suspended when an effect chain is added
392 void checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain);
393
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100394 String16 getWakeLockTag();
395
Eric Laurent81784c32012-11-19 14:55:58 -0800396 virtual void preExit() { }
397
398 friend class AudioFlinger; // for mEffectChains
399
400 const type_t mType;
401
402 // Used by parameters, config events, addTrack_l, exit
403 Condition mWaitWorkCV;
404
405 const sp<AudioFlinger> mAudioFlinger;
Glenn Kasten9b58f632013-07-16 11:37:48 -0700406
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800407 // updated by PlaybackThread::readOutputParameters_l() or
408 // RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800409 uint32_t mSampleRate;
410 size_t mFrameCount; // output HAL, direct output, record
Eric Laurent81784c32012-11-19 14:55:58 -0800411 audio_channel_mask_t mChannelMask;
Glenn Kastenf6ed4232013-07-16 11:16:27 -0700412 uint32_t mChannelCount;
Eric Laurent81784c32012-11-19 14:55:58 -0800413 size_t mFrameSize;
Andy Hung463be252014-07-10 16:56:07 -0700414 audio_format_t mFormat; // Source format for Recording and
415 // Sink format for Playback.
416 // Sink format may be different than
417 // HAL format if Fastmixer is used.
418 audio_format_t mHALFormat;
Glenn Kasten70949c42013-08-06 07:40:12 -0700419 size_t mBufferSize; // HAL buffer size for read() or write()
Eric Laurent81784c32012-11-19 14:55:58 -0800420
Eric Laurent10351942014-05-08 18:49:52 -0700421 Vector< sp<ConfigEvent> > mConfigEvents;
Eric Laurent81784c32012-11-19 14:55:58 -0800422
423 // These fields are written and read by thread itself without lock or barrier,
Glenn Kasten4944acb2013-08-19 08:39:20 -0700424 // and read by other threads without lock or barrier via standby(), outDevice()
Eric Laurent81784c32012-11-19 14:55:58 -0800425 // and inDevice().
426 // Because of the absence of a lock or barrier, any other thread that reads
427 // these fields must use the information in isolation, or be prepared to deal
428 // with possibility that it might be inconsistent with other information.
Glenn Kasten4944acb2013-08-19 08:39:20 -0700429 bool mStandby; // Whether thread is currently in standby.
Eric Laurent81784c32012-11-19 14:55:58 -0800430 audio_devices_t mOutDevice; // output device
431 audio_devices_t mInDevice; // input device
432 audio_source_t mAudioSource; // (see audio.h, audio_source_t)
433
434 const audio_io_handle_t mId;
435 Vector< sp<EffectChain> > mEffectChains;
436
437 static const int kNameLength = 16; // prctl(PR_SET_NAME) limit
438 char mName[kNameLength];
439 sp<IPowerManager> mPowerManager;
440 sp<IBinder> mWakeLockToken;
441 const sp<PMDeathRecipient> mDeathRecipient;
442 // list of suspended effects per session and per type. The first vector is
443 // keyed by session ID, the second by type UUID timeLow field
444 KeyedVector< int, KeyedVector< int, sp<SuspendedSessionDesc> > >
445 mSuspendedSessions;
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800446 static const size_t kLogSize = 4 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -0800447 sp<NBLog::Writer> mNBLogWriter;
Eric Laurent81784c32012-11-19 14:55:58 -0800448};
449
450// --- PlaybackThread ---
451class PlaybackThread : public ThreadBase {
452public:
453
454#include "PlaybackTracks.h"
455
456 enum mixer_state {
457 MIXER_IDLE, // no active tracks
458 MIXER_TRACKS_ENABLED, // at least one active track, but no track has any data ready
Eric Laurentbfb1b832013-01-07 09:53:42 -0800459 MIXER_TRACKS_READY, // at least one active track, and at least one track has data
460 MIXER_DRAIN_TRACK, // drain currently playing track
461 MIXER_DRAIN_ALL, // fully drain the hardware
Eric Laurent81784c32012-11-19 14:55:58 -0800462 // standby mode does not have an enum value
463 // suspend by audio policy manager is orthogonal to mixer state
464 };
465
Eric Laurentbfb1b832013-01-07 09:53:42 -0800466 // retry count before removing active track in case of underrun on offloaded thread:
467 // we need to make sure that AudioTrack client has enough time to send large buffers
468//FIXME may be more appropriate if expressed in time units. Need to revise how underrun is handled
469 // for offloaded tracks
470 static const int8_t kMaxTrackRetriesOffload = 20;
471
Eric Laurent81784c32012-11-19 14:55:58 -0800472 PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
473 audio_io_handle_t id, audio_devices_t device, type_t type);
474 virtual ~PlaybackThread();
475
476 void dump(int fd, const Vector<String16>& args);
477
478 // Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -0800479 virtual bool threadLoop();
480
481 // RefBase
482 virtual void onFirstRef();
483
484protected:
485 // Code snippets that were lifted up out of threadLoop()
486 virtual void threadLoop_mix() = 0;
487 virtual void threadLoop_sleepTime() = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800488 virtual ssize_t threadLoop_write();
489 virtual void threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -0800490 virtual void threadLoop_standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800491 virtual void threadLoop_exit();
Eric Laurent81784c32012-11-19 14:55:58 -0800492 virtual void threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
493
494 // prepareTracks_l reads and writes mActiveTracks, and returns
495 // the pending set of tracks to remove via Vector 'tracksToRemove'. The caller
496 // is responsible for clearing or destroying this Vector later on, when it
497 // is safe to do so. That will drop the final ref count and destroy the tracks.
498 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove) = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800499 void removeTracks_l(const Vector< sp<Track> >& tracksToRemove);
500
501 void writeCallback();
Eric Laurent3b4529e2013-09-05 18:09:19 -0700502 void resetWriteBlocked(uint32_t sequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800503 void drainCallback();
Eric Laurent3b4529e2013-09-05 18:09:19 -0700504 void resetDraining(uint32_t sequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800505
506 static int asyncCallback(stream_callback_event_t event, void *param, void *cookie);
507
508 virtual bool waitingAsyncCallback();
509 virtual bool waitingAsyncCallback_l();
510 virtual bool shouldStandby_l();
Haynes Mathew George4c6a4332014-01-15 12:31:39 -0800511 virtual void onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800512
513 // ThreadBase virtuals
514 virtual void preExit();
515
516public:
517
518 virtual status_t initCheck() const { return (mOutput == NULL) ? NO_INIT : NO_ERROR; }
519
520 // return estimated latency in milliseconds, as reported by HAL
521 uint32_t latency() const;
522 // same, but lock must already be held
523 uint32_t latency_l() const;
524
525 void setMasterVolume(float value);
526 void setMasterMute(bool muted);
527
528 void setStreamVolume(audio_stream_type_t stream, float value);
529 void setStreamMute(audio_stream_type_t stream, bool muted);
530
531 float streamVolume(audio_stream_type_t stream) const;
532
533 sp<Track> createTrack_l(
534 const sp<AudioFlinger::Client>& client,
535 audio_stream_type_t streamType,
536 uint32_t sampleRate,
537 audio_format_t format,
538 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -0800539 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -0800540 const sp<IMemory>& sharedBuffer,
541 int sessionId,
542 IAudioFlinger::track_flags_t *flags,
543 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800544 int uid,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700545 status_t *status /*non-NULL*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800546
547 AudioStreamOut* getOutput() const;
548 AudioStreamOut* clearOutput();
549 virtual audio_stream_t* stream() const;
550
551 // a very large number of suspend() will eventually wraparound, but unlikely
552 void suspend() { (void) android_atomic_inc(&mSuspended); }
553 void restore()
554 {
555 // if restore() is done without suspend(), get back into
556 // range so that the next suspend() will operate correctly
557 if (android_atomic_dec(&mSuspended) <= 0) {
558 android_atomic_release_store(0, &mSuspended);
559 }
560 }
561 bool isSuspended() const
562 { return android_atomic_acquire_load(&mSuspended) > 0; }
563
564 virtual String8 getParameters(const String8& keys);
Eric Laurent021cf962014-05-13 10:18:14 -0700565 virtual void audioConfigChanged(int event, int param = 0);
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000566 status_t getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames);
Andy Hung010a1a12014-03-13 13:57:33 -0700567 // FIXME rename mixBuffer() to sinkBuffer() and remove int16_t* dependency.
568 // Consider also removing and passing an explicit mMainBuffer initialization
569 // parameter to AF::PlaybackThread::Track::Track().
570 int16_t *mixBuffer() const {
571 return reinterpret_cast<int16_t *>(mSinkBuffer); };
Eric Laurent81784c32012-11-19 14:55:58 -0800572
573 virtual void detachAuxEffect_l(int effectId);
574 status_t attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track> track,
575 int EffectId);
576 status_t attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track> track,
577 int EffectId);
578
579 virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
580 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
581 virtual uint32_t hasAudioSession(int sessionId) const;
582 virtual uint32_t getStrategyForSession_l(int sessionId);
583
584
585 virtual status_t setSyncEvent(const sp<SyncEvent>& event);
586 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const;
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700587
588 // called with AudioFlinger lock held
Eric Laurent81784c32012-11-19 14:55:58 -0800589 void invalidateTracks(audio_stream_type_t streamType);
590
Glenn Kasten9b58f632013-07-16 11:37:48 -0700591 virtual size_t frameCount() const { return mNormalFrameCount; }
592
593 // Return's the HAL's frame count i.e. fast mixer buffer size.
594 size_t frameCountHAL() const { return mFrameCount; }
Eric Laurent81784c32012-11-19 14:55:58 -0800595
Eric Laurent83b88082014-06-20 18:31:16 -0700596 status_t getTimestamp_l(AudioTimestamp& timestamp);
597
598 void addPatchTrack(const sp<PatchTrack>& track);
599 void deletePatchTrack(const sp<PatchTrack>& track);
600
601 virtual void getAudioPortConfig(struct audio_port_config *config);
Eric Laurentaccc1472013-09-20 09:36:34 -0700602
Eric Laurent81784c32012-11-19 14:55:58 -0800603protected:
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800604 // updated by readOutputParameters_l()
Glenn Kasten9b58f632013-07-16 11:37:48 -0700605 size_t mNormalFrameCount; // normal mixer and effects
606
Andy Hung010a1a12014-03-13 13:57:33 -0700607 void* mSinkBuffer; // frame size aligned sink buffer
Eric Laurent81784c32012-11-19 14:55:58 -0800608
Andy Hung98ef9782014-03-04 14:46:50 -0800609 // TODO:
610 // Rearrange the buffer info into a struct/class with
611 // clear, copy, construction, destruction methods.
612 //
613 // mSinkBuffer also has associated with it:
614 //
615 // mSinkBufferSize: Sink Buffer Size
616 // mFormat: Sink Buffer Format
617
Andy Hung69aed5f2014-02-25 17:24:40 -0800618 // Mixer Buffer (mMixerBuffer*)
619 //
620 // In the case of floating point or multichannel data, which is not in the
621 // sink format, it is required to accumulate in a higher precision or greater channel count
622 // buffer before downmixing or data conversion to the sink buffer.
623
624 // Set to "true" to enable the Mixer Buffer otherwise mixer output goes to sink buffer.
625 bool mMixerBufferEnabled;
626
627 // Storage, 32 byte aligned (may make this alignment a requirement later).
628 // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
629 void* mMixerBuffer;
630
631 // Size of mMixerBuffer in bytes: mNormalFrameCount * #channels * sampsize.
632 size_t mMixerBufferSize;
633
634 // The audio format of mMixerBuffer. Set to AUDIO_FORMAT_PCM_(FLOAT|16_BIT) only.
635 audio_format_t mMixerBufferFormat;
636
637 // An internal flag set to true by MixerThread::prepareTracks_l()
638 // when mMixerBuffer contains valid data after mixing.
639 bool mMixerBufferValid;
640
Andy Hung98ef9782014-03-04 14:46:50 -0800641 // Effects Buffer (mEffectsBuffer*)
642 //
643 // In the case of effects data, which is not in the sink format,
644 // it is required to accumulate in a different buffer before data conversion
645 // to the sink buffer.
646
647 // Set to "true" to enable the Effects Buffer otherwise effects output goes to sink buffer.
648 bool mEffectBufferEnabled;
649
650 // Storage, 32 byte aligned (may make this alignment a requirement later).
651 // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
652 void* mEffectBuffer;
653
654 // Size of mEffectsBuffer in bytes: mNormalFrameCount * #channels * sampsize.
655 size_t mEffectBufferSize;
656
657 // The audio format of mEffectsBuffer. Set to AUDIO_FORMAT_PCM_16_BIT only.
658 audio_format_t mEffectBufferFormat;
659
660 // An internal flag set to true by MixerThread::prepareTracks_l()
661 // when mEffectsBuffer contains valid data after mixing.
662 //
663 // When this is set, all mixer data is routed into the effects buffer
664 // for any processing (including output processing).
665 bool mEffectBufferValid;
666
Eric Laurent81784c32012-11-19 14:55:58 -0800667 // suspend count, > 0 means suspended. While suspended, the thread continues to pull from
668 // tracks and mix, but doesn't write to HAL. A2DP and SCO HAL implementations can't handle
669 // concurrent use of both of them, so Audio Policy Service suspends one of the threads to
670 // workaround that restriction.
671 // 'volatile' means accessed via atomic operations and no lock.
672 volatile int32_t mSuspended;
673
674 // FIXME overflows every 6+ hours at 44.1 kHz stereo 16-bit samples
675 // mFramesWritten would be better, or 64-bit even better
676 size_t mBytesWritten;
677private:
678 // mMasterMute is in both PlaybackThread and in AudioFlinger. When a
679 // PlaybackThread needs to find out if master-muted, it checks it's local
680 // copy rather than the one in AudioFlinger. This optimization saves a lock.
681 bool mMasterMute;
682 void setMasterMute_l(bool muted) { mMasterMute = muted; }
683protected:
684 SortedVector< wp<Track> > mActiveTracks; // FIXME check if this could be sp<>
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800685 SortedVector<int> mWakeLockUids;
686 int mActiveTracksGeneration;
Eric Laurentfd477972013-10-25 18:10:40 -0700687 wp<Track> mLatestActiveTrack; // latest track added to mActiveTracks
Eric Laurent81784c32012-11-19 14:55:58 -0800688
689 // Allocate a track name for a given channel mask.
690 // Returns name >= 0 if successful, -1 on failure.
Andy Hunge8a1ced2014-05-09 15:02:21 -0700691 virtual int getTrackName_l(audio_channel_mask_t channelMask,
692 audio_format_t format, int sessionId) = 0;
Eric Laurent81784c32012-11-19 14:55:58 -0800693 virtual void deleteTrackName_l(int name) = 0;
694
695 // Time to sleep between cycles when:
696 virtual uint32_t activeSleepTimeUs() const; // mixer state MIXER_TRACKS_ENABLED
697 virtual uint32_t idleSleepTimeUs() const = 0; // mixer state MIXER_IDLE
698 virtual uint32_t suspendSleepTimeUs() const = 0; // audio policy manager suspended us
699 // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write()
700 // No sleep in standby mode; waits on a condition
701
702 // Code snippets that are temporarily lifted up out of threadLoop() until the merge
703 void checkSilentMode_l();
704
705 // Non-trivial for DUPLICATING only
706 virtual void saveOutputTracks() { }
707 virtual void clearOutputTracks() { }
708
709 // Cache various calculated values, at threadLoop() entry and after a parameter change
710 virtual void cacheParameters_l();
711
712 virtual uint32_t correctLatency_l(uint32_t latency) const;
713
Eric Laurent1c333e22014-05-20 10:48:17 -0700714 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
715 audio_patch_handle_t *handle);
716 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle);
717
Eric Laurent0f7b5f22014-12-19 10:43:21 -0800718 bool usesHwAvSync() const { return (mType == DIRECT) && (mOutput != NULL) &&
719 (mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC); }
720
Eric Laurent81784c32012-11-19 14:55:58 -0800721private:
722
723 friend class AudioFlinger; // for numerous
724
Eric Laurent81784c32012-11-19 14:55:58 -0800725 PlaybackThread& operator = (const PlaybackThread&);
726
727 status_t addTrack_l(const sp<Track>& track);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800728 bool destroyTrack_l(const sp<Track>& track);
Eric Laurent81784c32012-11-19 14:55:58 -0800729 void removeTrack_l(const sp<Track>& track);
Eric Laurentede6c3b2013-09-19 14:37:46 -0700730 void broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800731
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800732 void readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800733
734 virtual void dumpInternals(int fd, const Vector<String16>& args);
735 void dumpTracks(int fd, const Vector<String16>& args);
736
737 SortedVector< sp<Track> > mTracks;
Eric Laurent223fd5c2014-11-11 13:43:36 -0800738 stream_type_t mStreamTypes[AUDIO_STREAM_CNT];
Eric Laurent81784c32012-11-19 14:55:58 -0800739 AudioStreamOut *mOutput;
740
741 float mMasterVolume;
742 nsecs_t mLastWriteTime;
743 int mNumWrites;
744 int mNumDelayedWrites;
745 bool mInWrite;
746
747 // FIXME rename these former local variables of threadLoop to standard "m" names
748 nsecs_t standbyTime;
Andy Hung25c2dac2014-02-27 14:56:00 -0800749 size_t mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -0800750
751 // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l()
752 uint32_t activeSleepTime;
753 uint32_t idleSleepTime;
754
755 uint32_t sleepTime;
756
757 // mixer status returned by prepareTracks_l()
758 mixer_state mMixerStatus; // current cycle
759 // previous cycle when in prepareTracks_l()
760 mixer_state mMixerStatusIgnoringFastTracks;
761 // FIXME or a separate ready state per track
762
763 // FIXME move these declarations into the specific sub-class that needs them
764 // MIXER only
765 uint32_t sleepTimeShift;
766
767 // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value
768 nsecs_t standbyDelay;
769
770 // MIXER only
771 nsecs_t maxPeriod;
772
773 // DUPLICATING only
774 uint32_t writeFrames;
775
Eric Laurentbfb1b832013-01-07 09:53:42 -0800776 size_t mBytesRemaining;
777 size_t mCurrentWriteLength;
778 bool mUseAsyncWrite;
Eric Laurent3b4529e2013-09-05 18:09:19 -0700779 // mWriteAckSequence contains current write sequence on bits 31-1. The write sequence is
780 // incremented each time a write(), a flush() or a standby() occurs.
781 // Bit 0 is set when a write blocks and indicates a callback is expected.
782 // Bit 0 is reset by the async callback thread calling resetWriteBlocked(). Out of sequence
783 // callbacks are ignored.
784 uint32_t mWriteAckSequence;
785 // mDrainSequence contains current drain sequence on bits 31-1. The drain sequence is
786 // incremented each time a drain is requested or a flush() or standby() occurs.
787 // Bit 0 is set when the drain() command is called at the HAL and indicates a callback is
788 // expected.
789 // Bit 0 is reset by the async callback thread calling resetDraining(). Out of sequence
790 // callbacks are ignored.
791 uint32_t mDrainSequence;
Eric Laurentede6c3b2013-09-19 14:37:46 -0700792 // A condition that must be evaluated by prepareTrack_l() has changed and we must not wait
793 // for async write callback in the thread loop before evaluating it
Eric Laurentbfb1b832013-01-07 09:53:42 -0800794 bool mSignalPending;
795 sp<AsyncCallbackThread> mCallbackThread;
796
Eric Laurent81784c32012-11-19 14:55:58 -0800797private:
798 // The HAL output sink is treated as non-blocking, but current implementation is blocking
799 sp<NBAIO_Sink> mOutputSink;
800 // If a fast mixer is present, the blocking pipe sink, otherwise clear
801 sp<NBAIO_Sink> mPipeSink;
802 // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink
803 sp<NBAIO_Sink> mNormalSink;
Glenn Kasten46909e72013-02-26 09:20:22 -0800804#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -0800805 // For dumpsys
806 sp<NBAIO_Sink> mTeeSink;
807 sp<NBAIO_Source> mTeeSource;
Glenn Kasten46909e72013-02-26 09:20:22 -0800808#endif
Eric Laurent81784c32012-11-19 14:55:58 -0800809 uint32_t mScreenState; // cached copy of gScreenState
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800810 static const size_t kFastMixerLogSize = 4 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -0800811 sp<NBLog::Writer> mFastMixerNBLogWriter;
Eric Laurent81784c32012-11-19 14:55:58 -0800812public:
813 virtual bool hasFastMixer() const = 0;
Glenn Kasten0f11b512014-01-31 16:18:54 -0800814 virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -0800815 { FastTrackUnderruns dummy; return dummy; }
816
817protected:
818 // accessed by both binder threads and within threadLoop(), lock on mutex needed
819 unsigned mFastTrackAvailMask; // bit i set if fast track [i] is available
Eric Laurentd1f69b02014-12-15 14:33:13 -0800820 bool mHwSupportsPause;
821 bool mHwPaused;
822 bool mFlushPending;
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700823private:
824 // timestamp latch:
825 // D input is written by threadLoop_write while mutex is unlocked, and read while locked
826 // Q output is written while locked, and read while locked
827 struct {
828 AudioTimestamp mTimestamp;
829 uint32_t mUnpresentedFrames;
Glenn Kasten4c053ea2014-09-28 14:41:07 -0700830 KeyedVector<Track *, uint32_t> mFramesReleased;
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700831 } mLatchD, mLatchQ;
Glenn Kasten4c053ea2014-09-28 14:41:07 -0700832 bool mLatchDValid; // true means mLatchD is valid
833 // (except for mFramesReleased which is filled in later),
834 // and clock it into latch at next opportunity
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700835 bool mLatchQValid; // true means mLatchQ is valid
Eric Laurent81784c32012-11-19 14:55:58 -0800836};
837
838class MixerThread : public PlaybackThread {
839public:
840 MixerThread(const sp<AudioFlinger>& audioFlinger,
841 AudioStreamOut* output,
842 audio_io_handle_t id,
843 audio_devices_t device,
844 type_t type = MIXER);
845 virtual ~MixerThread();
846
847 // Thread virtuals
848
Eric Laurent10351942014-05-08 18:49:52 -0700849 virtual bool checkForNewParameter_l(const String8& keyValuePair,
850 status_t& status);
Eric Laurent81784c32012-11-19 14:55:58 -0800851 virtual void dumpInternals(int fd, const Vector<String16>& args);
852
853protected:
854 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
Andy Hunge8a1ced2014-05-09 15:02:21 -0700855 virtual int getTrackName_l(audio_channel_mask_t channelMask,
856 audio_format_t format, int sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800857 virtual void deleteTrackName_l(int name);
858 virtual uint32_t idleSleepTimeUs() const;
859 virtual uint32_t suspendSleepTimeUs() const;
860 virtual void cacheParameters_l();
861
862 // threadLoop snippets
Eric Laurentbfb1b832013-01-07 09:53:42 -0800863 virtual ssize_t threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -0800864 virtual void threadLoop_standby();
865 virtual void threadLoop_mix();
866 virtual void threadLoop_sleepTime();
867 virtual void threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
868 virtual uint32_t correctLatency_l(uint32_t latency) const;
869
870 AudioMixer* mAudioMixer; // normal mixer
871private:
872 // one-time initialization, no locks required
Glenn Kasten4d23ca32014-05-13 10:39:51 -0700873 sp<FastMixer> mFastMixer; // non-0 if there is also a fast mixer
Eric Laurent81784c32012-11-19 14:55:58 -0800874 sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread
875
876 // contents are not guaranteed to be consistent, no locks required
877 FastMixerDumpState mFastMixerDumpState;
878#ifdef STATE_QUEUE_DUMP
879 StateQueueObserverDump mStateQueueObserverDump;
880 StateQueueMutatorDump mStateQueueMutatorDump;
881#endif
882 AudioWatchdogDump mAudioWatchdogDump;
883
884 // accessible only within the threadLoop(), no locks required
885 // mFastMixer->sq() // for mutating and pushing state
886 int32_t mFastMixerFutex; // for cold idle
887
888public:
Glenn Kasten4d23ca32014-05-13 10:39:51 -0700889 virtual bool hasFastMixer() const { return mFastMixer != 0; }
Eric Laurent81784c32012-11-19 14:55:58 -0800890 virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const {
891 ALOG_ASSERT(fastIndex < FastMixerState::kMaxFastTracks);
892 return mFastMixerDumpState.mTracks[fastIndex].mUnderruns;
893 }
Eric Laurent83b88082014-06-20 18:31:16 -0700894
Eric Laurent81784c32012-11-19 14:55:58 -0800895};
896
897class DirectOutputThread : public PlaybackThread {
898public:
899
900 DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
901 audio_io_handle_t id, audio_devices_t device);
902 virtual ~DirectOutputThread();
903
904 // Thread virtuals
905
Eric Laurent10351942014-05-08 18:49:52 -0700906 virtual bool checkForNewParameter_l(const String8& keyValuePair,
907 status_t& status);
Eric Laurente659ef42014-09-29 13:06:46 -0700908 virtual void flushHw_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800909
910protected:
Andy Hunge8a1ced2014-05-09 15:02:21 -0700911 virtual int getTrackName_l(audio_channel_mask_t channelMask,
912 audio_format_t format, int sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800913 virtual void deleteTrackName_l(int name);
914 virtual uint32_t activeSleepTimeUs() const;
915 virtual uint32_t idleSleepTimeUs() const;
916 virtual uint32_t suspendSleepTimeUs() const;
917 virtual void cacheParameters_l();
918
919 // threadLoop snippets
920 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
921 virtual void threadLoop_mix();
922 virtual void threadLoop_sleepTime();
Eric Laurentd1f69b02014-12-15 14:33:13 -0800923 virtual void threadLoop_exit();
924 virtual bool shouldStandby_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800925
Eric Laurent81784c32012-11-19 14:55:58 -0800926 // volumes last sent to audio HAL with stream->set_volume()
927 float mLeftVolFloat;
928 float mRightVolFloat;
929
Eric Laurentbfb1b832013-01-07 09:53:42 -0800930 DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
931 audio_io_handle_t id, uint32_t device, ThreadBase::type_t type);
932 void processVolume_l(Track *track, bool lastTrack);
933
Eric Laurent81784c32012-11-19 14:55:58 -0800934 // prepareTracks_l() tells threadLoop_mix() the name of the single active track
935 sp<Track> mActiveTrack;
936public:
937 virtual bool hasFastMixer() const { return false; }
938};
939
Eric Laurentbfb1b832013-01-07 09:53:42 -0800940class OffloadThread : public DirectOutputThread {
941public:
942
943 OffloadThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
944 audio_io_handle_t id, uint32_t device);
Eric Laurent6a51d7e2013-10-17 18:59:26 -0700945 virtual ~OffloadThread() {};
Eric Laurente659ef42014-09-29 13:06:46 -0700946 virtual void flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800947
948protected:
949 // threadLoop snippets
950 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
951 virtual void threadLoop_exit();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800952
953 virtual bool waitingAsyncCallback();
954 virtual bool waitingAsyncCallback_l();
Haynes Mathew George4c6a4332014-01-15 12:31:39 -0800955 virtual void onAddNewTrack_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800956
957private:
Eric Laurentbfb1b832013-01-07 09:53:42 -0800958 size_t mPausedWriteLength; // length in bytes of write interrupted by pause
959 size_t mPausedBytesRemaining; // bytes still waiting in mixbuffer after resume
Eric Laurentd7e59222013-11-15 12:02:28 -0800960 wp<Track> mPreviousTrack; // used to detect track switch
Eric Laurentbfb1b832013-01-07 09:53:42 -0800961};
962
963class AsyncCallbackThread : public Thread {
964public:
965
Eric Laurent4de95592013-09-26 15:28:21 -0700966 AsyncCallbackThread(const wp<PlaybackThread>& playbackThread);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800967
968 virtual ~AsyncCallbackThread();
969
970 // Thread virtuals
971 virtual bool threadLoop();
972
973 // RefBase
974 virtual void onFirstRef();
975
976 void exit();
Eric Laurent3b4529e2013-09-05 18:09:19 -0700977 void setWriteBlocked(uint32_t sequence);
978 void resetWriteBlocked();
979 void setDraining(uint32_t sequence);
980 void resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800981
982private:
Eric Laurent4de95592013-09-26 15:28:21 -0700983 const wp<PlaybackThread> mPlaybackThread;
Eric Laurent3b4529e2013-09-05 18:09:19 -0700984 // mWriteAckSequence corresponds to the last write sequence passed by the offload thread via
985 // setWriteBlocked(). The sequence is shifted one bit to the left and the lsb is used
986 // to indicate that the callback has been received via resetWriteBlocked()
Eric Laurent4de95592013-09-26 15:28:21 -0700987 uint32_t mWriteAckSequence;
Eric Laurent3b4529e2013-09-05 18:09:19 -0700988 // mDrainSequence corresponds to the last drain sequence passed by the offload thread via
989 // setDraining(). The sequence is shifted one bit to the left and the lsb is used
990 // to indicate that the callback has been received via resetDraining()
Eric Laurent4de95592013-09-26 15:28:21 -0700991 uint32_t mDrainSequence;
992 Condition mWaitWorkCV;
993 Mutex mLock;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800994};
995
Eric Laurent81784c32012-11-19 14:55:58 -0800996class DuplicatingThread : public MixerThread {
997public:
998 DuplicatingThread(const sp<AudioFlinger>& audioFlinger, MixerThread* mainThread,
999 audio_io_handle_t id);
1000 virtual ~DuplicatingThread();
1001
1002 // Thread virtuals
1003 void addOutputTrack(MixerThread* thread);
1004 void removeOutputTrack(MixerThread* thread);
1005 uint32_t waitTimeMs() const { return mWaitTimeMs; }
1006protected:
1007 virtual uint32_t activeSleepTimeUs() const;
1008
1009private:
1010 bool outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks);
1011protected:
1012 // threadLoop snippets
1013 virtual void threadLoop_mix();
1014 virtual void threadLoop_sleepTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001015 virtual ssize_t threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08001016 virtual void threadLoop_standby();
1017 virtual void cacheParameters_l();
1018
1019private:
1020 // called from threadLoop, addOutputTrack, removeOutputTrack
1021 virtual void updateWaitTime_l();
1022protected:
1023 virtual void saveOutputTracks();
1024 virtual void clearOutputTracks();
1025private:
1026
1027 uint32_t mWaitTimeMs;
1028 SortedVector < sp<OutputTrack> > outputTracks;
1029 SortedVector < sp<OutputTrack> > mOutputTracks;
1030public:
1031 virtual bool hasFastMixer() const { return false; }
1032};
1033
1034
1035// record thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001036class RecordThread : public ThreadBase
Eric Laurent81784c32012-11-19 14:55:58 -08001037{
1038public:
1039
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001040 class RecordTrack;
1041 class ResamplerBufferProvider : public AudioBufferProvider
1042 // derives from AudioBufferProvider interface for use by resampler
1043 {
1044 public:
1045 ResamplerBufferProvider(RecordTrack* recordTrack) : mRecordTrack(recordTrack) { }
1046 virtual ~ResamplerBufferProvider() { }
1047 // AudioBufferProvider interface
1048 virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts);
1049 virtual void releaseBuffer(AudioBufferProvider::Buffer* buffer);
1050 private:
1051 RecordTrack * const mRecordTrack;
1052 };
1053
Eric Laurent81784c32012-11-19 14:55:58 -08001054#include "RecordTracks.h"
1055
1056 RecordThread(const sp<AudioFlinger>& audioFlinger,
1057 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08001058 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08001059 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08001060 audio_devices_t inDevice
1061#ifdef TEE_SINK
1062 , const sp<NBAIO_Sink>& teeSink
1063#endif
1064 );
Eric Laurent81784c32012-11-19 14:55:58 -08001065 virtual ~RecordThread();
1066
1067 // no addTrack_l ?
1068 void destroyTrack_l(const sp<RecordTrack>& track);
1069 void removeTrack_l(const sp<RecordTrack>& track);
1070
1071 void dumpInternals(int fd, const Vector<String16>& args);
1072 void dumpTracks(int fd, const Vector<String16>& args);
1073
1074 // Thread virtuals
1075 virtual bool threadLoop();
Eric Laurent81784c32012-11-19 14:55:58 -08001076
1077 // RefBase
1078 virtual void onFirstRef();
1079
1080 virtual status_t initCheck() const { return (mInput == NULL) ? NO_INIT : NO_ERROR; }
Glenn Kastene198c362013-08-13 09:13:36 -07001081
Glenn Kastenb880f5e2014-05-07 08:43:45 -07001082 virtual sp<MemoryDealer> readOnlyHeap() const { return mReadOnlyHeap; }
1083
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001084 virtual sp<IMemory> pipeMemory() const { return mPipeMemory; }
1085
Eric Laurent81784c32012-11-19 14:55:58 -08001086 sp<AudioFlinger::RecordThread::RecordTrack> createRecordTrack_l(
1087 const sp<AudioFlinger::Client>& client,
1088 uint32_t sampleRate,
1089 audio_format_t format,
1090 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001091 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001092 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001093 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001094 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07001095 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001096 pid_t tid,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001097 status_t *status /*non-NULL*/);
Eric Laurent81784c32012-11-19 14:55:58 -08001098
1099 status_t start(RecordTrack* recordTrack,
1100 AudioSystem::sync_event_t event,
1101 int triggerSession);
1102
1103 // ask the thread to stop the specified track, and
1104 // return true if the caller should then do it's part of the stopping process
Glenn Kastena8356f62013-07-25 14:37:52 -07001105 bool stop(RecordTrack* recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08001106
1107 void dump(int fd, const Vector<String16>& args);
1108 AudioStreamIn* clearInput();
1109 virtual audio_stream_t* stream() const;
1110
Eric Laurent81784c32012-11-19 14:55:58 -08001111
Eric Laurent10351942014-05-08 18:49:52 -07001112 virtual bool checkForNewParameter_l(const String8& keyValuePair,
1113 status_t& status);
1114 virtual void cacheParameters_l() {}
Eric Laurent81784c32012-11-19 14:55:58 -08001115 virtual String8 getParameters(const String8& keys);
Eric Laurent021cf962014-05-13 10:18:14 -07001116 virtual void audioConfigChanged(int event, int param = 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07001117 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
1118 audio_patch_handle_t *handle);
1119 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle);
Eric Laurent83b88082014-06-20 18:31:16 -07001120
1121 void addPatchRecord(const sp<PatchRecord>& record);
1122 void deletePatchRecord(const sp<PatchRecord>& record);
1123
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001124 void readInputParameters_l();
Glenn Kasten5f972c02014-01-13 09:59:31 -08001125 virtual uint32_t getInputFramesLost();
Eric Laurent81784c32012-11-19 14:55:58 -08001126
1127 virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
1128 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
1129 virtual uint32_t hasAudioSession(int sessionId) const;
1130
1131 // Return the set of unique session IDs across all tracks.
1132 // The keys are the session IDs, and the associated values are meaningless.
1133 // FIXME replace by Set [and implement Bag/Multiset for other uses].
1134 KeyedVector<int, bool> sessionIds() const;
1135
1136 virtual status_t setSyncEvent(const sp<SyncEvent>& event);
1137 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const;
1138
1139 static void syncStartEventCallback(const wp<SyncEvent>& event);
Eric Laurent81784c32012-11-19 14:55:58 -08001140
Glenn Kasten9b58f632013-07-16 11:37:48 -07001141 virtual size_t frameCount() const { return mFrameCount; }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001142 bool hasFastCapture() const { return mFastCapture != 0; }
Eric Laurent83b88082014-06-20 18:31:16 -07001143 virtual void getAudioPortConfig(struct audio_port_config *config);
Glenn Kasten9b58f632013-07-16 11:37:48 -07001144
Eric Laurent81784c32012-11-19 14:55:58 -08001145private:
Eric Laurent81784c32012-11-19 14:55:58 -08001146 // Enter standby if not already in standby, and set mStandby flag
Glenn Kasten93e471f2013-08-19 08:40:07 -07001147 void standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08001148
1149 // Call the HAL standby method unconditionally, and don't change mStandby flag
Glenn Kastene198c362013-08-13 09:13:36 -07001150 void inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08001151
1152 AudioStreamIn *mInput;
1153 SortedVector < sp<RecordTrack> > mTracks;
Glenn Kasten2b806402013-11-20 16:37:38 -08001154 // mActiveTracks has dual roles: it indicates the current active track(s), and
Eric Laurent81784c32012-11-19 14:55:58 -08001155 // is used together with mStartStopCond to indicate start()/stop() progress
Glenn Kasten2b806402013-11-20 16:37:38 -08001156 SortedVector< sp<RecordTrack> > mActiveTracks;
1157 // generation counter for mActiveTracks
1158 int mActiveTracksGen;
Eric Laurent81784c32012-11-19 14:55:58 -08001159 Condition mStartStopCond;
Glenn Kasten9b58f632013-07-16 11:37:48 -07001160
Glenn Kasten85948432013-08-19 12:09:05 -07001161 // resampler converts input at HAL Hz to output at AudioRecord client Hz
1162 int16_t *mRsmpInBuffer; // see new[] for details on the size
1163 size_t mRsmpInFrames; // size of resampler input in frames
1164 size_t mRsmpInFramesP2;// size rounded up to a power-of-2
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001165
1166 // rolling index that is never cleared
Glenn Kasten85948432013-08-19 12:09:05 -07001167 int32_t mRsmpInRear; // last filled frame + 1
Glenn Kasten85948432013-08-19 12:09:05 -07001168
Eric Laurent81784c32012-11-19 14:55:58 -08001169 // For dumpsys
1170 const sp<NBAIO_Sink> mTeeSink;
Glenn Kastenb880f5e2014-05-07 08:43:45 -07001171
1172 const sp<MemoryDealer> mReadOnlyHeap;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001173
1174 // one-time initialization, no locks required
1175 sp<FastCapture> mFastCapture; // non-0 if there is also a fast capture
1176 // FIXME audio watchdog thread
1177
1178 // contents are not guaranteed to be consistent, no locks required
1179 FastCaptureDumpState mFastCaptureDumpState;
1180#ifdef STATE_QUEUE_DUMP
1181 // FIXME StateQueue observer and mutator dump fields
1182#endif
1183 // FIXME audio watchdog dump
1184
1185 // accessible only within the threadLoop(), no locks required
1186 // mFastCapture->sq() // for mutating and pushing state
1187 int32_t mFastCaptureFutex; // for cold idle
1188
1189 // The HAL input source is treated as non-blocking,
1190 // but current implementation is blocking
1191 sp<NBAIO_Source> mInputSource;
1192 // The source for the normal capture thread to read from: mInputSource or mPipeSource
1193 sp<NBAIO_Source> mNormalSource;
1194 // If a fast capture is present, the non-blocking pipe sink written to by fast capture,
1195 // otherwise clear
1196 sp<NBAIO_Sink> mPipeSink;
1197 // If a fast capture is present, the non-blocking pipe source read by normal thread,
1198 // otherwise clear
1199 sp<NBAIO_Source> mPipeSource;
1200 // Depth of pipe from fast capture to normal thread and fast clients, always power of 2
1201 size_t mPipeFramesP2;
1202 // If a fast capture is present, the Pipe as IMemory, otherwise clear
1203 sp<IMemory> mPipeMemory;
1204
1205 static const size_t kFastCaptureLogSize = 4 * 1024;
1206 sp<NBLog::Writer> mFastCaptureNBLogWriter;
1207
1208 bool mFastTrackAvail; // true if fast track available
Eric Laurent81784c32012-11-19 14:55:58 -08001209};