blob: c265833895909bc43298470d330be48437eb0a63 [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; }
232 audio_io_handle_t id() const { return mId;}
233
234 // dynamic externally-visible
235 uint32_t sampleRate() const { return mSampleRate; }
Eric Laurent81784c32012-11-19 14:55:58 -0800236 audio_channel_mask_t channelMask() const { return mChannelMask; }
237 audio_format_t format() const { return mFormat; }
238 // Called by AudioFlinger::frameCount(audio_io_handle_t output) and effects,
Glenn Kasten9b58f632013-07-16 11:37:48 -0700239 // and returns the [normal mix] buffer's frame count.
240 virtual size_t frameCount() const = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800241 size_t frameSize() const { return mFrameSize; }
Eric Laurent81784c32012-11-19 14:55:58 -0800242
243 // Should be "virtual status_t requestExitAndWait()" and override same
244 // method in Thread, but Thread::requestExitAndWait() is not yet virtual.
245 void exit();
Eric Laurent10351942014-05-08 18:49:52 -0700246 virtual bool checkForNewParameter_l(const String8& keyValuePair,
247 status_t& status) = 0;
Eric Laurent81784c32012-11-19 14:55:58 -0800248 virtual status_t setParameters(const String8& keyValuePairs);
249 virtual String8 getParameters(const String8& keys) = 0;
Eric Laurent021cf962014-05-13 10:18:14 -0700250 virtual void audioConfigChanged(int event, int param = 0) = 0;
Eric Laurent10351942014-05-08 18:49:52 -0700251 // sendConfigEvent_l() must be called with ThreadBase::mLock held
252 // Can temporarily release the lock if waiting for a reply from
253 // processConfigEvents_l().
254 status_t sendConfigEvent_l(sp<ConfigEvent>& event);
Eric Laurent81784c32012-11-19 14:55:58 -0800255 void sendIoConfigEvent(int event, int param = 0);
256 void sendIoConfigEvent_l(int event, int param = 0);
257 void sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio);
Eric Laurent10351942014-05-08 18:49:52 -0700258 status_t sendSetParameterConfigEvent_l(const String8& keyValuePair);
Eric Laurent1c333e22014-05-20 10:48:17 -0700259 status_t sendCreateAudioPatchConfigEvent(const struct audio_patch *patch,
260 audio_patch_handle_t *handle);
261 status_t sendReleaseAudioPatchConfigEvent(audio_patch_handle_t handle);
Eric Laurent021cf962014-05-13 10:18:14 -0700262 void processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -0700263 virtual void cacheParameters_l() = 0;
Eric Laurent1c333e22014-05-20 10:48:17 -0700264 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
265 audio_patch_handle_t *handle) = 0;
266 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle) = 0;
267
Eric Laurent81784c32012-11-19 14:55:58 -0800268
269 // see note at declaration of mStandby, mOutDevice and mInDevice
270 bool standby() const { return mStandby; }
271 audio_devices_t outDevice() const { return mOutDevice; }
272 audio_devices_t inDevice() const { return mInDevice; }
273
274 virtual audio_stream_t* stream() const = 0;
275
276 sp<EffectHandle> createEffect_l(
277 const sp<AudioFlinger::Client>& client,
278 const sp<IEffectClient>& effectClient,
279 int32_t priority,
280 int sessionId,
281 effect_descriptor_t *desc,
282 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700283 status_t *status /*non-NULL*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800284 void disconnectEffect(const sp< EffectModule>& effect,
285 EffectHandle *handle,
286 bool unpinIfLast);
287
288 // return values for hasAudioSession (bit field)
289 enum effect_state {
290 EFFECT_SESSION = 0x1, // the audio session corresponds to at least one
291 // effect
292 TRACK_SESSION = 0x2 // the audio session corresponds to at least one
293 // track
294 };
295
296 // get effect chain corresponding to session Id.
297 sp<EffectChain> getEffectChain(int sessionId);
298 // same as getEffectChain() but must be called with ThreadBase mutex locked
299 sp<EffectChain> getEffectChain_l(int sessionId) const;
300 // add an effect chain to the chain list (mEffectChains)
301 virtual status_t addEffectChain_l(const sp<EffectChain>& chain) = 0;
302 // remove an effect chain from the chain list (mEffectChains)
303 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain) = 0;
304 // lock all effect chains Mutexes. Must be called before releasing the
305 // ThreadBase mutex before processing the mixer and effects. This guarantees the
306 // integrity of the chains during the process.
307 // Also sets the parameter 'effectChains' to current value of mEffectChains.
308 void lockEffectChains_l(Vector< sp<EffectChain> >& effectChains);
309 // unlock effect chains after process
310 void unlockEffectChains(const Vector< sp<EffectChain> >& effectChains);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800311 // get a copy of mEffectChains vector
312 Vector< sp<EffectChain> > getEffectChains_l() const { return mEffectChains; };
Eric Laurent81784c32012-11-19 14:55:58 -0800313 // set audio mode to all effect chains
314 void setMode(audio_mode_t mode);
315 // get effect module with corresponding ID on specified audio session
316 sp<AudioFlinger::EffectModule> getEffect(int sessionId, int effectId);
317 sp<AudioFlinger::EffectModule> getEffect_l(int sessionId, int effectId);
318 // add and effect module. Also creates the effect chain is none exists for
319 // the effects audio session
320 status_t addEffect_l(const sp< EffectModule>& effect);
321 // remove and effect module. Also removes the effect chain is this was the last
322 // effect
323 void removeEffect_l(const sp< EffectModule>& effect);
324 // detach all tracks connected to an auxiliary effect
Glenn Kasten0f11b512014-01-31 16:18:54 -0800325 virtual void detachAuxEffect_l(int effectId __unused) {}
Eric Laurent81784c32012-11-19 14:55:58 -0800326 // returns either EFFECT_SESSION if effects on this audio session exist in one
327 // chain, or TRACK_SESSION if tracks on this audio session exist, or both
328 virtual uint32_t hasAudioSession(int sessionId) const = 0;
329 // the value returned by default implementation is not important as the
330 // strategy is only meaningful for PlaybackThread which implements this method
Glenn Kasten0f11b512014-01-31 16:18:54 -0800331 virtual uint32_t getStrategyForSession_l(int sessionId __unused) { return 0; }
Eric Laurent81784c32012-11-19 14:55:58 -0800332
333 // suspend or restore effect according to the type of effect passed. a NULL
334 // type pointer means suspend all effects in the session
335 void setEffectSuspended(const effect_uuid_t *type,
336 bool suspend,
337 int sessionId = AUDIO_SESSION_OUTPUT_MIX);
338 // check if some effects must be suspended/restored when an effect is enabled
339 // or disabled
340 void checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
341 bool enabled,
342 int sessionId = AUDIO_SESSION_OUTPUT_MIX);
343 void checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
344 bool enabled,
345 int sessionId = AUDIO_SESSION_OUTPUT_MIX);
346
347 virtual status_t setSyncEvent(const sp<SyncEvent>& event) = 0;
348 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const = 0;
349
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700350 // Return a reference to a per-thread heap which can be used to allocate IMemory
351 // objects that will be read-only to client processes, read/write to mediaserver,
352 // and shared by all client processes of the thread.
353 // The heap is per-thread rather than common across all threads, because
354 // clients can't be trusted not to modify the offset of the IMemory they receive.
355 // If a thread does not have such a heap, this method returns 0.
356 virtual sp<MemoryDealer> readOnlyHeap() const { return 0; }
Eric Laurent81784c32012-11-19 14:55:58 -0800357
Glenn Kasten6181ffd2014-05-13 10:41:52 -0700358 virtual sp<IMemory> pipeMemory() const { return 0; }
359
Eric Laurent81784c32012-11-19 14:55:58 -0800360 mutable Mutex mLock;
361
362protected:
363
364 // entry describing an effect being suspended in mSuspendedSessions keyed vector
365 class SuspendedSessionDesc : public RefBase {
366 public:
367 SuspendedSessionDesc() : mRefCount(0) {}
368
369 int mRefCount; // number of active suspend requests
370 effect_uuid_t mType; // effect type UUID
371 };
372
Marco Nelissene14a5d62013-10-03 08:51:24 -0700373 void acquireWakeLock(int uid = -1);
374 void acquireWakeLock_l(int uid = -1);
Eric Laurent81784c32012-11-19 14:55:58 -0800375 void releaseWakeLock();
376 void releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800377 void updateWakeLockUids(const SortedVector<int> &uids);
378 void updateWakeLockUids_l(const SortedVector<int> &uids);
379 void getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800380 void setEffectSuspended_l(const effect_uuid_t *type,
381 bool suspend,
382 int sessionId);
383 // updated mSuspendedSessions when an effect suspended or restored
384 void updateSuspendedSessions_l(const effect_uuid_t *type,
385 bool suspend,
386 int sessionId);
387 // check if some effects must be suspended when an effect chain is added
388 void checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain);
389
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100390 String16 getWakeLockTag();
391
Eric Laurent81784c32012-11-19 14:55:58 -0800392 virtual void preExit() { }
393
394 friend class AudioFlinger; // for mEffectChains
395
396 const type_t mType;
397
398 // Used by parameters, config events, addTrack_l, exit
399 Condition mWaitWorkCV;
400
401 const sp<AudioFlinger> mAudioFlinger;
Glenn Kasten9b58f632013-07-16 11:37:48 -0700402
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800403 // updated by PlaybackThread::readOutputParameters_l() or
404 // RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800405 uint32_t mSampleRate;
406 size_t mFrameCount; // output HAL, direct output, record
Eric Laurent81784c32012-11-19 14:55:58 -0800407 audio_channel_mask_t mChannelMask;
Glenn Kastenf6ed4232013-07-16 11:16:27 -0700408 uint32_t mChannelCount;
Eric Laurent81784c32012-11-19 14:55:58 -0800409 size_t mFrameSize;
410 audio_format_t mFormat;
Glenn Kasten70949c42013-08-06 07:40:12 -0700411 size_t mBufferSize; // HAL buffer size for read() or write()
Eric Laurent81784c32012-11-19 14:55:58 -0800412
Eric Laurent10351942014-05-08 18:49:52 -0700413 Vector< sp<ConfigEvent> > mConfigEvents;
Eric Laurent81784c32012-11-19 14:55:58 -0800414
415 // These fields are written and read by thread itself without lock or barrier,
Glenn Kasten4944acb2013-08-19 08:39:20 -0700416 // and read by other threads without lock or barrier via standby(), outDevice()
Eric Laurent81784c32012-11-19 14:55:58 -0800417 // and inDevice().
418 // Because of the absence of a lock or barrier, any other thread that reads
419 // these fields must use the information in isolation, or be prepared to deal
420 // with possibility that it might be inconsistent with other information.
Glenn Kasten4944acb2013-08-19 08:39:20 -0700421 bool mStandby; // Whether thread is currently in standby.
Eric Laurent81784c32012-11-19 14:55:58 -0800422 audio_devices_t mOutDevice; // output device
423 audio_devices_t mInDevice; // input device
424 audio_source_t mAudioSource; // (see audio.h, audio_source_t)
425
426 const audio_io_handle_t mId;
427 Vector< sp<EffectChain> > mEffectChains;
428
429 static const int kNameLength = 16; // prctl(PR_SET_NAME) limit
430 char mName[kNameLength];
431 sp<IPowerManager> mPowerManager;
432 sp<IBinder> mWakeLockToken;
433 const sp<PMDeathRecipient> mDeathRecipient;
434 // list of suspended effects per session and per type. The first vector is
435 // keyed by session ID, the second by type UUID timeLow field
436 KeyedVector< int, KeyedVector< int, sp<SuspendedSessionDesc> > >
437 mSuspendedSessions;
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800438 static const size_t kLogSize = 4 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -0800439 sp<NBLog::Writer> mNBLogWriter;
Eric Laurent81784c32012-11-19 14:55:58 -0800440};
441
442// --- PlaybackThread ---
443class PlaybackThread : public ThreadBase {
444public:
445
446#include "PlaybackTracks.h"
447
448 enum mixer_state {
449 MIXER_IDLE, // no active tracks
450 MIXER_TRACKS_ENABLED, // at least one active track, but no track has any data ready
Eric Laurentbfb1b832013-01-07 09:53:42 -0800451 MIXER_TRACKS_READY, // at least one active track, and at least one track has data
452 MIXER_DRAIN_TRACK, // drain currently playing track
453 MIXER_DRAIN_ALL, // fully drain the hardware
Eric Laurent81784c32012-11-19 14:55:58 -0800454 // standby mode does not have an enum value
455 // suspend by audio policy manager is orthogonal to mixer state
456 };
457
Eric Laurentbfb1b832013-01-07 09:53:42 -0800458 // retry count before removing active track in case of underrun on offloaded thread:
459 // we need to make sure that AudioTrack client has enough time to send large buffers
460//FIXME may be more appropriate if expressed in time units. Need to revise how underrun is handled
461 // for offloaded tracks
462 static const int8_t kMaxTrackRetriesOffload = 20;
463
Eric Laurent81784c32012-11-19 14:55:58 -0800464 PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
465 audio_io_handle_t id, audio_devices_t device, type_t type);
466 virtual ~PlaybackThread();
467
468 void dump(int fd, const Vector<String16>& args);
469
470 // Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -0800471 virtual bool threadLoop();
472
473 // RefBase
474 virtual void onFirstRef();
475
476protected:
477 // Code snippets that were lifted up out of threadLoop()
478 virtual void threadLoop_mix() = 0;
479 virtual void threadLoop_sleepTime() = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800480 virtual ssize_t threadLoop_write();
481 virtual void threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -0800482 virtual void threadLoop_standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800483 virtual void threadLoop_exit();
Eric Laurent81784c32012-11-19 14:55:58 -0800484 virtual void threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
485
486 // prepareTracks_l reads and writes mActiveTracks, and returns
487 // the pending set of tracks to remove via Vector 'tracksToRemove'. The caller
488 // is responsible for clearing or destroying this Vector later on, when it
489 // is safe to do so. That will drop the final ref count and destroy the tracks.
490 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove) = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800491 void removeTracks_l(const Vector< sp<Track> >& tracksToRemove);
492
493 void writeCallback();
Eric Laurent3b4529e2013-09-05 18:09:19 -0700494 void resetWriteBlocked(uint32_t sequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800495 void drainCallback();
Eric Laurent3b4529e2013-09-05 18:09:19 -0700496 void resetDraining(uint32_t sequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800497
498 static int asyncCallback(stream_callback_event_t event, void *param, void *cookie);
499
500 virtual bool waitingAsyncCallback();
501 virtual bool waitingAsyncCallback_l();
502 virtual bool shouldStandby_l();
Haynes Mathew George4c6a4332014-01-15 12:31:39 -0800503 virtual void onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800504
505 // ThreadBase virtuals
506 virtual void preExit();
507
508public:
509
510 virtual status_t initCheck() const { return (mOutput == NULL) ? NO_INIT : NO_ERROR; }
511
512 // return estimated latency in milliseconds, as reported by HAL
513 uint32_t latency() const;
514 // same, but lock must already be held
515 uint32_t latency_l() const;
516
517 void setMasterVolume(float value);
518 void setMasterMute(bool muted);
519
520 void setStreamVolume(audio_stream_type_t stream, float value);
521 void setStreamMute(audio_stream_type_t stream, bool muted);
522
523 float streamVolume(audio_stream_type_t stream) const;
524
525 sp<Track> createTrack_l(
526 const sp<AudioFlinger::Client>& client,
527 audio_stream_type_t streamType,
528 uint32_t sampleRate,
529 audio_format_t format,
530 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -0800531 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -0800532 const sp<IMemory>& sharedBuffer,
533 int sessionId,
534 IAudioFlinger::track_flags_t *flags,
535 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800536 int uid,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700537 status_t *status /*non-NULL*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800538
539 AudioStreamOut* getOutput() const;
540 AudioStreamOut* clearOutput();
541 virtual audio_stream_t* stream() const;
542
543 // a very large number of suspend() will eventually wraparound, but unlikely
544 void suspend() { (void) android_atomic_inc(&mSuspended); }
545 void restore()
546 {
547 // if restore() is done without suspend(), get back into
548 // range so that the next suspend() will operate correctly
549 if (android_atomic_dec(&mSuspended) <= 0) {
550 android_atomic_release_store(0, &mSuspended);
551 }
552 }
553 bool isSuspended() const
554 { return android_atomic_acquire_load(&mSuspended) > 0; }
555
556 virtual String8 getParameters(const String8& keys);
Eric Laurent021cf962014-05-13 10:18:14 -0700557 virtual void audioConfigChanged(int event, int param = 0);
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000558 status_t getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames);
Andy Hung010a1a12014-03-13 13:57:33 -0700559 // FIXME rename mixBuffer() to sinkBuffer() and remove int16_t* dependency.
560 // Consider also removing and passing an explicit mMainBuffer initialization
561 // parameter to AF::PlaybackThread::Track::Track().
562 int16_t *mixBuffer() const {
563 return reinterpret_cast<int16_t *>(mSinkBuffer); };
Eric Laurent81784c32012-11-19 14:55:58 -0800564
565 virtual void detachAuxEffect_l(int effectId);
566 status_t attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track> track,
567 int EffectId);
568 status_t attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track> track,
569 int EffectId);
570
571 virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
572 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
573 virtual uint32_t hasAudioSession(int sessionId) const;
574 virtual uint32_t getStrategyForSession_l(int sessionId);
575
576
577 virtual status_t setSyncEvent(const sp<SyncEvent>& event);
578 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const;
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700579
580 // called with AudioFlinger lock held
Eric Laurent81784c32012-11-19 14:55:58 -0800581 void invalidateTracks(audio_stream_type_t streamType);
582
Glenn Kasten9b58f632013-07-16 11:37:48 -0700583 virtual size_t frameCount() const { return mNormalFrameCount; }
584
585 // Return's the HAL's frame count i.e. fast mixer buffer size.
586 size_t frameCountHAL() const { return mFrameCount; }
Eric Laurent81784c32012-11-19 14:55:58 -0800587
Eric Laurentaccc1472013-09-20 09:36:34 -0700588 status_t getTimestamp_l(AudioTimestamp& timestamp);
589
Eric Laurent81784c32012-11-19 14:55:58 -0800590protected:
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800591 // updated by readOutputParameters_l()
Glenn Kasten9b58f632013-07-16 11:37:48 -0700592 size_t mNormalFrameCount; // normal mixer and effects
593
Andy Hung010a1a12014-03-13 13:57:33 -0700594 void* mSinkBuffer; // frame size aligned sink buffer
Eric Laurent81784c32012-11-19 14:55:58 -0800595
Andy Hung98ef9782014-03-04 14:46:50 -0800596 // TODO:
597 // Rearrange the buffer info into a struct/class with
598 // clear, copy, construction, destruction methods.
599 //
600 // mSinkBuffer also has associated with it:
601 //
602 // mSinkBufferSize: Sink Buffer Size
603 // mFormat: Sink Buffer Format
604
Andy Hung69aed5f2014-02-25 17:24:40 -0800605 // Mixer Buffer (mMixerBuffer*)
606 //
607 // In the case of floating point or multichannel data, which is not in the
608 // sink format, it is required to accumulate in a higher precision or greater channel count
609 // buffer before downmixing or data conversion to the sink buffer.
610
611 // Set to "true" to enable the Mixer Buffer otherwise mixer output goes to sink buffer.
612 bool mMixerBufferEnabled;
613
614 // Storage, 32 byte aligned (may make this alignment a requirement later).
615 // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
616 void* mMixerBuffer;
617
618 // Size of mMixerBuffer in bytes: mNormalFrameCount * #channels * sampsize.
619 size_t mMixerBufferSize;
620
621 // The audio format of mMixerBuffer. Set to AUDIO_FORMAT_PCM_(FLOAT|16_BIT) only.
622 audio_format_t mMixerBufferFormat;
623
624 // An internal flag set to true by MixerThread::prepareTracks_l()
625 // when mMixerBuffer contains valid data after mixing.
626 bool mMixerBufferValid;
627
Andy Hung98ef9782014-03-04 14:46:50 -0800628 // Effects Buffer (mEffectsBuffer*)
629 //
630 // In the case of effects data, which is not in the sink format,
631 // it is required to accumulate in a different buffer before data conversion
632 // to the sink buffer.
633
634 // Set to "true" to enable the Effects Buffer otherwise effects output goes to sink buffer.
635 bool mEffectBufferEnabled;
636
637 // Storage, 32 byte aligned (may make this alignment a requirement later).
638 // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
639 void* mEffectBuffer;
640
641 // Size of mEffectsBuffer in bytes: mNormalFrameCount * #channels * sampsize.
642 size_t mEffectBufferSize;
643
644 // The audio format of mEffectsBuffer. Set to AUDIO_FORMAT_PCM_16_BIT only.
645 audio_format_t mEffectBufferFormat;
646
647 // An internal flag set to true by MixerThread::prepareTracks_l()
648 // when mEffectsBuffer contains valid data after mixing.
649 //
650 // When this is set, all mixer data is routed into the effects buffer
651 // for any processing (including output processing).
652 bool mEffectBufferValid;
653
Eric Laurent81784c32012-11-19 14:55:58 -0800654 // suspend count, > 0 means suspended. While suspended, the thread continues to pull from
655 // tracks and mix, but doesn't write to HAL. A2DP and SCO HAL implementations can't handle
656 // concurrent use of both of them, so Audio Policy Service suspends one of the threads to
657 // workaround that restriction.
658 // 'volatile' means accessed via atomic operations and no lock.
659 volatile int32_t mSuspended;
660
661 // FIXME overflows every 6+ hours at 44.1 kHz stereo 16-bit samples
662 // mFramesWritten would be better, or 64-bit even better
663 size_t mBytesWritten;
664private:
665 // mMasterMute is in both PlaybackThread and in AudioFlinger. When a
666 // PlaybackThread needs to find out if master-muted, it checks it's local
667 // copy rather than the one in AudioFlinger. This optimization saves a lock.
668 bool mMasterMute;
669 void setMasterMute_l(bool muted) { mMasterMute = muted; }
670protected:
671 SortedVector< wp<Track> > mActiveTracks; // FIXME check if this could be sp<>
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800672 SortedVector<int> mWakeLockUids;
673 int mActiveTracksGeneration;
Eric Laurentfd477972013-10-25 18:10:40 -0700674 wp<Track> mLatestActiveTrack; // latest track added to mActiveTracks
Eric Laurent81784c32012-11-19 14:55:58 -0800675
676 // Allocate a track name for a given channel mask.
677 // Returns name >= 0 if successful, -1 on failure.
Andy Hunge8a1ced2014-05-09 15:02:21 -0700678 virtual int getTrackName_l(audio_channel_mask_t channelMask,
679 audio_format_t format, int sessionId) = 0;
Eric Laurent81784c32012-11-19 14:55:58 -0800680 virtual void deleteTrackName_l(int name) = 0;
681
682 // Time to sleep between cycles when:
683 virtual uint32_t activeSleepTimeUs() const; // mixer state MIXER_TRACKS_ENABLED
684 virtual uint32_t idleSleepTimeUs() const = 0; // mixer state MIXER_IDLE
685 virtual uint32_t suspendSleepTimeUs() const = 0; // audio policy manager suspended us
686 // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write()
687 // No sleep in standby mode; waits on a condition
688
689 // Code snippets that are temporarily lifted up out of threadLoop() until the merge
690 void checkSilentMode_l();
691
692 // Non-trivial for DUPLICATING only
693 virtual void saveOutputTracks() { }
694 virtual void clearOutputTracks() { }
695
696 // Cache various calculated values, at threadLoop() entry and after a parameter change
697 virtual void cacheParameters_l();
698
699 virtual uint32_t correctLatency_l(uint32_t latency) const;
700
Eric Laurent1c333e22014-05-20 10:48:17 -0700701 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
702 audio_patch_handle_t *handle);
703 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle);
704
Eric Laurent81784c32012-11-19 14:55:58 -0800705private:
706
707 friend class AudioFlinger; // for numerous
708
Eric Laurent81784c32012-11-19 14:55:58 -0800709 PlaybackThread& operator = (const PlaybackThread&);
710
711 status_t addTrack_l(const sp<Track>& track);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800712 bool destroyTrack_l(const sp<Track>& track);
Eric Laurent81784c32012-11-19 14:55:58 -0800713 void removeTrack_l(const sp<Track>& track);
Eric Laurentede6c3b2013-09-19 14:37:46 -0700714 void broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800715
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800716 void readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800717
718 virtual void dumpInternals(int fd, const Vector<String16>& args);
719 void dumpTracks(int fd, const Vector<String16>& args);
720
721 SortedVector< sp<Track> > mTracks;
722 // mStreamTypes[] uses 1 additional stream type internally for the OutputTrack used by
723 // DuplicatingThread
724 stream_type_t mStreamTypes[AUDIO_STREAM_CNT + 1];
725 AudioStreamOut *mOutput;
726
727 float mMasterVolume;
728 nsecs_t mLastWriteTime;
729 int mNumWrites;
730 int mNumDelayedWrites;
731 bool mInWrite;
732
733 // FIXME rename these former local variables of threadLoop to standard "m" names
734 nsecs_t standbyTime;
Andy Hung25c2dac2014-02-27 14:56:00 -0800735 size_t mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -0800736
737 // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l()
738 uint32_t activeSleepTime;
739 uint32_t idleSleepTime;
740
741 uint32_t sleepTime;
742
743 // mixer status returned by prepareTracks_l()
744 mixer_state mMixerStatus; // current cycle
745 // previous cycle when in prepareTracks_l()
746 mixer_state mMixerStatusIgnoringFastTracks;
747 // FIXME or a separate ready state per track
748
749 // FIXME move these declarations into the specific sub-class that needs them
750 // MIXER only
751 uint32_t sleepTimeShift;
752
753 // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value
754 nsecs_t standbyDelay;
755
756 // MIXER only
757 nsecs_t maxPeriod;
758
759 // DUPLICATING only
760 uint32_t writeFrames;
761
Eric Laurentbfb1b832013-01-07 09:53:42 -0800762 size_t mBytesRemaining;
763 size_t mCurrentWriteLength;
764 bool mUseAsyncWrite;
Eric Laurent3b4529e2013-09-05 18:09:19 -0700765 // mWriteAckSequence contains current write sequence on bits 31-1. The write sequence is
766 // incremented each time a write(), a flush() or a standby() occurs.
767 // Bit 0 is set when a write blocks and indicates a callback is expected.
768 // Bit 0 is reset by the async callback thread calling resetWriteBlocked(). Out of sequence
769 // callbacks are ignored.
770 uint32_t mWriteAckSequence;
771 // mDrainSequence contains current drain sequence on bits 31-1. The drain sequence is
772 // incremented each time a drain is requested or a flush() or standby() occurs.
773 // Bit 0 is set when the drain() command is called at the HAL and indicates a callback is
774 // expected.
775 // Bit 0 is reset by the async callback thread calling resetDraining(). Out of sequence
776 // callbacks are ignored.
777 uint32_t mDrainSequence;
Eric Laurentede6c3b2013-09-19 14:37:46 -0700778 // A condition that must be evaluated by prepareTrack_l() has changed and we must not wait
779 // for async write callback in the thread loop before evaluating it
Eric Laurentbfb1b832013-01-07 09:53:42 -0800780 bool mSignalPending;
781 sp<AsyncCallbackThread> mCallbackThread;
782
Eric Laurent81784c32012-11-19 14:55:58 -0800783private:
784 // The HAL output sink is treated as non-blocking, but current implementation is blocking
785 sp<NBAIO_Sink> mOutputSink;
786 // If a fast mixer is present, the blocking pipe sink, otherwise clear
787 sp<NBAIO_Sink> mPipeSink;
788 // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink
789 sp<NBAIO_Sink> mNormalSink;
Glenn Kasten46909e72013-02-26 09:20:22 -0800790#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -0800791 // For dumpsys
792 sp<NBAIO_Sink> mTeeSink;
793 sp<NBAIO_Source> mTeeSource;
Glenn Kasten46909e72013-02-26 09:20:22 -0800794#endif
Eric Laurent81784c32012-11-19 14:55:58 -0800795 uint32_t mScreenState; // cached copy of gScreenState
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800796 static const size_t kFastMixerLogSize = 4 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -0800797 sp<NBLog::Writer> mFastMixerNBLogWriter;
Eric Laurent81784c32012-11-19 14:55:58 -0800798public:
799 virtual bool hasFastMixer() const = 0;
Glenn Kasten0f11b512014-01-31 16:18:54 -0800800 virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -0800801 { FastTrackUnderruns dummy; return dummy; }
802
803protected:
804 // accessed by both binder threads and within threadLoop(), lock on mutex needed
805 unsigned mFastTrackAvailMask; // bit i set if fast track [i] is available
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700806
807private:
808 // timestamp latch:
809 // D input is written by threadLoop_write while mutex is unlocked, and read while locked
810 // Q output is written while locked, and read while locked
811 struct {
812 AudioTimestamp mTimestamp;
813 uint32_t mUnpresentedFrames;
814 } mLatchD, mLatchQ;
815 bool mLatchDValid; // true means mLatchD is valid, and clock it into latch at next opportunity
816 bool mLatchQValid; // true means mLatchQ is valid
Eric Laurent81784c32012-11-19 14:55:58 -0800817};
818
819class MixerThread : public PlaybackThread {
820public:
821 MixerThread(const sp<AudioFlinger>& audioFlinger,
822 AudioStreamOut* output,
823 audio_io_handle_t id,
824 audio_devices_t device,
825 type_t type = MIXER);
826 virtual ~MixerThread();
827
828 // Thread virtuals
829
Eric Laurent10351942014-05-08 18:49:52 -0700830 virtual bool checkForNewParameter_l(const String8& keyValuePair,
831 status_t& status);
Eric Laurent81784c32012-11-19 14:55:58 -0800832 virtual void dumpInternals(int fd, const Vector<String16>& args);
833
834protected:
835 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
Andy Hunge8a1ced2014-05-09 15:02:21 -0700836 virtual int getTrackName_l(audio_channel_mask_t channelMask,
837 audio_format_t format, int sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800838 virtual void deleteTrackName_l(int name);
839 virtual uint32_t idleSleepTimeUs() const;
840 virtual uint32_t suspendSleepTimeUs() const;
841 virtual void cacheParameters_l();
842
843 // threadLoop snippets
Eric Laurentbfb1b832013-01-07 09:53:42 -0800844 virtual ssize_t threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -0800845 virtual void threadLoop_standby();
846 virtual void threadLoop_mix();
847 virtual void threadLoop_sleepTime();
848 virtual void threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
849 virtual uint32_t correctLatency_l(uint32_t latency) const;
850
851 AudioMixer* mAudioMixer; // normal mixer
852private:
853 // one-time initialization, no locks required
Glenn Kasten4d23ca32014-05-13 10:39:51 -0700854 sp<FastMixer> mFastMixer; // non-0 if there is also a fast mixer
Eric Laurent81784c32012-11-19 14:55:58 -0800855 sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread
856
857 // contents are not guaranteed to be consistent, no locks required
858 FastMixerDumpState mFastMixerDumpState;
859#ifdef STATE_QUEUE_DUMP
860 StateQueueObserverDump mStateQueueObserverDump;
861 StateQueueMutatorDump mStateQueueMutatorDump;
862#endif
863 AudioWatchdogDump mAudioWatchdogDump;
864
865 // accessible only within the threadLoop(), no locks required
866 // mFastMixer->sq() // for mutating and pushing state
867 int32_t mFastMixerFutex; // for cold idle
868
869public:
Glenn Kasten4d23ca32014-05-13 10:39:51 -0700870 virtual bool hasFastMixer() const { return mFastMixer != 0; }
Eric Laurent81784c32012-11-19 14:55:58 -0800871 virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const {
872 ALOG_ASSERT(fastIndex < FastMixerState::kMaxFastTracks);
873 return mFastMixerDumpState.mTracks[fastIndex].mUnderruns;
874 }
875};
876
877class DirectOutputThread : public PlaybackThread {
878public:
879
880 DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
881 audio_io_handle_t id, audio_devices_t device);
882 virtual ~DirectOutputThread();
883
884 // Thread virtuals
885
Eric Laurent10351942014-05-08 18:49:52 -0700886 virtual bool checkForNewParameter_l(const String8& keyValuePair,
887 status_t& status);
Eric Laurent81784c32012-11-19 14:55:58 -0800888
889protected:
Andy Hunge8a1ced2014-05-09 15:02:21 -0700890 virtual int getTrackName_l(audio_channel_mask_t channelMask,
891 audio_format_t format, int sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800892 virtual void deleteTrackName_l(int name);
893 virtual uint32_t activeSleepTimeUs() const;
894 virtual uint32_t idleSleepTimeUs() const;
895 virtual uint32_t suspendSleepTimeUs() const;
896 virtual void cacheParameters_l();
897
898 // threadLoop snippets
899 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
900 virtual void threadLoop_mix();
901 virtual void threadLoop_sleepTime();
902
Eric Laurent81784c32012-11-19 14:55:58 -0800903 // volumes last sent to audio HAL with stream->set_volume()
904 float mLeftVolFloat;
905 float mRightVolFloat;
906
Eric Laurentbfb1b832013-01-07 09:53:42 -0800907 DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
908 audio_io_handle_t id, uint32_t device, ThreadBase::type_t type);
909 void processVolume_l(Track *track, bool lastTrack);
910
Eric Laurent81784c32012-11-19 14:55:58 -0800911 // prepareTracks_l() tells threadLoop_mix() the name of the single active track
912 sp<Track> mActiveTrack;
913public:
914 virtual bool hasFastMixer() const { return false; }
915};
916
Eric Laurentbfb1b832013-01-07 09:53:42 -0800917class OffloadThread : public DirectOutputThread {
918public:
919
920 OffloadThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
921 audio_io_handle_t id, uint32_t device);
Eric Laurent6a51d7e2013-10-17 18:59:26 -0700922 virtual ~OffloadThread() {};
Eric Laurentbfb1b832013-01-07 09:53:42 -0800923
924protected:
925 // threadLoop snippets
926 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
927 virtual void threadLoop_exit();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800928
929 virtual bool waitingAsyncCallback();
930 virtual bool waitingAsyncCallback_l();
931 virtual bool shouldStandby_l();
Haynes Mathew George4c6a4332014-01-15 12:31:39 -0800932 virtual void onAddNewTrack_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800933
934private:
935 void flushHw_l();
936
937private:
938 bool mHwPaused;
939 bool mFlushPending;
940 size_t mPausedWriteLength; // length in bytes of write interrupted by pause
941 size_t mPausedBytesRemaining; // bytes still waiting in mixbuffer after resume
Eric Laurentd7e59222013-11-15 12:02:28 -0800942 wp<Track> mPreviousTrack; // used to detect track switch
Eric Laurentbfb1b832013-01-07 09:53:42 -0800943};
944
945class AsyncCallbackThread : public Thread {
946public:
947
Eric Laurent4de95592013-09-26 15:28:21 -0700948 AsyncCallbackThread(const wp<PlaybackThread>& playbackThread);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800949
950 virtual ~AsyncCallbackThread();
951
952 // Thread virtuals
953 virtual bool threadLoop();
954
955 // RefBase
956 virtual void onFirstRef();
957
958 void exit();
Eric Laurent3b4529e2013-09-05 18:09:19 -0700959 void setWriteBlocked(uint32_t sequence);
960 void resetWriteBlocked();
961 void setDraining(uint32_t sequence);
962 void resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800963
964private:
Eric Laurent4de95592013-09-26 15:28:21 -0700965 const wp<PlaybackThread> mPlaybackThread;
Eric Laurent3b4529e2013-09-05 18:09:19 -0700966 // mWriteAckSequence corresponds to the last write sequence passed by the offload thread via
967 // setWriteBlocked(). The sequence is shifted one bit to the left and the lsb is used
968 // to indicate that the callback has been received via resetWriteBlocked()
Eric Laurent4de95592013-09-26 15:28:21 -0700969 uint32_t mWriteAckSequence;
Eric Laurent3b4529e2013-09-05 18:09:19 -0700970 // mDrainSequence corresponds to the last drain sequence passed by the offload thread via
971 // setDraining(). The sequence is shifted one bit to the left and the lsb is used
972 // to indicate that the callback has been received via resetDraining()
Eric Laurent4de95592013-09-26 15:28:21 -0700973 uint32_t mDrainSequence;
974 Condition mWaitWorkCV;
975 Mutex mLock;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800976};
977
Eric Laurent81784c32012-11-19 14:55:58 -0800978class DuplicatingThread : public MixerThread {
979public:
980 DuplicatingThread(const sp<AudioFlinger>& audioFlinger, MixerThread* mainThread,
981 audio_io_handle_t id);
982 virtual ~DuplicatingThread();
983
984 // Thread virtuals
985 void addOutputTrack(MixerThread* thread);
986 void removeOutputTrack(MixerThread* thread);
987 uint32_t waitTimeMs() const { return mWaitTimeMs; }
988protected:
989 virtual uint32_t activeSleepTimeUs() const;
990
991private:
992 bool outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks);
993protected:
994 // threadLoop snippets
995 virtual void threadLoop_mix();
996 virtual void threadLoop_sleepTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800997 virtual ssize_t threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -0800998 virtual void threadLoop_standby();
999 virtual void cacheParameters_l();
1000
1001private:
1002 // called from threadLoop, addOutputTrack, removeOutputTrack
1003 virtual void updateWaitTime_l();
1004protected:
1005 virtual void saveOutputTracks();
1006 virtual void clearOutputTracks();
1007private:
1008
1009 uint32_t mWaitTimeMs;
1010 SortedVector < sp<OutputTrack> > outputTracks;
1011 SortedVector < sp<OutputTrack> > mOutputTracks;
1012public:
1013 virtual bool hasFastMixer() const { return false; }
1014};
1015
1016
1017// record thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001018class RecordThread : public ThreadBase
Eric Laurent81784c32012-11-19 14:55:58 -08001019{
1020public:
1021
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001022 class RecordTrack;
1023 class ResamplerBufferProvider : public AudioBufferProvider
1024 // derives from AudioBufferProvider interface for use by resampler
1025 {
1026 public:
1027 ResamplerBufferProvider(RecordTrack* recordTrack) : mRecordTrack(recordTrack) { }
1028 virtual ~ResamplerBufferProvider() { }
1029 // AudioBufferProvider interface
1030 virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts);
1031 virtual void releaseBuffer(AudioBufferProvider::Buffer* buffer);
1032 private:
1033 RecordTrack * const mRecordTrack;
1034 };
1035
Eric Laurent81784c32012-11-19 14:55:58 -08001036#include "RecordTracks.h"
1037
1038 RecordThread(const sp<AudioFlinger>& audioFlinger,
1039 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08001040 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08001041 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08001042 audio_devices_t inDevice
1043#ifdef TEE_SINK
1044 , const sp<NBAIO_Sink>& teeSink
1045#endif
1046 );
Eric Laurent81784c32012-11-19 14:55:58 -08001047 virtual ~RecordThread();
1048
1049 // no addTrack_l ?
1050 void destroyTrack_l(const sp<RecordTrack>& track);
1051 void removeTrack_l(const sp<RecordTrack>& track);
1052
1053 void dumpInternals(int fd, const Vector<String16>& args);
1054 void dumpTracks(int fd, const Vector<String16>& args);
1055
1056 // Thread virtuals
1057 virtual bool threadLoop();
Eric Laurent81784c32012-11-19 14:55:58 -08001058
1059 // RefBase
1060 virtual void onFirstRef();
1061
1062 virtual status_t initCheck() const { return (mInput == NULL) ? NO_INIT : NO_ERROR; }
Glenn Kastene198c362013-08-13 09:13:36 -07001063
Glenn Kastenb880f5e2014-05-07 08:43:45 -07001064 virtual sp<MemoryDealer> readOnlyHeap() const { return mReadOnlyHeap; }
1065
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001066 virtual sp<IMemory> pipeMemory() const { return mPipeMemory; }
1067
Eric Laurent81784c32012-11-19 14:55:58 -08001068 sp<AudioFlinger::RecordThread::RecordTrack> createRecordTrack_l(
1069 const sp<AudioFlinger::Client>& client,
1070 uint32_t sampleRate,
1071 audio_format_t format,
1072 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001073 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001074 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001075 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001076 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07001077 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001078 pid_t tid,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001079 status_t *status /*non-NULL*/);
Eric Laurent81784c32012-11-19 14:55:58 -08001080
1081 status_t start(RecordTrack* recordTrack,
1082 AudioSystem::sync_event_t event,
1083 int triggerSession);
1084
1085 // ask the thread to stop the specified track, and
1086 // return true if the caller should then do it's part of the stopping process
Glenn Kastena8356f62013-07-25 14:37:52 -07001087 bool stop(RecordTrack* recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08001088
1089 void dump(int fd, const Vector<String16>& args);
1090 AudioStreamIn* clearInput();
1091 virtual audio_stream_t* stream() const;
1092
Eric Laurent81784c32012-11-19 14:55:58 -08001093
Eric Laurent10351942014-05-08 18:49:52 -07001094 virtual bool checkForNewParameter_l(const String8& keyValuePair,
1095 status_t& status);
1096 virtual void cacheParameters_l() {}
Eric Laurent81784c32012-11-19 14:55:58 -08001097 virtual String8 getParameters(const String8& keys);
Eric Laurent021cf962014-05-13 10:18:14 -07001098 virtual void audioConfigChanged(int event, int param = 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07001099 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
1100 audio_patch_handle_t *handle);
1101 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle);
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001102 void readInputParameters_l();
Glenn Kasten5f972c02014-01-13 09:59:31 -08001103 virtual uint32_t getInputFramesLost();
Eric Laurent81784c32012-11-19 14:55:58 -08001104
1105 virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
1106 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
1107 virtual uint32_t hasAudioSession(int sessionId) const;
1108
1109 // Return the set of unique session IDs across all tracks.
1110 // The keys are the session IDs, and the associated values are meaningless.
1111 // FIXME replace by Set [and implement Bag/Multiset for other uses].
1112 KeyedVector<int, bool> sessionIds() const;
1113
1114 virtual status_t setSyncEvent(const sp<SyncEvent>& event);
1115 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const;
1116
1117 static void syncStartEventCallback(const wp<SyncEvent>& event);
Eric Laurent81784c32012-11-19 14:55:58 -08001118
Glenn Kasten9b58f632013-07-16 11:37:48 -07001119 virtual size_t frameCount() const { return mFrameCount; }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001120 bool hasFastCapture() const { return mFastCapture != 0; }
Glenn Kasten9b58f632013-07-16 11:37:48 -07001121
Eric Laurent81784c32012-11-19 14:55:58 -08001122private:
Eric Laurent81784c32012-11-19 14:55:58 -08001123 // Enter standby if not already in standby, and set mStandby flag
Glenn Kasten93e471f2013-08-19 08:40:07 -07001124 void standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08001125
1126 // Call the HAL standby method unconditionally, and don't change mStandby flag
Glenn Kastene198c362013-08-13 09:13:36 -07001127 void inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08001128
1129 AudioStreamIn *mInput;
1130 SortedVector < sp<RecordTrack> > mTracks;
Glenn Kasten2b806402013-11-20 16:37:38 -08001131 // mActiveTracks has dual roles: it indicates the current active track(s), and
Eric Laurent81784c32012-11-19 14:55:58 -08001132 // is used together with mStartStopCond to indicate start()/stop() progress
Glenn Kasten2b806402013-11-20 16:37:38 -08001133 SortedVector< sp<RecordTrack> > mActiveTracks;
1134 // generation counter for mActiveTracks
1135 int mActiveTracksGen;
Eric Laurent81784c32012-11-19 14:55:58 -08001136 Condition mStartStopCond;
Glenn Kasten9b58f632013-07-16 11:37:48 -07001137
Glenn Kasten85948432013-08-19 12:09:05 -07001138 // resampler converts input at HAL Hz to output at AudioRecord client Hz
1139 int16_t *mRsmpInBuffer; // see new[] for details on the size
1140 size_t mRsmpInFrames; // size of resampler input in frames
1141 size_t mRsmpInFramesP2;// size rounded up to a power-of-2
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001142
1143 // rolling index that is never cleared
Glenn Kasten85948432013-08-19 12:09:05 -07001144 int32_t mRsmpInRear; // last filled frame + 1
Glenn Kasten85948432013-08-19 12:09:05 -07001145
Eric Laurent81784c32012-11-19 14:55:58 -08001146 // For dumpsys
1147 const sp<NBAIO_Sink> mTeeSink;
Glenn Kastenb880f5e2014-05-07 08:43:45 -07001148
1149 const sp<MemoryDealer> mReadOnlyHeap;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001150
1151 // one-time initialization, no locks required
1152 sp<FastCapture> mFastCapture; // non-0 if there is also a fast capture
1153 // FIXME audio watchdog thread
1154
1155 // contents are not guaranteed to be consistent, no locks required
1156 FastCaptureDumpState mFastCaptureDumpState;
1157#ifdef STATE_QUEUE_DUMP
1158 // FIXME StateQueue observer and mutator dump fields
1159#endif
1160 // FIXME audio watchdog dump
1161
1162 // accessible only within the threadLoop(), no locks required
1163 // mFastCapture->sq() // for mutating and pushing state
1164 int32_t mFastCaptureFutex; // for cold idle
1165
1166 // The HAL input source is treated as non-blocking,
1167 // but current implementation is blocking
1168 sp<NBAIO_Source> mInputSource;
1169 // The source for the normal capture thread to read from: mInputSource or mPipeSource
1170 sp<NBAIO_Source> mNormalSource;
1171 // If a fast capture is present, the non-blocking pipe sink written to by fast capture,
1172 // otherwise clear
1173 sp<NBAIO_Sink> mPipeSink;
1174 // If a fast capture is present, the non-blocking pipe source read by normal thread,
1175 // otherwise clear
1176 sp<NBAIO_Source> mPipeSource;
1177 // Depth of pipe from fast capture to normal thread and fast clients, always power of 2
1178 size_t mPipeFramesP2;
1179 // If a fast capture is present, the Pipe as IMemory, otherwise clear
1180 sp<IMemory> mPipeMemory;
1181
1182 static const size_t kFastCaptureLogSize = 4 * 1024;
1183 sp<NBLog::Writer> mFastCaptureNBLogWriter;
1184
1185 bool mFastTrackAvail; // true if fast track available
Eric Laurent81784c32012-11-19 14:55:58 -08001186};