blob: 4397cec3b27142df7eac5f0920d58c1c054c4d07 [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
Glenn Kasten97b7b752014-09-28 13:04:24 -070035 static const char *threadTypeToString(type_t type);
36
Eric Laurent81784c32012-11-19 14:55:58 -080037 ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
38 audio_devices_t outDevice, audio_devices_t inDevice, type_t type);
39 virtual ~ThreadBase();
40
Glenn Kastencf04c2c2013-08-06 07:41:16 -070041 virtual status_t readyToRun();
42
Eric Laurent81784c32012-11-19 14:55:58 -080043 void dumpBase(int fd, const Vector<String16>& args);
44 void dumpEffectChains(int fd, const Vector<String16>& args);
45
46 void clearPowerManager();
47
48 // base for record and playback
49 enum {
50 CFG_EVENT_IO,
Eric Laurent10351942014-05-08 18:49:52 -070051 CFG_EVENT_PRIO,
52 CFG_EVENT_SET_PARAMETER,
Eric Laurent1c333e22014-05-20 10:48:17 -070053 CFG_EVENT_CREATE_AUDIO_PATCH,
54 CFG_EVENT_RELEASE_AUDIO_PATCH,
Eric Laurent81784c32012-11-19 14:55:58 -080055 };
56
Eric Laurent10351942014-05-08 18:49:52 -070057 class ConfigEventData: public RefBase {
Eric Laurent81784c32012-11-19 14:55:58 -080058 public:
Eric Laurent10351942014-05-08 18:49:52 -070059 virtual ~ConfigEventData() {}
Eric Laurent81784c32012-11-19 14:55:58 -080060
61 virtual void dump(char *buffer, size_t size) = 0;
Eric Laurent10351942014-05-08 18:49:52 -070062 protected:
63 ConfigEventData() {}
Eric Laurent81784c32012-11-19 14:55:58 -080064 };
65
Eric Laurent10351942014-05-08 18:49:52 -070066 // Config event sequence by client if status needed (e.g binder thread calling setParameters()):
67 // 1. create SetParameterConfigEvent. This sets mWaitStatus in config event
68 // 2. Lock mLock
69 // 3. Call sendConfigEvent_l(): Append to mConfigEvents and mWaitWorkCV.signal
70 // 4. sendConfigEvent_l() reads status from event->mStatus;
71 // 5. sendConfigEvent_l() returns status
72 // 6. Unlock
73 //
74 // Parameter sequence by server: threadLoop calling processConfigEvents_l():
75 // 1. Lock mLock
76 // 2. If there is an entry in mConfigEvents proceed ...
77 // 3. Read first entry in mConfigEvents
78 // 4. Remove first entry from mConfigEvents
79 // 5. Process
80 // 6. Set event->mStatus
81 // 7. event->mCond.signal
82 // 8. Unlock
Eric Laurent81784c32012-11-19 14:55:58 -080083
Eric Laurent10351942014-05-08 18:49:52 -070084 class ConfigEvent: public RefBase {
85 public:
86 virtual ~ConfigEvent() {}
87
88 void dump(char *buffer, size_t size) { mData->dump(buffer, size); }
89
90 const int mType; // event type e.g. CFG_EVENT_IO
91 Mutex mLock; // mutex associated with mCond
92 Condition mCond; // condition for status return
93 status_t mStatus; // status communicated to sender
94 bool mWaitStatus; // true if sender is waiting for status
95 sp<ConfigEventData> mData; // event specific parameter data
96
97 protected:
98 ConfigEvent(int type) : mType(type), mStatus(NO_ERROR), mWaitStatus(false), mData(NULL) {}
99 };
100
101 class IoConfigEventData : public ConfigEventData {
102 public:
103 IoConfigEventData(int event, int param) :
104 mEvent(event), mParam(param) {}
Eric Laurent81784c32012-11-19 14:55:58 -0800105
106 virtual void dump(char *buffer, size_t size) {
107 snprintf(buffer, size, "IO event: event %d, param %d\n", mEvent, mParam);
108 }
109
Eric Laurent81784c32012-11-19 14:55:58 -0800110 const int mEvent;
111 const int mParam;
112 };
113
Eric Laurent10351942014-05-08 18:49:52 -0700114 class IoConfigEvent : public ConfigEvent {
Eric Laurent81784c32012-11-19 14:55:58 -0800115 public:
Eric Laurent10351942014-05-08 18:49:52 -0700116 IoConfigEvent(int event, int param) :
117 ConfigEvent(CFG_EVENT_IO) {
118 mData = new IoConfigEventData(event, param);
119 }
120 virtual ~IoConfigEvent() {}
121 };
Eric Laurent81784c32012-11-19 14:55:58 -0800122
Eric Laurent10351942014-05-08 18:49:52 -0700123 class PrioConfigEventData : public ConfigEventData {
124 public:
125 PrioConfigEventData(pid_t pid, pid_t tid, int32_t prio) :
126 mPid(pid), mTid(tid), mPrio(prio) {}
Eric Laurent81784c32012-11-19 14:55:58 -0800127
128 virtual void dump(char *buffer, size_t size) {
129 snprintf(buffer, size, "Prio event: pid %d, tid %d, prio %d\n", mPid, mTid, mPrio);
130 }
131
Eric Laurent81784c32012-11-19 14:55:58 -0800132 const pid_t mPid;
133 const pid_t mTid;
134 const int32_t mPrio;
135 };
136
Eric Laurent10351942014-05-08 18:49:52 -0700137 class PrioConfigEvent : public ConfigEvent {
138 public:
139 PrioConfigEvent(pid_t pid, pid_t tid, int32_t prio) :
140 ConfigEvent(CFG_EVENT_PRIO) {
141 mData = new PrioConfigEventData(pid, tid, prio);
142 }
143 virtual ~PrioConfigEvent() {}
144 };
145
146 class SetParameterConfigEventData : public ConfigEventData {
147 public:
148 SetParameterConfigEventData(String8 keyValuePairs) :
149 mKeyValuePairs(keyValuePairs) {}
150
151 virtual void dump(char *buffer, size_t size) {
152 snprintf(buffer, size, "KeyValue: %s\n", mKeyValuePairs.string());
153 }
154
155 const String8 mKeyValuePairs;
156 };
157
158 class SetParameterConfigEvent : public ConfigEvent {
159 public:
160 SetParameterConfigEvent(String8 keyValuePairs) :
161 ConfigEvent(CFG_EVENT_SET_PARAMETER) {
162 mData = new SetParameterConfigEventData(keyValuePairs);
163 mWaitStatus = true;
164 }
165 virtual ~SetParameterConfigEvent() {}
166 };
167
Eric Laurent1c333e22014-05-20 10:48:17 -0700168 class CreateAudioPatchConfigEventData : public ConfigEventData {
169 public:
170 CreateAudioPatchConfigEventData(const struct audio_patch patch,
171 audio_patch_handle_t handle) :
172 mPatch(patch), mHandle(handle) {}
173
174 virtual void dump(char *buffer, size_t size) {
175 snprintf(buffer, size, "Patch handle: %u\n", mHandle);
176 }
177
178 const struct audio_patch mPatch;
179 audio_patch_handle_t mHandle;
180 };
181
182 class CreateAudioPatchConfigEvent : public ConfigEvent {
183 public:
184 CreateAudioPatchConfigEvent(const struct audio_patch patch,
185 audio_patch_handle_t handle) :
186 ConfigEvent(CFG_EVENT_CREATE_AUDIO_PATCH) {
187 mData = new CreateAudioPatchConfigEventData(patch, handle);
188 mWaitStatus = true;
189 }
190 virtual ~CreateAudioPatchConfigEvent() {}
191 };
192
193 class ReleaseAudioPatchConfigEventData : public ConfigEventData {
194 public:
195 ReleaseAudioPatchConfigEventData(const audio_patch_handle_t handle) :
196 mHandle(handle) {}
197
198 virtual void dump(char *buffer, size_t size) {
199 snprintf(buffer, size, "Patch handle: %u\n", mHandle);
200 }
201
202 audio_patch_handle_t mHandle;
203 };
204
205 class ReleaseAudioPatchConfigEvent : public ConfigEvent {
206 public:
207 ReleaseAudioPatchConfigEvent(const audio_patch_handle_t handle) :
208 ConfigEvent(CFG_EVENT_RELEASE_AUDIO_PATCH) {
209 mData = new ReleaseAudioPatchConfigEventData(handle);
210 mWaitStatus = true;
211 }
212 virtual ~ReleaseAudioPatchConfigEvent() {}
213 };
Eric Laurent81784c32012-11-19 14:55:58 -0800214
215 class PMDeathRecipient : public IBinder::DeathRecipient {
216 public:
217 PMDeathRecipient(const wp<ThreadBase>& thread) : mThread(thread) {}
218 virtual ~PMDeathRecipient() {}
219
220 // IBinder::DeathRecipient
221 virtual void binderDied(const wp<IBinder>& who);
222
223 private:
224 PMDeathRecipient(const PMDeathRecipient&);
225 PMDeathRecipient& operator = (const PMDeathRecipient&);
226
227 wp<ThreadBase> mThread;
228 };
229
230 virtual status_t initCheck() const = 0;
231
232 // static externally-visible
233 type_t type() const { return mType; }
234 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,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700287 status_t *status /*non-NULL*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800288
289 // return values for hasAudioSession (bit field)
290 enum effect_state {
291 EFFECT_SESSION = 0x1, // the audio session corresponds to at least one
292 // effect
293 TRACK_SESSION = 0x2 // the audio session corresponds to at least one
294 // track
295 };
296
297 // get effect chain corresponding to session Id.
298 sp<EffectChain> getEffectChain(int sessionId);
299 // same as getEffectChain() but must be called with ThreadBase mutex locked
300 sp<EffectChain> getEffectChain_l(int sessionId) const;
301 // add an effect chain to the chain list (mEffectChains)
302 virtual status_t addEffectChain_l(const sp<EffectChain>& chain) = 0;
303 // remove an effect chain from the chain list (mEffectChains)
304 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain) = 0;
305 // lock all effect chains Mutexes. Must be called before releasing the
306 // ThreadBase mutex before processing the mixer and effects. This guarantees the
307 // integrity of the chains during the process.
308 // Also sets the parameter 'effectChains' to current value of mEffectChains.
309 void lockEffectChains_l(Vector< sp<EffectChain> >& effectChains);
310 // unlock effect chains after process
311 void unlockEffectChains(const Vector< sp<EffectChain> >& effectChains);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800312 // get a copy of mEffectChains vector
313 Vector< sp<EffectChain> > getEffectChains_l() const { return mEffectChains; };
Eric Laurent81784c32012-11-19 14:55:58 -0800314 // set audio mode to all effect chains
315 void setMode(audio_mode_t mode);
316 // get effect module with corresponding ID on specified audio session
317 sp<AudioFlinger::EffectModule> getEffect(int sessionId, int effectId);
318 sp<AudioFlinger::EffectModule> getEffect_l(int sessionId, int effectId);
319 // add and effect module. Also creates the effect chain is none exists for
320 // the effects audio session
321 status_t addEffect_l(const sp< EffectModule>& effect);
322 // remove and effect module. Also removes the effect chain is this was the last
323 // effect
324 void removeEffect_l(const sp< EffectModule>& effect);
325 // detach all tracks connected to an auxiliary effect
Glenn Kasten0f11b512014-01-31 16:18:54 -0800326 virtual void detachAuxEffect_l(int effectId __unused) {}
Eric Laurent81784c32012-11-19 14:55:58 -0800327 // returns either EFFECT_SESSION if effects on this audio session exist in one
328 // chain, or TRACK_SESSION if tracks on this audio session exist, or both
329 virtual uint32_t hasAudioSession(int sessionId) const = 0;
330 // the value returned by default implementation is not important as the
331 // strategy is only meaningful for PlaybackThread which implements this method
Glenn Kasten0f11b512014-01-31 16:18:54 -0800332 virtual uint32_t getStrategyForSession_l(int sessionId __unused) { return 0; }
Eric Laurent81784c32012-11-19 14:55:58 -0800333
334 // suspend or restore effect according to the type of effect passed. a NULL
335 // type pointer means suspend all effects in the session
336 void setEffectSuspended(const effect_uuid_t *type,
337 bool suspend,
338 int sessionId = AUDIO_SESSION_OUTPUT_MIX);
339 // check if some effects must be suspended/restored when an effect is enabled
340 // or disabled
341 void checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
342 bool enabled,
343 int sessionId = AUDIO_SESSION_OUTPUT_MIX);
344 void checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
345 bool enabled,
346 int sessionId = AUDIO_SESSION_OUTPUT_MIX);
347
348 virtual status_t setSyncEvent(const sp<SyncEvent>& event) = 0;
349 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const = 0;
350
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700351 // Return a reference to a per-thread heap which can be used to allocate IMemory
352 // objects that will be read-only to client processes, read/write to mediaserver,
353 // and shared by all client processes of the thread.
354 // The heap is per-thread rather than common across all threads, because
355 // clients can't be trusted not to modify the offset of the IMemory they receive.
356 // If a thread does not have such a heap, this method returns 0.
357 virtual sp<MemoryDealer> readOnlyHeap() const { return 0; }
Eric Laurent81784c32012-11-19 14:55:58 -0800358
Glenn Kasten6181ffd2014-05-13 10:41:52 -0700359 virtual sp<IMemory> pipeMemory() const { return 0; }
360
Eric Laurent81784c32012-11-19 14:55:58 -0800361 mutable Mutex mLock;
362
363protected:
364
365 // entry describing an effect being suspended in mSuspendedSessions keyed vector
366 class SuspendedSessionDesc : public RefBase {
367 public:
368 SuspendedSessionDesc() : mRefCount(0) {}
369
370 int mRefCount; // number of active suspend requests
371 effect_uuid_t mType; // effect type UUID
372 };
373
Marco Nelissene14a5d62013-10-03 08:51:24 -0700374 void acquireWakeLock(int uid = -1);
375 void acquireWakeLock_l(int uid = -1);
Eric Laurent81784c32012-11-19 14:55:58 -0800376 void releaseWakeLock();
377 void releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800378 void updateWakeLockUids(const SortedVector<int> &uids);
379 void updateWakeLockUids_l(const SortedVector<int> &uids);
380 void getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800381 void setEffectSuspended_l(const effect_uuid_t *type,
382 bool suspend,
383 int sessionId);
384 // updated mSuspendedSessions when an effect suspended or restored
385 void updateSuspendedSessions_l(const effect_uuid_t *type,
386 bool suspend,
387 int sessionId);
388 // check if some effects must be suspended when an effect chain is added
389 void checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain);
390
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100391 String16 getWakeLockTag();
392
Eric Laurent81784c32012-11-19 14:55:58 -0800393 virtual void preExit() { }
394
395 friend class AudioFlinger; // for mEffectChains
396
397 const type_t mType;
398
399 // Used by parameters, config events, addTrack_l, exit
400 Condition mWaitWorkCV;
401
402 const sp<AudioFlinger> mAudioFlinger;
Glenn Kasten9b58f632013-07-16 11:37:48 -0700403
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800404 // updated by PlaybackThread::readOutputParameters_l() or
405 // RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800406 uint32_t mSampleRate;
407 size_t mFrameCount; // output HAL, direct output, record
Eric Laurent81784c32012-11-19 14:55:58 -0800408 audio_channel_mask_t mChannelMask;
Glenn Kastenf6ed4232013-07-16 11:16:27 -0700409 uint32_t mChannelCount;
Eric Laurent81784c32012-11-19 14:55:58 -0800410 size_t mFrameSize;
Glenn Kasten97b7b752014-09-28 13:04:24 -0700411 // not HAL frame size, this is for output sink (to pipe to fast mixer)
Andy Hung463be252014-07-10 16:56:07 -0700412 audio_format_t mFormat; // Source format for Recording and
413 // Sink format for Playback.
414 // Sink format may be different than
415 // HAL format if Fastmixer is used.
416 audio_format_t mHALFormat;
Glenn Kasten70949c42013-08-06 07:40:12 -0700417 size_t mBufferSize; // HAL buffer size for read() or write()
Eric Laurent81784c32012-11-19 14:55:58 -0800418
Eric Laurent10351942014-05-08 18:49:52 -0700419 Vector< sp<ConfigEvent> > mConfigEvents;
Eric Laurent81784c32012-11-19 14:55:58 -0800420
421 // These fields are written and read by thread itself without lock or barrier,
Glenn Kasten4944acb2013-08-19 08:39:20 -0700422 // and read by other threads without lock or barrier via standby(), outDevice()
Eric Laurent81784c32012-11-19 14:55:58 -0800423 // and inDevice().
424 // Because of the absence of a lock or barrier, any other thread that reads
425 // these fields must use the information in isolation, or be prepared to deal
426 // with possibility that it might be inconsistent with other information.
Glenn Kasten4944acb2013-08-19 08:39:20 -0700427 bool mStandby; // Whether thread is currently in standby.
Eric Laurent81784c32012-11-19 14:55:58 -0800428 audio_devices_t mOutDevice; // output device
429 audio_devices_t mInDevice; // input device
430 audio_source_t mAudioSource; // (see audio.h, audio_source_t)
431
432 const audio_io_handle_t mId;
433 Vector< sp<EffectChain> > mEffectChains;
434
435 static const int kNameLength = 16; // prctl(PR_SET_NAME) limit
436 char mName[kNameLength];
437 sp<IPowerManager> mPowerManager;
438 sp<IBinder> mWakeLockToken;
439 const sp<PMDeathRecipient> mDeathRecipient;
440 // list of suspended effects per session and per type. The first vector is
441 // keyed by session ID, the second by type UUID timeLow field
442 KeyedVector< int, KeyedVector< int, sp<SuspendedSessionDesc> > >
443 mSuspendedSessions;
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800444 static const size_t kLogSize = 4 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -0800445 sp<NBLog::Writer> mNBLogWriter;
Eric Laurent81784c32012-11-19 14:55:58 -0800446};
447
448// --- PlaybackThread ---
449class PlaybackThread : public ThreadBase {
450public:
451
452#include "PlaybackTracks.h"
453
454 enum mixer_state {
455 MIXER_IDLE, // no active tracks
456 MIXER_TRACKS_ENABLED, // at least one active track, but no track has any data ready
Eric Laurentbfb1b832013-01-07 09:53:42 -0800457 MIXER_TRACKS_READY, // at least one active track, and at least one track has data
458 MIXER_DRAIN_TRACK, // drain currently playing track
459 MIXER_DRAIN_ALL, // fully drain the hardware
Eric Laurent81784c32012-11-19 14:55:58 -0800460 // standby mode does not have an enum value
461 // suspend by audio policy manager is orthogonal to mixer state
462 };
463
Eric Laurentbfb1b832013-01-07 09:53:42 -0800464 // retry count before removing active track in case of underrun on offloaded thread:
465 // we need to make sure that AudioTrack client has enough time to send large buffers
466//FIXME may be more appropriate if expressed in time units. Need to revise how underrun is handled
467 // for offloaded tracks
468 static const int8_t kMaxTrackRetriesOffload = 20;
469
Eric Laurent81784c32012-11-19 14:55:58 -0800470 PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
471 audio_io_handle_t id, audio_devices_t device, type_t type);
472 virtual ~PlaybackThread();
473
474 void dump(int fd, const Vector<String16>& args);
475
476 // Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -0800477 virtual bool threadLoop();
478
479 // RefBase
480 virtual void onFirstRef();
481
482protected:
483 // Code snippets that were lifted up out of threadLoop()
484 virtual void threadLoop_mix() = 0;
485 virtual void threadLoop_sleepTime() = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800486 virtual ssize_t threadLoop_write();
487 virtual void threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -0800488 virtual void threadLoop_standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800489 virtual void threadLoop_exit();
Eric Laurent81784c32012-11-19 14:55:58 -0800490 virtual void threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
491
492 // prepareTracks_l reads and writes mActiveTracks, and returns
493 // the pending set of tracks to remove via Vector 'tracksToRemove'. The caller
494 // is responsible for clearing or destroying this Vector later on, when it
495 // is safe to do so. That will drop the final ref count and destroy the tracks.
496 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove) = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800497 void removeTracks_l(const Vector< sp<Track> >& tracksToRemove);
498
499 void writeCallback();
Eric Laurent3b4529e2013-09-05 18:09:19 -0700500 void resetWriteBlocked(uint32_t sequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800501 void drainCallback();
Eric Laurent3b4529e2013-09-05 18:09:19 -0700502 void resetDraining(uint32_t sequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800503
504 static int asyncCallback(stream_callback_event_t event, void *param, void *cookie);
505
506 virtual bool waitingAsyncCallback();
507 virtual bool waitingAsyncCallback_l();
508 virtual bool shouldStandby_l();
Haynes Mathew George4c6a4332014-01-15 12:31:39 -0800509 virtual void onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800510
511 // ThreadBase virtuals
512 virtual void preExit();
513
514public:
515
516 virtual status_t initCheck() const { return (mOutput == NULL) ? NO_INIT : NO_ERROR; }
517
518 // return estimated latency in milliseconds, as reported by HAL
519 uint32_t latency() const;
520 // same, but lock must already be held
521 uint32_t latency_l() const;
522
523 void setMasterVolume(float value);
524 void setMasterMute(bool muted);
525
526 void setStreamVolume(audio_stream_type_t stream, float value);
527 void setStreamMute(audio_stream_type_t stream, bool muted);
528
529 float streamVolume(audio_stream_type_t stream) const;
530
531 sp<Track> createTrack_l(
532 const sp<AudioFlinger::Client>& client,
533 audio_stream_type_t streamType,
534 uint32_t sampleRate,
535 audio_format_t format,
536 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -0800537 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -0800538 const sp<IMemory>& sharedBuffer,
539 int sessionId,
540 IAudioFlinger::track_flags_t *flags,
541 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800542 int uid,
Glenn Kasten9156ef32013-08-06 15:39:08 -0700543 status_t *status /*non-NULL*/);
Eric Laurent81784c32012-11-19 14:55:58 -0800544
545 AudioStreamOut* getOutput() const;
546 AudioStreamOut* clearOutput();
547 virtual audio_stream_t* stream() const;
548
549 // a very large number of suspend() will eventually wraparound, but unlikely
550 void suspend() { (void) android_atomic_inc(&mSuspended); }
551 void restore()
552 {
553 // if restore() is done without suspend(), get back into
554 // range so that the next suspend() will operate correctly
555 if (android_atomic_dec(&mSuspended) <= 0) {
556 android_atomic_release_store(0, &mSuspended);
557 }
558 }
559 bool isSuspended() const
560 { return android_atomic_acquire_load(&mSuspended) > 0; }
561
562 virtual String8 getParameters(const String8& keys);
Eric Laurent021cf962014-05-13 10:18:14 -0700563 virtual void audioConfigChanged(int event, int param = 0);
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000564 status_t getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames);
Andy Hung010a1a12014-03-13 13:57:33 -0700565 // FIXME rename mixBuffer() to sinkBuffer() and remove int16_t* dependency.
566 // Consider also removing and passing an explicit mMainBuffer initialization
567 // parameter to AF::PlaybackThread::Track::Track().
568 int16_t *mixBuffer() const {
569 return reinterpret_cast<int16_t *>(mSinkBuffer); };
Eric Laurent81784c32012-11-19 14:55:58 -0800570
571 virtual void detachAuxEffect_l(int effectId);
572 status_t attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track> track,
573 int EffectId);
574 status_t attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track> track,
575 int EffectId);
576
577 virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
578 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
579 virtual uint32_t hasAudioSession(int sessionId) const;
580 virtual uint32_t getStrategyForSession_l(int sessionId);
581
582
583 virtual status_t setSyncEvent(const sp<SyncEvent>& event);
584 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const;
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700585
586 // called with AudioFlinger lock held
Eric Laurent81784c32012-11-19 14:55:58 -0800587 void invalidateTracks(audio_stream_type_t streamType);
588
Glenn Kasten9b58f632013-07-16 11:37:48 -0700589 virtual size_t frameCount() const { return mNormalFrameCount; }
590
591 // Return's the HAL's frame count i.e. fast mixer buffer size.
592 size_t frameCountHAL() const { return mFrameCount; }
Eric Laurent81784c32012-11-19 14:55:58 -0800593
Eric Laurent83b88082014-06-20 18:31:16 -0700594 status_t getTimestamp_l(AudioTimestamp& timestamp);
595
596 void addPatchTrack(const sp<PatchTrack>& track);
597 void deletePatchTrack(const sp<PatchTrack>& track);
598
599 virtual void getAudioPortConfig(struct audio_port_config *config);
Eric Laurentaccc1472013-09-20 09:36:34 -0700600
Eric Laurent81784c32012-11-19 14:55:58 -0800601protected:
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800602 // updated by readOutputParameters_l()
Glenn Kasten9b58f632013-07-16 11:37:48 -0700603 size_t mNormalFrameCount; // normal mixer and effects
604
Andy Hung010a1a12014-03-13 13:57:33 -0700605 void* mSinkBuffer; // frame size aligned sink buffer
Eric Laurent81784c32012-11-19 14:55:58 -0800606
Andy Hung98ef9782014-03-04 14:46:50 -0800607 // TODO:
608 // Rearrange the buffer info into a struct/class with
609 // clear, copy, construction, destruction methods.
610 //
611 // mSinkBuffer also has associated with it:
612 //
613 // mSinkBufferSize: Sink Buffer Size
614 // mFormat: Sink Buffer Format
615
Andy Hung69aed5f2014-02-25 17:24:40 -0800616 // Mixer Buffer (mMixerBuffer*)
617 //
618 // In the case of floating point or multichannel data, which is not in the
619 // sink format, it is required to accumulate in a higher precision or greater channel count
620 // buffer before downmixing or data conversion to the sink buffer.
621
622 // Set to "true" to enable the Mixer Buffer otherwise mixer output goes to sink buffer.
623 bool mMixerBufferEnabled;
624
625 // Storage, 32 byte aligned (may make this alignment a requirement later).
626 // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
627 void* mMixerBuffer;
628
629 // Size of mMixerBuffer in bytes: mNormalFrameCount * #channels * sampsize.
630 size_t mMixerBufferSize;
631
632 // The audio format of mMixerBuffer. Set to AUDIO_FORMAT_PCM_(FLOAT|16_BIT) only.
633 audio_format_t mMixerBufferFormat;
634
635 // An internal flag set to true by MixerThread::prepareTracks_l()
636 // when mMixerBuffer contains valid data after mixing.
637 bool mMixerBufferValid;
638
Andy Hung98ef9782014-03-04 14:46:50 -0800639 // Effects Buffer (mEffectsBuffer*)
640 //
641 // In the case of effects data, which is not in the sink format,
642 // it is required to accumulate in a different buffer before data conversion
643 // to the sink buffer.
644
645 // Set to "true" to enable the Effects Buffer otherwise effects output goes to sink buffer.
646 bool mEffectBufferEnabled;
647
648 // Storage, 32 byte aligned (may make this alignment a requirement later).
649 // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
650 void* mEffectBuffer;
651
652 // Size of mEffectsBuffer in bytes: mNormalFrameCount * #channels * sampsize.
653 size_t mEffectBufferSize;
654
655 // The audio format of mEffectsBuffer. Set to AUDIO_FORMAT_PCM_16_BIT only.
656 audio_format_t mEffectBufferFormat;
657
658 // An internal flag set to true by MixerThread::prepareTracks_l()
659 // when mEffectsBuffer contains valid data after mixing.
660 //
661 // When this is set, all mixer data is routed into the effects buffer
662 // for any processing (including output processing).
663 bool mEffectBufferValid;
664
Eric Laurent81784c32012-11-19 14:55:58 -0800665 // suspend count, > 0 means suspended. While suspended, the thread continues to pull from
666 // tracks and mix, but doesn't write to HAL. A2DP and SCO HAL implementations can't handle
667 // concurrent use of both of them, so Audio Policy Service suspends one of the threads to
668 // workaround that restriction.
669 // 'volatile' means accessed via atomic operations and no lock.
670 volatile int32_t mSuspended;
671
672 // FIXME overflows every 6+ hours at 44.1 kHz stereo 16-bit samples
673 // mFramesWritten would be better, or 64-bit even better
674 size_t mBytesWritten;
675private:
676 // mMasterMute is in both PlaybackThread and in AudioFlinger. When a
677 // PlaybackThread needs to find out if master-muted, it checks it's local
678 // copy rather than the one in AudioFlinger. This optimization saves a lock.
679 bool mMasterMute;
680 void setMasterMute_l(bool muted) { mMasterMute = muted; }
681protected:
682 SortedVector< wp<Track> > mActiveTracks; // FIXME check if this could be sp<>
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800683 SortedVector<int> mWakeLockUids;
684 int mActiveTracksGeneration;
Eric Laurentfd477972013-10-25 18:10:40 -0700685 wp<Track> mLatestActiveTrack; // latest track added to mActiveTracks
Eric Laurent81784c32012-11-19 14:55:58 -0800686
687 // Allocate a track name for a given channel mask.
688 // Returns name >= 0 if successful, -1 on failure.
Andy Hunge8a1ced2014-05-09 15:02:21 -0700689 virtual int getTrackName_l(audio_channel_mask_t channelMask,
690 audio_format_t format, int sessionId) = 0;
Eric Laurent81784c32012-11-19 14:55:58 -0800691 virtual void deleteTrackName_l(int name) = 0;
692
693 // Time to sleep between cycles when:
694 virtual uint32_t activeSleepTimeUs() const; // mixer state MIXER_TRACKS_ENABLED
695 virtual uint32_t idleSleepTimeUs() const = 0; // mixer state MIXER_IDLE
696 virtual uint32_t suspendSleepTimeUs() const = 0; // audio policy manager suspended us
697 // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write()
698 // No sleep in standby mode; waits on a condition
699
700 // Code snippets that are temporarily lifted up out of threadLoop() until the merge
701 void checkSilentMode_l();
702
703 // Non-trivial for DUPLICATING only
704 virtual void saveOutputTracks() { }
705 virtual void clearOutputTracks() { }
706
707 // Cache various calculated values, at threadLoop() entry and after a parameter change
708 virtual void cacheParameters_l();
709
710 virtual uint32_t correctLatency_l(uint32_t latency) const;
711
Eric Laurent1c333e22014-05-20 10:48:17 -0700712 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
713 audio_patch_handle_t *handle);
714 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle);
715
Eric Laurent81784c32012-11-19 14:55:58 -0800716private:
717
718 friend class AudioFlinger; // for numerous
719
Eric Laurent81784c32012-11-19 14:55:58 -0800720 PlaybackThread& operator = (const PlaybackThread&);
721
722 status_t addTrack_l(const sp<Track>& track);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800723 bool destroyTrack_l(const sp<Track>& track);
Eric Laurent81784c32012-11-19 14:55:58 -0800724 void removeTrack_l(const sp<Track>& track);
Eric Laurentede6c3b2013-09-19 14:37:46 -0700725 void broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800726
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800727 void readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800728
729 virtual void dumpInternals(int fd, const Vector<String16>& args);
730 void dumpTracks(int fd, const Vector<String16>& args);
731
732 SortedVector< sp<Track> > mTracks;
Eric Laurent223fd5c2014-11-11 13:43:36 -0800733 stream_type_t mStreamTypes[AUDIO_STREAM_CNT];
Eric Laurent81784c32012-11-19 14:55:58 -0800734 AudioStreamOut *mOutput;
735
736 float mMasterVolume;
737 nsecs_t mLastWriteTime;
738 int mNumWrites;
739 int mNumDelayedWrites;
740 bool mInWrite;
741
742 // FIXME rename these former local variables of threadLoop to standard "m" names
743 nsecs_t standbyTime;
Andy Hung25c2dac2014-02-27 14:56:00 -0800744 size_t mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -0800745
746 // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l()
747 uint32_t activeSleepTime;
748 uint32_t idleSleepTime;
749
750 uint32_t sleepTime;
751
752 // mixer status returned by prepareTracks_l()
753 mixer_state mMixerStatus; // current cycle
754 // previous cycle when in prepareTracks_l()
755 mixer_state mMixerStatusIgnoringFastTracks;
756 // FIXME or a separate ready state per track
757
758 // FIXME move these declarations into the specific sub-class that needs them
759 // MIXER only
760 uint32_t sleepTimeShift;
761
762 // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value
763 nsecs_t standbyDelay;
764
765 // MIXER only
766 nsecs_t maxPeriod;
767
768 // DUPLICATING only
769 uint32_t writeFrames;
770
Eric Laurentbfb1b832013-01-07 09:53:42 -0800771 size_t mBytesRemaining;
772 size_t mCurrentWriteLength;
773 bool mUseAsyncWrite;
Eric Laurent3b4529e2013-09-05 18:09:19 -0700774 // mWriteAckSequence contains current write sequence on bits 31-1. The write sequence is
775 // incremented each time a write(), a flush() or a standby() occurs.
776 // Bit 0 is set when a write blocks and indicates a callback is expected.
777 // Bit 0 is reset by the async callback thread calling resetWriteBlocked(). Out of sequence
778 // callbacks are ignored.
779 uint32_t mWriteAckSequence;
780 // mDrainSequence contains current drain sequence on bits 31-1. The drain sequence is
781 // incremented each time a drain is requested or a flush() or standby() occurs.
782 // Bit 0 is set when the drain() command is called at the HAL and indicates a callback is
783 // expected.
784 // Bit 0 is reset by the async callback thread calling resetDraining(). Out of sequence
785 // callbacks are ignored.
786 uint32_t mDrainSequence;
Eric Laurentede6c3b2013-09-19 14:37:46 -0700787 // A condition that must be evaluated by prepareTrack_l() has changed and we must not wait
788 // for async write callback in the thread loop before evaluating it
Eric Laurentbfb1b832013-01-07 09:53:42 -0800789 bool mSignalPending;
790 sp<AsyncCallbackThread> mCallbackThread;
791
Eric Laurent81784c32012-11-19 14:55:58 -0800792private:
793 // The HAL output sink is treated as non-blocking, but current implementation is blocking
794 sp<NBAIO_Sink> mOutputSink;
795 // If a fast mixer is present, the blocking pipe sink, otherwise clear
796 sp<NBAIO_Sink> mPipeSink;
797 // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink
798 sp<NBAIO_Sink> mNormalSink;
Glenn Kasten46909e72013-02-26 09:20:22 -0800799#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -0800800 // For dumpsys
801 sp<NBAIO_Sink> mTeeSink;
802 sp<NBAIO_Source> mTeeSource;
Glenn Kasten46909e72013-02-26 09:20:22 -0800803#endif
Eric Laurent81784c32012-11-19 14:55:58 -0800804 uint32_t mScreenState; // cached copy of gScreenState
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800805 static const size_t kFastMixerLogSize = 4 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -0800806 sp<NBLog::Writer> mFastMixerNBLogWriter;
Eric Laurent81784c32012-11-19 14:55:58 -0800807public:
808 virtual bool hasFastMixer() const = 0;
Glenn Kasten0f11b512014-01-31 16:18:54 -0800809 virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -0800810 { FastTrackUnderruns dummy; return dummy; }
811
812protected:
813 // accessed by both binder threads and within threadLoop(), lock on mutex needed
814 unsigned mFastTrackAvailMask; // bit i set if fast track [i] is available
Eric Laurentd1f69b02014-12-15 14:33:13 -0800815 bool mHwSupportsPause;
816 bool mHwPaused;
817 bool mFlushPending;
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700818private:
819 // timestamp latch:
820 // D input is written by threadLoop_write while mutex is unlocked, and read while locked
821 // Q output is written while locked, and read while locked
822 struct {
823 AudioTimestamp mTimestamp;
824 uint32_t mUnpresentedFrames;
Glenn Kasten4c053ea2014-09-28 14:41:07 -0700825 KeyedVector<Track *, uint32_t> mFramesReleased;
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700826 } mLatchD, mLatchQ;
Glenn Kasten4c053ea2014-09-28 14:41:07 -0700827 bool mLatchDValid; // true means mLatchD is valid
828 // (except for mFramesReleased which is filled in later),
829 // and clock it into latch at next opportunity
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700830 bool mLatchQValid; // true means mLatchQ is valid
Eric Laurent81784c32012-11-19 14:55:58 -0800831};
832
833class MixerThread : public PlaybackThread {
834public:
835 MixerThread(const sp<AudioFlinger>& audioFlinger,
836 AudioStreamOut* output,
837 audio_io_handle_t id,
838 audio_devices_t device,
839 type_t type = MIXER);
840 virtual ~MixerThread();
841
842 // Thread virtuals
843
Eric Laurent10351942014-05-08 18:49:52 -0700844 virtual bool checkForNewParameter_l(const String8& keyValuePair,
845 status_t& status);
Eric Laurent81784c32012-11-19 14:55:58 -0800846 virtual void dumpInternals(int fd, const Vector<String16>& args);
847
848protected:
849 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
Andy Hunge8a1ced2014-05-09 15:02:21 -0700850 virtual int getTrackName_l(audio_channel_mask_t channelMask,
851 audio_format_t format, int sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800852 virtual void deleteTrackName_l(int name);
853 virtual uint32_t idleSleepTimeUs() const;
854 virtual uint32_t suspendSleepTimeUs() const;
855 virtual void cacheParameters_l();
856
857 // threadLoop snippets
Eric Laurentbfb1b832013-01-07 09:53:42 -0800858 virtual ssize_t threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -0800859 virtual void threadLoop_standby();
860 virtual void threadLoop_mix();
861 virtual void threadLoop_sleepTime();
862 virtual void threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
863 virtual uint32_t correctLatency_l(uint32_t latency) const;
864
865 AudioMixer* mAudioMixer; // normal mixer
866private:
867 // one-time initialization, no locks required
Glenn Kasten4d23ca32014-05-13 10:39:51 -0700868 sp<FastMixer> mFastMixer; // non-0 if there is also a fast mixer
Eric Laurent81784c32012-11-19 14:55:58 -0800869 sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread
870
871 // contents are not guaranteed to be consistent, no locks required
872 FastMixerDumpState mFastMixerDumpState;
873#ifdef STATE_QUEUE_DUMP
874 StateQueueObserverDump mStateQueueObserverDump;
875 StateQueueMutatorDump mStateQueueMutatorDump;
876#endif
877 AudioWatchdogDump mAudioWatchdogDump;
878
879 // accessible only within the threadLoop(), no locks required
880 // mFastMixer->sq() // for mutating and pushing state
881 int32_t mFastMixerFutex; // for cold idle
882
883public:
Glenn Kasten4d23ca32014-05-13 10:39:51 -0700884 virtual bool hasFastMixer() const { return mFastMixer != 0; }
Eric Laurent81784c32012-11-19 14:55:58 -0800885 virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const {
886 ALOG_ASSERT(fastIndex < FastMixerState::kMaxFastTracks);
887 return mFastMixerDumpState.mTracks[fastIndex].mUnderruns;
888 }
Eric Laurent83b88082014-06-20 18:31:16 -0700889
Eric Laurent81784c32012-11-19 14:55:58 -0800890};
891
892class DirectOutputThread : public PlaybackThread {
893public:
894
895 DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
896 audio_io_handle_t id, audio_devices_t device);
897 virtual ~DirectOutputThread();
898
899 // Thread virtuals
900
Eric Laurent10351942014-05-08 18:49:52 -0700901 virtual bool checkForNewParameter_l(const String8& keyValuePair,
902 status_t& status);
Eric Laurente659ef42014-09-29 13:06:46 -0700903 virtual void flushHw_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800904
905protected:
Andy Hunge8a1ced2014-05-09 15:02:21 -0700906 virtual int getTrackName_l(audio_channel_mask_t channelMask,
907 audio_format_t format, int sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -0800908 virtual void deleteTrackName_l(int name);
909 virtual uint32_t activeSleepTimeUs() const;
910 virtual uint32_t idleSleepTimeUs() const;
911 virtual uint32_t suspendSleepTimeUs() const;
912 virtual void cacheParameters_l();
913
914 // threadLoop snippets
915 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
916 virtual void threadLoop_mix();
917 virtual void threadLoop_sleepTime();
Eric Laurentd1f69b02014-12-15 14:33:13 -0800918 virtual void threadLoop_exit();
919 virtual bool shouldStandby_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800920
Eric Laurent81784c32012-11-19 14:55:58 -0800921 // volumes last sent to audio HAL with stream->set_volume()
922 float mLeftVolFloat;
923 float mRightVolFloat;
924
Eric Laurentbfb1b832013-01-07 09:53:42 -0800925 DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
926 audio_io_handle_t id, uint32_t device, ThreadBase::type_t type);
927 void processVolume_l(Track *track, bool lastTrack);
928
Eric Laurent81784c32012-11-19 14:55:58 -0800929 // prepareTracks_l() tells threadLoop_mix() the name of the single active track
930 sp<Track> mActiveTrack;
931public:
932 virtual bool hasFastMixer() const { return false; }
933};
934
Eric Laurentbfb1b832013-01-07 09:53:42 -0800935class OffloadThread : public DirectOutputThread {
936public:
937
938 OffloadThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
939 audio_io_handle_t id, uint32_t device);
Eric Laurent6a51d7e2013-10-17 18:59:26 -0700940 virtual ~OffloadThread() {};
Eric Laurente659ef42014-09-29 13:06:46 -0700941 virtual void flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800942
943protected:
944 // threadLoop snippets
945 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
946 virtual void threadLoop_exit();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800947
948 virtual bool waitingAsyncCallback();
949 virtual bool waitingAsyncCallback_l();
Haynes Mathew George4c6a4332014-01-15 12:31:39 -0800950 virtual void onAddNewTrack_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800951
952private:
Eric Laurentbfb1b832013-01-07 09:53:42 -0800953 size_t mPausedWriteLength; // length in bytes of write interrupted by pause
954 size_t mPausedBytesRemaining; // bytes still waiting in mixbuffer after resume
Eric Laurentd7e59222013-11-15 12:02:28 -0800955 wp<Track> mPreviousTrack; // used to detect track switch
Eric Laurentbfb1b832013-01-07 09:53:42 -0800956};
957
958class AsyncCallbackThread : public Thread {
959public:
960
Eric Laurent4de95592013-09-26 15:28:21 -0700961 AsyncCallbackThread(const wp<PlaybackThread>& playbackThread);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800962
963 virtual ~AsyncCallbackThread();
964
965 // Thread virtuals
966 virtual bool threadLoop();
967
968 // RefBase
969 virtual void onFirstRef();
970
971 void exit();
Eric Laurent3b4529e2013-09-05 18:09:19 -0700972 void setWriteBlocked(uint32_t sequence);
973 void resetWriteBlocked();
974 void setDraining(uint32_t sequence);
975 void resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800976
977private:
Eric Laurent4de95592013-09-26 15:28:21 -0700978 const wp<PlaybackThread> mPlaybackThread;
Eric Laurent3b4529e2013-09-05 18:09:19 -0700979 // mWriteAckSequence corresponds to the last write sequence passed by the offload thread via
980 // setWriteBlocked(). The sequence is shifted one bit to the left and the lsb is used
981 // to indicate that the callback has been received via resetWriteBlocked()
Eric Laurent4de95592013-09-26 15:28:21 -0700982 uint32_t mWriteAckSequence;
Eric Laurent3b4529e2013-09-05 18:09:19 -0700983 // mDrainSequence corresponds to the last drain sequence passed by the offload thread via
984 // setDraining(). The sequence is shifted one bit to the left and the lsb is used
985 // to indicate that the callback has been received via resetDraining()
Eric Laurent4de95592013-09-26 15:28:21 -0700986 uint32_t mDrainSequence;
987 Condition mWaitWorkCV;
988 Mutex mLock;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800989};
990
Eric Laurent81784c32012-11-19 14:55:58 -0800991class DuplicatingThread : public MixerThread {
992public:
993 DuplicatingThread(const sp<AudioFlinger>& audioFlinger, MixerThread* mainThread,
994 audio_io_handle_t id);
995 virtual ~DuplicatingThread();
996
997 // Thread virtuals
998 void addOutputTrack(MixerThread* thread);
999 void removeOutputTrack(MixerThread* thread);
1000 uint32_t waitTimeMs() const { return mWaitTimeMs; }
1001protected:
1002 virtual uint32_t activeSleepTimeUs() const;
1003
1004private:
1005 bool outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks);
1006protected:
1007 // threadLoop snippets
1008 virtual void threadLoop_mix();
1009 virtual void threadLoop_sleepTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001010 virtual ssize_t threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08001011 virtual void threadLoop_standby();
1012 virtual void cacheParameters_l();
1013
1014private:
1015 // called from threadLoop, addOutputTrack, removeOutputTrack
1016 virtual void updateWaitTime_l();
1017protected:
1018 virtual void saveOutputTracks();
1019 virtual void clearOutputTracks();
1020private:
1021
1022 uint32_t mWaitTimeMs;
1023 SortedVector < sp<OutputTrack> > outputTracks;
1024 SortedVector < sp<OutputTrack> > mOutputTracks;
1025public:
1026 virtual bool hasFastMixer() const { return false; }
1027};
1028
1029
1030// record thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001031class RecordThread : public ThreadBase
Eric Laurent81784c32012-11-19 14:55:58 -08001032{
1033public:
1034
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001035 class RecordTrack;
1036 class ResamplerBufferProvider : public AudioBufferProvider
1037 // derives from AudioBufferProvider interface for use by resampler
1038 {
1039 public:
1040 ResamplerBufferProvider(RecordTrack* recordTrack) : mRecordTrack(recordTrack) { }
1041 virtual ~ResamplerBufferProvider() { }
1042 // AudioBufferProvider interface
1043 virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts);
1044 virtual void releaseBuffer(AudioBufferProvider::Buffer* buffer);
1045 private:
1046 RecordTrack * const mRecordTrack;
1047 };
1048
Eric Laurent81784c32012-11-19 14:55:58 -08001049#include "RecordTracks.h"
1050
1051 RecordThread(const sp<AudioFlinger>& audioFlinger,
1052 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08001053 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08001054 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08001055 audio_devices_t inDevice
1056#ifdef TEE_SINK
1057 , const sp<NBAIO_Sink>& teeSink
1058#endif
1059 );
Eric Laurent81784c32012-11-19 14:55:58 -08001060 virtual ~RecordThread();
1061
1062 // no addTrack_l ?
1063 void destroyTrack_l(const sp<RecordTrack>& track);
1064 void removeTrack_l(const sp<RecordTrack>& track);
1065
1066 void dumpInternals(int fd, const Vector<String16>& args);
1067 void dumpTracks(int fd, const Vector<String16>& args);
1068
1069 // Thread virtuals
1070 virtual bool threadLoop();
Eric Laurent81784c32012-11-19 14:55:58 -08001071
1072 // RefBase
1073 virtual void onFirstRef();
1074
1075 virtual status_t initCheck() const { return (mInput == NULL) ? NO_INIT : NO_ERROR; }
Glenn Kastene198c362013-08-13 09:13:36 -07001076
Glenn Kastenb880f5e2014-05-07 08:43:45 -07001077 virtual sp<MemoryDealer> readOnlyHeap() const { return mReadOnlyHeap; }
1078
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001079 virtual sp<IMemory> pipeMemory() const { return mPipeMemory; }
1080
Eric Laurent81784c32012-11-19 14:55:58 -08001081 sp<AudioFlinger::RecordThread::RecordTrack> createRecordTrack_l(
1082 const sp<AudioFlinger::Client>& client,
1083 uint32_t sampleRate,
1084 audio_format_t format,
1085 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001086 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001087 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001088 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001089 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07001090 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001091 pid_t tid,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001092 status_t *status /*non-NULL*/);
Eric Laurent81784c32012-11-19 14:55:58 -08001093
1094 status_t start(RecordTrack* recordTrack,
1095 AudioSystem::sync_event_t event,
1096 int triggerSession);
1097
1098 // ask the thread to stop the specified track, and
1099 // return true if the caller should then do it's part of the stopping process
Glenn Kastena8356f62013-07-25 14:37:52 -07001100 bool stop(RecordTrack* recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08001101
1102 void dump(int fd, const Vector<String16>& args);
1103 AudioStreamIn* clearInput();
1104 virtual audio_stream_t* stream() const;
1105
Eric Laurent81784c32012-11-19 14:55:58 -08001106
Eric Laurent10351942014-05-08 18:49:52 -07001107 virtual bool checkForNewParameter_l(const String8& keyValuePair,
1108 status_t& status);
1109 virtual void cacheParameters_l() {}
Eric Laurent81784c32012-11-19 14:55:58 -08001110 virtual String8 getParameters(const String8& keys);
Eric Laurent021cf962014-05-13 10:18:14 -07001111 virtual void audioConfigChanged(int event, int param = 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07001112 virtual status_t createAudioPatch_l(const struct audio_patch *patch,
1113 audio_patch_handle_t *handle);
1114 virtual status_t releaseAudioPatch_l(const audio_patch_handle_t handle);
Eric Laurent83b88082014-06-20 18:31:16 -07001115
1116 void addPatchRecord(const sp<PatchRecord>& record);
1117 void deletePatchRecord(const sp<PatchRecord>& record);
1118
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001119 void readInputParameters_l();
Glenn Kasten5f972c02014-01-13 09:59:31 -08001120 virtual uint32_t getInputFramesLost();
Eric Laurent81784c32012-11-19 14:55:58 -08001121
1122 virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
1123 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
1124 virtual uint32_t hasAudioSession(int sessionId) const;
1125
1126 // Return the set of unique session IDs across all tracks.
1127 // The keys are the session IDs, and the associated values are meaningless.
1128 // FIXME replace by Set [and implement Bag/Multiset for other uses].
1129 KeyedVector<int, bool> sessionIds() const;
1130
1131 virtual status_t setSyncEvent(const sp<SyncEvent>& event);
1132 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const;
1133
1134 static void syncStartEventCallback(const wp<SyncEvent>& event);
Eric Laurent81784c32012-11-19 14:55:58 -08001135
Glenn Kasten9b58f632013-07-16 11:37:48 -07001136 virtual size_t frameCount() const { return mFrameCount; }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001137 bool hasFastCapture() const { return mFastCapture != 0; }
Eric Laurent83b88082014-06-20 18:31:16 -07001138 virtual void getAudioPortConfig(struct audio_port_config *config);
Glenn Kasten9b58f632013-07-16 11:37:48 -07001139
Eric Laurent81784c32012-11-19 14:55:58 -08001140private:
Eric Laurent81784c32012-11-19 14:55:58 -08001141 // Enter standby if not already in standby, and set mStandby flag
Glenn Kasten93e471f2013-08-19 08:40:07 -07001142 void standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08001143
1144 // Call the HAL standby method unconditionally, and don't change mStandby flag
Glenn Kastene198c362013-08-13 09:13:36 -07001145 void inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08001146
1147 AudioStreamIn *mInput;
1148 SortedVector < sp<RecordTrack> > mTracks;
Glenn Kasten2b806402013-11-20 16:37:38 -08001149 // mActiveTracks has dual roles: it indicates the current active track(s), and
Eric Laurent81784c32012-11-19 14:55:58 -08001150 // is used together with mStartStopCond to indicate start()/stop() progress
Glenn Kasten2b806402013-11-20 16:37:38 -08001151 SortedVector< sp<RecordTrack> > mActiveTracks;
1152 // generation counter for mActiveTracks
1153 int mActiveTracksGen;
Eric Laurent81784c32012-11-19 14:55:58 -08001154 Condition mStartStopCond;
Glenn Kasten9b58f632013-07-16 11:37:48 -07001155
Glenn Kasten85948432013-08-19 12:09:05 -07001156 // resampler converts input at HAL Hz to output at AudioRecord client Hz
1157 int16_t *mRsmpInBuffer; // see new[] for details on the size
1158 size_t mRsmpInFrames; // size of resampler input in frames
1159 size_t mRsmpInFramesP2;// size rounded up to a power-of-2
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08001160
1161 // rolling index that is never cleared
Glenn Kasten85948432013-08-19 12:09:05 -07001162 int32_t mRsmpInRear; // last filled frame + 1
Glenn Kasten85948432013-08-19 12:09:05 -07001163
Eric Laurent81784c32012-11-19 14:55:58 -08001164 // For dumpsys
1165 const sp<NBAIO_Sink> mTeeSink;
Glenn Kastenb880f5e2014-05-07 08:43:45 -07001166
1167 const sp<MemoryDealer> mReadOnlyHeap;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001168
1169 // one-time initialization, no locks required
Glenn Kastenb187de12014-12-30 08:18:15 -08001170 sp<FastCapture> mFastCapture; // non-0 if there is also
1171 // a fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07001172 // FIXME audio watchdog thread
1173
1174 // contents are not guaranteed to be consistent, no locks required
1175 FastCaptureDumpState mFastCaptureDumpState;
1176#ifdef STATE_QUEUE_DUMP
1177 // FIXME StateQueue observer and mutator dump fields
1178#endif
1179 // FIXME audio watchdog dump
1180
1181 // accessible only within the threadLoop(), no locks required
1182 // mFastCapture->sq() // for mutating and pushing state
1183 int32_t mFastCaptureFutex; // for cold idle
1184
1185 // The HAL input source is treated as non-blocking,
1186 // but current implementation is blocking
1187 sp<NBAIO_Source> mInputSource;
1188 // The source for the normal capture thread to read from: mInputSource or mPipeSource
1189 sp<NBAIO_Source> mNormalSource;
1190 // If a fast capture is present, the non-blocking pipe sink written to by fast capture,
1191 // otherwise clear
1192 sp<NBAIO_Sink> mPipeSink;
1193 // If a fast capture is present, the non-blocking pipe source read by normal thread,
1194 // otherwise clear
1195 sp<NBAIO_Source> mPipeSource;
1196 // Depth of pipe from fast capture to normal thread and fast clients, always power of 2
1197 size_t mPipeFramesP2;
1198 // If a fast capture is present, the Pipe as IMemory, otherwise clear
1199 sp<IMemory> mPipeMemory;
1200
1201 static const size_t kFastCaptureLogSize = 4 * 1024;
1202 sp<NBLog::Writer> mFastCaptureNBLogWriter;
1203
1204 bool mFastTrackAvail; // true if fast track available
Eric Laurent81784c32012-11-19 14:55:58 -08001205};