blob: 8036a28319a07e11d8e7f1543bb797c751c0972b [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
Alok Kediya601e9b52013-09-27 11:55:10 +05302** Copyright (c) 2013, The Linux Foundation. All rights reserved.
3** Not a Contribution.
Eric Laurent81784c32012-11-19 14:55:58 -08004** Copyright 2012, The Android Open Source Project
5**
6** Licensed under the Apache License, Version 2.0 (the "License");
7** you may not use this file except in compliance with the License.
8** You may obtain a copy of the License at
9**
10** http://www.apache.org/licenses/LICENSE-2.0
11**
12** Unless required by applicable law or agreed to in writing, software
13** distributed under the License is distributed on an "AS IS" BASIS,
14** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15** See the License for the specific language governing permissions and
16** limitations under the License.
17*/
18
19#ifndef INCLUDING_FROM_AUDIOFLINGER_H
20 #error This header file should only be included from AudioFlinger.h
21#endif
22
23class ThreadBase : public Thread {
24public:
25
26#include "TrackBase.h"
27
28 enum type_t {
29 MIXER, // Thread class is MixerThread
30 DIRECT, // Thread class is DirectOutputThread
31 DUPLICATING, // Thread class is DuplicatingThread
Eric Laurentbfb1b832013-01-07 09:53:42 -080032 RECORD, // Thread class is RecordThread
33 OFFLOAD // Thread class is OffloadThread
Eric Laurent81784c32012-11-19 14:55:58 -080034 };
35
36 ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
37 audio_devices_t outDevice, audio_devices_t inDevice, type_t type);
38 virtual ~ThreadBase();
39
40 void dumpBase(int fd, const Vector<String16>& args);
41 void dumpEffectChains(int fd, const Vector<String16>& args);
42
43 void clearPowerManager();
44
45 // base for record and playback
46 enum {
47 CFG_EVENT_IO,
48 CFG_EVENT_PRIO
49 };
50
51 class ConfigEvent {
52 public:
53 ConfigEvent(int type) : mType(type) {}
54 virtual ~ConfigEvent() {}
55
56 int type() const { return mType; }
57
58 virtual void dump(char *buffer, size_t size) = 0;
59
60 private:
61 const int mType;
62 };
63
64 class IoConfigEvent : public ConfigEvent {
65 public:
66 IoConfigEvent(int event, int param) :
67 ConfigEvent(CFG_EVENT_IO), mEvent(event), mParam(event) {}
68 virtual ~IoConfigEvent() {}
69
70 int event() const { return mEvent; }
71 int param() const { return mParam; }
72
73 virtual void dump(char *buffer, size_t size) {
74 snprintf(buffer, size, "IO event: event %d, param %d\n", mEvent, mParam);
75 }
76
77 private:
78 const int mEvent;
79 const int mParam;
80 };
81
82 class PrioConfigEvent : public ConfigEvent {
83 public:
84 PrioConfigEvent(pid_t pid, pid_t tid, int32_t prio) :
85 ConfigEvent(CFG_EVENT_PRIO), mPid(pid), mTid(tid), mPrio(prio) {}
86 virtual ~PrioConfigEvent() {}
87
88 pid_t pid() const { return mPid; }
89 pid_t tid() const { return mTid; }
90 int32_t prio() const { return mPrio; }
91
92 virtual void dump(char *buffer, size_t size) {
93 snprintf(buffer, size, "Prio event: pid %d, tid %d, prio %d\n", mPid, mTid, mPrio);
94 }
95
96 private:
97 const pid_t mPid;
98 const pid_t mTid;
99 const int32_t mPrio;
100 };
101
102
103 class PMDeathRecipient : public IBinder::DeathRecipient {
104 public:
105 PMDeathRecipient(const wp<ThreadBase>& thread) : mThread(thread) {}
106 virtual ~PMDeathRecipient() {}
107
108 // IBinder::DeathRecipient
109 virtual void binderDied(const wp<IBinder>& who);
110
111 private:
112 PMDeathRecipient(const PMDeathRecipient&);
113 PMDeathRecipient& operator = (const PMDeathRecipient&);
114
115 wp<ThreadBase> mThread;
116 };
117
118 virtual status_t initCheck() const = 0;
119
120 // static externally-visible
121 type_t type() const { return mType; }
122 audio_io_handle_t id() const { return mId;}
123
124 // dynamic externally-visible
125 uint32_t sampleRate() const { return mSampleRate; }
126 uint32_t channelCount() const { return mChannelCount; }
127 audio_channel_mask_t channelMask() const { return mChannelMask; }
128 audio_format_t format() const { return mFormat; }
129 // Called by AudioFlinger::frameCount(audio_io_handle_t output) and effects,
Glenn Kasten9b58f632013-07-16 11:37:48 -0700130 // and returns the [normal mix] buffer's frame count.
131 virtual size_t frameCount() const = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800132 size_t frameSize() const { return mFrameSize; }
Eric Laurent81784c32012-11-19 14:55:58 -0800133
134 // Should be "virtual status_t requestExitAndWait()" and override same
135 // method in Thread, but Thread::requestExitAndWait() is not yet virtual.
136 void exit();
137 virtual bool checkForNewParameters_l() = 0;
138 virtual status_t setParameters(const String8& keyValuePairs);
139 virtual String8 getParameters(const String8& keys) = 0;
140 virtual void audioConfigChanged_l(int event, int param = 0) = 0;
Ethan Chen8d420ed2013-11-14 00:40:54 -0800141#ifdef QCOM_HARDWARE
Alok Kediya601e9b52013-09-27 11:55:10 +0530142 void effectConfigChanged();
Ethan Chen8d420ed2013-11-14 00:40:54 -0800143#endif
Eric Laurent81784c32012-11-19 14:55:58 -0800144 void sendIoConfigEvent(int event, int param = 0);
145 void sendIoConfigEvent_l(int event, int param = 0);
146 void sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio);
147 void processConfigEvents();
148
149 // see note at declaration of mStandby, mOutDevice and mInDevice
150 bool standby() const { return mStandby; }
151 audio_devices_t outDevice() const { return mOutDevice; }
152 audio_devices_t inDevice() const { return mInDevice; }
153
154 virtual audio_stream_t* stream() const = 0;
155
156 sp<EffectHandle> createEffect_l(
157 const sp<AudioFlinger::Client>& client,
158 const sp<IEffectClient>& effectClient,
159 int32_t priority,
160 int sessionId,
161 effect_descriptor_t *desc,
162 int *enabled,
163 status_t *status);
164 void disconnectEffect(const sp< EffectModule>& effect,
165 EffectHandle *handle,
166 bool unpinIfLast);
167
168 // return values for hasAudioSession (bit field)
169 enum effect_state {
170 EFFECT_SESSION = 0x1, // the audio session corresponds to at least one
171 // effect
172 TRACK_SESSION = 0x2 // the audio session corresponds to at least one
173 // track
174 };
175
176 // get effect chain corresponding to session Id.
177 sp<EffectChain> getEffectChain(int sessionId);
178 // same as getEffectChain() but must be called with ThreadBase mutex locked
179 sp<EffectChain> getEffectChain_l(int sessionId) const;
180 // add an effect chain to the chain list (mEffectChains)
181 virtual status_t addEffectChain_l(const sp<EffectChain>& chain) = 0;
182 // remove an effect chain from the chain list (mEffectChains)
183 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain) = 0;
184 // lock all effect chains Mutexes. Must be called before releasing the
185 // ThreadBase mutex before processing the mixer and effects. This guarantees the
186 // integrity of the chains during the process.
187 // Also sets the parameter 'effectChains' to current value of mEffectChains.
188 void lockEffectChains_l(Vector< sp<EffectChain> >& effectChains);
189 // unlock effect chains after process
190 void unlockEffectChains(const Vector< sp<EffectChain> >& effectChains);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800191 // get a copy of mEffectChains vector
192 Vector< sp<EffectChain> > getEffectChains_l() const { return mEffectChains; };
Eric Laurent81784c32012-11-19 14:55:58 -0800193 // set audio mode to all effect chains
194 void setMode(audio_mode_t mode);
195 // get effect module with corresponding ID on specified audio session
196 sp<AudioFlinger::EffectModule> getEffect(int sessionId, int effectId);
197 sp<AudioFlinger::EffectModule> getEffect_l(int sessionId, int effectId);
198 // add and effect module. Also creates the effect chain is none exists for
199 // the effects audio session
200 status_t addEffect_l(const sp< EffectModule>& effect);
201 // remove and effect module. Also removes the effect chain is this was the last
202 // effect
203 void removeEffect_l(const sp< EffectModule>& effect);
204 // detach all tracks connected to an auxiliary effect
205 virtual void detachAuxEffect_l(int effectId) {}
206 // returns either EFFECT_SESSION if effects on this audio session exist in one
207 // chain, or TRACK_SESSION if tracks on this audio session exist, or both
208 virtual uint32_t hasAudioSession(int sessionId) const = 0;
209 // the value returned by default implementation is not important as the
210 // strategy is only meaningful for PlaybackThread which implements this method
211 virtual uint32_t getStrategyForSession_l(int sessionId) { return 0; }
212
213 // suspend or restore effect according to the type of effect passed. a NULL
214 // type pointer means suspend all effects in the session
215 void setEffectSuspended(const effect_uuid_t *type,
216 bool suspend,
217 int sessionId = AUDIO_SESSION_OUTPUT_MIX);
218 // check if some effects must be suspended/restored when an effect is enabled
219 // or disabled
220 void checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
221 bool enabled,
222 int sessionId = AUDIO_SESSION_OUTPUT_MIX);
223 void checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
224 bool enabled,
225 int sessionId = AUDIO_SESSION_OUTPUT_MIX);
226
227 virtual status_t setSyncEvent(const sp<SyncEvent>& event) = 0;
228 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const = 0;
229
230
231 mutable Mutex mLock;
232
233protected:
234
235 // entry describing an effect being suspended in mSuspendedSessions keyed vector
236 class SuspendedSessionDesc : public RefBase {
237 public:
238 SuspendedSessionDesc() : mRefCount(0) {}
239
240 int mRefCount; // number of active suspend requests
241 effect_uuid_t mType; // effect type UUID
242 };
243
Marco Nelissene14a5d62013-10-03 08:51:24 -0700244 void acquireWakeLock(int uid = -1);
245 void acquireWakeLock_l(int uid = -1);
Eric Laurent81784c32012-11-19 14:55:58 -0800246 void releaseWakeLock();
247 void releaseWakeLock_l();
Marco Nelissen9cae2172013-01-14 14:12:05 -0800248 void updateWakeLockUids(const SortedVector<int> &uids);
249 void updateWakeLockUids_l(const SortedVector<int> &uids);
250 void getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800251 void setEffectSuspended_l(const effect_uuid_t *type,
252 bool suspend,
253 int sessionId);
254 // updated mSuspendedSessions when an effect suspended or restored
255 void updateSuspendedSessions_l(const effect_uuid_t *type,
256 bool suspend,
257 int sessionId);
258 // check if some effects must be suspended when an effect chain is added
259 void checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain);
260
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100261 String16 getWakeLockTag();
262
Eric Laurent81784c32012-11-19 14:55:58 -0800263 virtual void preExit() { }
264
265 friend class AudioFlinger; // for mEffectChains
266
267 const type_t mType;
268
269 // Used by parameters, config events, addTrack_l, exit
270 Condition mWaitWorkCV;
271
272 const sp<AudioFlinger> mAudioFlinger;
Glenn Kasten9b58f632013-07-16 11:37:48 -0700273
274 // updated by PlaybackThread::readOutputParameters() or
275 // RecordThread::readInputParameters()
Eric Laurent81784c32012-11-19 14:55:58 -0800276 uint32_t mSampleRate;
277 size_t mFrameCount; // output HAL, direct output, record
Eric Laurent81784c32012-11-19 14:55:58 -0800278 audio_channel_mask_t mChannelMask;
Glenn Kastenf6ed4232013-07-16 11:16:27 -0700279 uint32_t mChannelCount;
Eric Laurent81784c32012-11-19 14:55:58 -0800280 size_t mFrameSize;
281 audio_format_t mFormat;
282
283 // Parameter sequence by client: binder thread calling setParameters():
284 // 1. Lock mLock
285 // 2. Append to mNewParameters
286 // 3. mWaitWorkCV.signal
287 // 4. mParamCond.waitRelative with timeout
288 // 5. read mParamStatus
289 // 6. mWaitWorkCV.signal
290 // 7. Unlock
291 //
292 // Parameter sequence by server: threadLoop calling checkForNewParameters_l():
293 // 1. Lock mLock
294 // 2. If there is an entry in mNewParameters proceed ...
295 // 2. Read first entry in mNewParameters
296 // 3. Process
297 // 4. Remove first entry from mNewParameters
298 // 5. Set mParamStatus
299 // 6. mParamCond.signal
300 // 7. mWaitWorkCV.wait with timeout (this is to avoid overwriting mParamStatus)
301 // 8. Unlock
302 Condition mParamCond;
303 Vector<String8> mNewParameters;
304 status_t mParamStatus;
305
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700306 // vector owns each ConfigEvent *, so must delete after removing
Eric Laurent81784c32012-11-19 14:55:58 -0800307 Vector<ConfigEvent *> mConfigEvents;
308
309 // These fields are written and read by thread itself without lock or barrier,
310 // and read by other threads without lock or barrier via standby() , outDevice()
311 // and inDevice().
312 // Because of the absence of a lock or barrier, any other thread that reads
313 // these fields must use the information in isolation, or be prepared to deal
314 // with possibility that it might be inconsistent with other information.
315 bool mStandby; // Whether thread is currently in standby.
316 audio_devices_t mOutDevice; // output device
317 audio_devices_t mInDevice; // input device
318 audio_source_t mAudioSource; // (see audio.h, audio_source_t)
319
320 const audio_io_handle_t mId;
321 Vector< sp<EffectChain> > mEffectChains;
322
323 static const int kNameLength = 16; // prctl(PR_SET_NAME) limit
324 char mName[kNameLength];
325 sp<IPowerManager> mPowerManager;
326 sp<IBinder> mWakeLockToken;
327 const sp<PMDeathRecipient> mDeathRecipient;
328 // list of suspended effects per session and per type. The first vector is
329 // keyed by session ID, the second by type UUID timeLow field
330 KeyedVector< int, KeyedVector< int, sp<SuspendedSessionDesc> > >
331 mSuspendedSessions;
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800332 static const size_t kLogSize = 4 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -0800333 sp<NBLog::Writer> mNBLogWriter;
Eric Laurent81784c32012-11-19 14:55:58 -0800334};
335
336// --- PlaybackThread ---
337class PlaybackThread : public ThreadBase {
338public:
339
340#include "PlaybackTracks.h"
341
342 enum mixer_state {
343 MIXER_IDLE, // no active tracks
344 MIXER_TRACKS_ENABLED, // at least one active track, but no track has any data ready
Eric Laurentbfb1b832013-01-07 09:53:42 -0800345 MIXER_TRACKS_READY, // at least one active track, and at least one track has data
346 MIXER_DRAIN_TRACK, // drain currently playing track
347 MIXER_DRAIN_ALL, // fully drain the hardware
Eric Laurent81784c32012-11-19 14:55:58 -0800348 // standby mode does not have an enum value
349 // suspend by audio policy manager is orthogonal to mixer state
350 };
351
Eric Laurentbfb1b832013-01-07 09:53:42 -0800352 // retry count before removing active track in case of underrun on offloaded thread:
353 // we need to make sure that AudioTrack client has enough time to send large buffers
354//FIXME may be more appropriate if expressed in time units. Need to revise how underrun is handled
355 // for offloaded tracks
356 static const int8_t kMaxTrackRetriesOffload = 20;
357
Eric Laurent81784c32012-11-19 14:55:58 -0800358 PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
359 audio_io_handle_t id, audio_devices_t device, type_t type);
360 virtual ~PlaybackThread();
361
362 void dump(int fd, const Vector<String16>& args);
363
364 // Thread virtuals
365 virtual status_t readyToRun();
366 virtual bool threadLoop();
367
368 // RefBase
369 virtual void onFirstRef();
370
371protected:
372 // Code snippets that were lifted up out of threadLoop()
373 virtual void threadLoop_mix() = 0;
374 virtual void threadLoop_sleepTime() = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800375 virtual ssize_t threadLoop_write();
376 virtual void threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -0800377 virtual void threadLoop_standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800378 virtual void threadLoop_exit();
Eric Laurent81784c32012-11-19 14:55:58 -0800379 virtual void threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
380
381 // prepareTracks_l reads and writes mActiveTracks, and returns
382 // the pending set of tracks to remove via Vector 'tracksToRemove'. The caller
383 // is responsible for clearing or destroying this Vector later on, when it
384 // is safe to do so. That will drop the final ref count and destroy the tracks.
385 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove) = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800386 void removeTracks_l(const Vector< sp<Track> >& tracksToRemove);
387
388 void writeCallback();
Eric Laurent3b4529e2013-09-05 18:09:19 -0700389 void resetWriteBlocked(uint32_t sequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800390 void drainCallback();
Eric Laurent3b4529e2013-09-05 18:09:19 -0700391 void resetDraining(uint32_t sequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800392
393 static int asyncCallback(stream_callback_event_t event, void *param, void *cookie);
394
395 virtual bool waitingAsyncCallback();
396 virtual bool waitingAsyncCallback_l();
397 virtual bool shouldStandby_l();
398
Eric Laurent81784c32012-11-19 14:55:58 -0800399
400 // ThreadBase virtuals
401 virtual void preExit();
402
403public:
404
405 virtual status_t initCheck() const { return (mOutput == NULL) ? NO_INIT : NO_ERROR; }
406
407 // return estimated latency in milliseconds, as reported by HAL
408 uint32_t latency() const;
409 // same, but lock must already be held
410 uint32_t latency_l() const;
411
412 void setMasterVolume(float value);
413 void setMasterMute(bool muted);
414
415 void setStreamVolume(audio_stream_type_t stream, float value);
416 void setStreamMute(audio_stream_type_t stream, bool muted);
417
418 float streamVolume(audio_stream_type_t stream) const;
419
420 sp<Track> createTrack_l(
421 const sp<AudioFlinger::Client>& client,
422 audio_stream_type_t streamType,
423 uint32_t sampleRate,
424 audio_format_t format,
425 audio_channel_mask_t channelMask,
426 size_t frameCount,
427 const sp<IMemory>& sharedBuffer,
428 int sessionId,
429 IAudioFlinger::track_flags_t *flags,
430 pid_t tid,
Marco Nelissen9cae2172013-01-14 14:12:05 -0800431 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -0800432 status_t *status);
433
434 AudioStreamOut* getOutput() const;
435 AudioStreamOut* clearOutput();
436 virtual audio_stream_t* stream() const;
437
438 // a very large number of suspend() will eventually wraparound, but unlikely
439 void suspend() { (void) android_atomic_inc(&mSuspended); }
440 void restore()
441 {
442 // if restore() is done without suspend(), get back into
443 // range so that the next suspend() will operate correctly
444 if (android_atomic_dec(&mSuspended) <= 0) {
445 android_atomic_release_store(0, &mSuspended);
446 }
447 }
448 bool isSuspended() const
449 { return android_atomic_acquire_load(&mSuspended) > 0; }
450
451 virtual String8 getParameters(const String8& keys);
452 virtual void audioConfigChanged_l(int event, int param = 0);
453 status_t getRenderPosition(size_t *halFrames, size_t *dspFrames);
454 int16_t *mixBuffer() const { return mMixBuffer; };
455
456 virtual void detachAuxEffect_l(int effectId);
457 status_t attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track> track,
458 int EffectId);
459 status_t attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track> track,
460 int EffectId);
461
462 virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
463 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
464 virtual uint32_t hasAudioSession(int sessionId) const;
465 virtual uint32_t getStrategyForSession_l(int sessionId);
466
467
468 virtual status_t setSyncEvent(const sp<SyncEvent>& event);
469 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const;
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700470
471 // called with AudioFlinger lock held
Eric Laurent81784c32012-11-19 14:55:58 -0800472 void invalidateTracks(audio_stream_type_t streamType);
473
Glenn Kasten9b58f632013-07-16 11:37:48 -0700474 virtual size_t frameCount() const { return mNormalFrameCount; }
475
476 // Return's the HAL's frame count i.e. fast mixer buffer size.
477 size_t frameCountHAL() const { return mFrameCount; }
Eric Laurent81784c32012-11-19 14:55:58 -0800478
Eric Laurentaccc1472013-09-20 09:36:34 -0700479 status_t getTimestamp_l(AudioTimestamp& timestamp);
480
Eric Laurent81784c32012-11-19 14:55:58 -0800481protected:
Glenn Kasten9b58f632013-07-16 11:37:48 -0700482 // updated by readOutputParameters()
483 size_t mNormalFrameCount; // normal mixer and effects
484
Eric Laurentbfb1b832013-01-07 09:53:42 -0800485 int16_t* mMixBuffer; // frame size aligned mix buffer
486 int8_t* mAllocMixBuffer; // mixer buffer allocation address
Eric Laurent81784c32012-11-19 14:55:58 -0800487
488 // suspend count, > 0 means suspended. While suspended, the thread continues to pull from
489 // tracks and mix, but doesn't write to HAL. A2DP and SCO HAL implementations can't handle
490 // concurrent use of both of them, so Audio Policy Service suspends one of the threads to
491 // workaround that restriction.
492 // 'volatile' means accessed via atomic operations and no lock.
493 volatile int32_t mSuspended;
494
495 // FIXME overflows every 6+ hours at 44.1 kHz stereo 16-bit samples
496 // mFramesWritten would be better, or 64-bit even better
497 size_t mBytesWritten;
498private:
499 // mMasterMute is in both PlaybackThread and in AudioFlinger. When a
500 // PlaybackThread needs to find out if master-muted, it checks it's local
501 // copy rather than the one in AudioFlinger. This optimization saves a lock.
502 bool mMasterMute;
503 void setMasterMute_l(bool muted) { mMasterMute = muted; }
504protected:
505 SortedVector< wp<Track> > mActiveTracks; // FIXME check if this could be sp<>
Marco Nelissen9cae2172013-01-14 14:12:05 -0800506 SortedVector<int> mWakeLockUids;
507 int mActiveTracksGeneration;
Eric Laurentfd477972013-10-25 18:10:40 -0700508 wp<Track> mLatestActiveTrack; // latest track added to mActiveTracks
Eric Laurent81784c32012-11-19 14:55:58 -0800509
510 // Allocate a track name for a given channel mask.
511 // Returns name >= 0 if successful, -1 on failure.
512 virtual int getTrackName_l(audio_channel_mask_t channelMask, int sessionId) = 0;
513 virtual void deleteTrackName_l(int name) = 0;
514
515 // Time to sleep between cycles when:
516 virtual uint32_t activeSleepTimeUs() const; // mixer state MIXER_TRACKS_ENABLED
517 virtual uint32_t idleSleepTimeUs() const = 0; // mixer state MIXER_IDLE
518 virtual uint32_t suspendSleepTimeUs() const = 0; // audio policy manager suspended us
519 // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write()
520 // No sleep in standby mode; waits on a condition
521
522 // Code snippets that are temporarily lifted up out of threadLoop() until the merge
523 void checkSilentMode_l();
524
525 // Non-trivial for DUPLICATING only
526 virtual void saveOutputTracks() { }
527 virtual void clearOutputTracks() { }
528
529 // Cache various calculated values, at threadLoop() entry and after a parameter change
530 virtual void cacheParameters_l();
531
532 virtual uint32_t correctLatency_l(uint32_t latency) const;
533
534private:
535
536 friend class AudioFlinger; // for numerous
537
538 PlaybackThread(const Client&);
539 PlaybackThread& operator = (const PlaybackThread&);
540
541 status_t addTrack_l(const sp<Track>& track);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800542 bool destroyTrack_l(const sp<Track>& track);
Eric Laurent81784c32012-11-19 14:55:58 -0800543 void removeTrack_l(const sp<Track>& track);
Eric Laurentede6c3b2013-09-19 14:37:46 -0700544 void broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800545
546 void readOutputParameters();
547
548 virtual void dumpInternals(int fd, const Vector<String16>& args);
549 void dumpTracks(int fd, const Vector<String16>& args);
550
551 SortedVector< sp<Track> > mTracks;
552 // mStreamTypes[] uses 1 additional stream type internally for the OutputTrack used by
553 // DuplicatingThread
554 stream_type_t mStreamTypes[AUDIO_STREAM_CNT + 1];
555 AudioStreamOut *mOutput;
556
557 float mMasterVolume;
558 nsecs_t mLastWriteTime;
559 int mNumWrites;
560 int mNumDelayedWrites;
561 bool mInWrite;
562
563 // FIXME rename these former local variables of threadLoop to standard "m" names
564 nsecs_t standbyTime;
565 size_t mixBufferSize;
566
567 // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l()
568 uint32_t activeSleepTime;
569 uint32_t idleSleepTime;
570
571 uint32_t sleepTime;
572
573 // mixer status returned by prepareTracks_l()
574 mixer_state mMixerStatus; // current cycle
575 // previous cycle when in prepareTracks_l()
576 mixer_state mMixerStatusIgnoringFastTracks;
577 // FIXME or a separate ready state per track
578
579 // FIXME move these declarations into the specific sub-class that needs them
580 // MIXER only
581 uint32_t sleepTimeShift;
582
583 // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value
584 nsecs_t standbyDelay;
585
586 // MIXER only
587 nsecs_t maxPeriod;
588
589 // DUPLICATING only
590 uint32_t writeFrames;
591
Eric Laurentbfb1b832013-01-07 09:53:42 -0800592 size_t mBytesRemaining;
593 size_t mCurrentWriteLength;
594 bool mUseAsyncWrite;
Eric Laurent3b4529e2013-09-05 18:09:19 -0700595 // mWriteAckSequence contains current write sequence on bits 31-1. The write sequence is
596 // incremented each time a write(), a flush() or a standby() occurs.
597 // Bit 0 is set when a write blocks and indicates a callback is expected.
598 // Bit 0 is reset by the async callback thread calling resetWriteBlocked(). Out of sequence
599 // callbacks are ignored.
600 uint32_t mWriteAckSequence;
601 // mDrainSequence contains current drain sequence on bits 31-1. The drain sequence is
602 // incremented each time a drain is requested or a flush() or standby() occurs.
603 // Bit 0 is set when the drain() command is called at the HAL and indicates a callback is
604 // expected.
605 // Bit 0 is reset by the async callback thread calling resetDraining(). Out of sequence
606 // callbacks are ignored.
607 uint32_t mDrainSequence;
Eric Laurentede6c3b2013-09-19 14:37:46 -0700608 // A condition that must be evaluated by prepareTrack_l() has changed and we must not wait
609 // for async write callback in the thread loop before evaluating it
Eric Laurentbfb1b832013-01-07 09:53:42 -0800610 bool mSignalPending;
611 sp<AsyncCallbackThread> mCallbackThread;
612
Eric Laurent81784c32012-11-19 14:55:58 -0800613private:
614 // The HAL output sink is treated as non-blocking, but current implementation is blocking
615 sp<NBAIO_Sink> mOutputSink;
616 // If a fast mixer is present, the blocking pipe sink, otherwise clear
617 sp<NBAIO_Sink> mPipeSink;
618 // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink
619 sp<NBAIO_Sink> mNormalSink;
Glenn Kasten46909e72013-02-26 09:20:22 -0800620#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -0800621 // For dumpsys
622 sp<NBAIO_Sink> mTeeSink;
623 sp<NBAIO_Source> mTeeSource;
Glenn Kasten46909e72013-02-26 09:20:22 -0800624#endif
Eric Laurent81784c32012-11-19 14:55:58 -0800625 uint32_t mScreenState; // cached copy of gScreenState
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800626 static const size_t kFastMixerLogSize = 4 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -0800627 sp<NBLog::Writer> mFastMixerNBLogWriter;
Eric Laurent81784c32012-11-19 14:55:58 -0800628public:
629 virtual bool hasFastMixer() const = 0;
630 virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const
631 { FastTrackUnderruns dummy; return dummy; }
632
633protected:
634 // accessed by both binder threads and within threadLoop(), lock on mutex needed
635 unsigned mFastTrackAvailMask; // bit i set if fast track [i] is available
Eric Laurentbfb1b832013-01-07 09:53:42 -0800636 virtual void flushOutput_l();
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700637
638private:
639 // timestamp latch:
640 // D input is written by threadLoop_write while mutex is unlocked, and read while locked
641 // Q output is written while locked, and read while locked
642 struct {
643 AudioTimestamp mTimestamp;
644 uint32_t mUnpresentedFrames;
645 } mLatchD, mLatchQ;
646 bool mLatchDValid; // true means mLatchD is valid, and clock it into latch at next opportunity
647 bool mLatchQValid; // true means mLatchQ is valid
Eric Laurent81784c32012-11-19 14:55:58 -0800648};
649
650class MixerThread : public PlaybackThread {
651public:
652 MixerThread(const sp<AudioFlinger>& audioFlinger,
653 AudioStreamOut* output,
654 audio_io_handle_t id,
655 audio_devices_t device,
656 type_t type = MIXER);
657 virtual ~MixerThread();
658
659 // Thread virtuals
660
661 virtual bool checkForNewParameters_l();
662 virtual void dumpInternals(int fd, const Vector<String16>& args);
663
664protected:
665 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
666 virtual int getTrackName_l(audio_channel_mask_t channelMask, int sessionId);
667 virtual void deleteTrackName_l(int name);
668 virtual uint32_t idleSleepTimeUs() const;
669 virtual uint32_t suspendSleepTimeUs() const;
670 virtual void cacheParameters_l();
671
672 // threadLoop snippets
Eric Laurentbfb1b832013-01-07 09:53:42 -0800673 virtual ssize_t threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -0800674 virtual void threadLoop_standby();
675 virtual void threadLoop_mix();
676 virtual void threadLoop_sleepTime();
677 virtual void threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
678 virtual uint32_t correctLatency_l(uint32_t latency) const;
679
680 AudioMixer* mAudioMixer; // normal mixer
681private:
682 // one-time initialization, no locks required
683 FastMixer* mFastMixer; // non-NULL if there is also a fast mixer
684 sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread
685
686 // contents are not guaranteed to be consistent, no locks required
687 FastMixerDumpState mFastMixerDumpState;
688#ifdef STATE_QUEUE_DUMP
689 StateQueueObserverDump mStateQueueObserverDump;
690 StateQueueMutatorDump mStateQueueMutatorDump;
691#endif
692 AudioWatchdogDump mAudioWatchdogDump;
693
694 // accessible only within the threadLoop(), no locks required
695 // mFastMixer->sq() // for mutating and pushing state
696 int32_t mFastMixerFutex; // for cold idle
697
698public:
699 virtual bool hasFastMixer() const { return mFastMixer != NULL; }
700 virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const {
701 ALOG_ASSERT(fastIndex < FastMixerState::kMaxFastTracks);
702 return mFastMixerDumpState.mTracks[fastIndex].mUnderruns;
703 }
704};
705
706class DirectOutputThread : public PlaybackThread {
707public:
708
709 DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
710 audio_io_handle_t id, audio_devices_t device);
711 virtual ~DirectOutputThread();
712
713 // Thread virtuals
714
715 virtual bool checkForNewParameters_l();
716
717protected:
718 virtual int getTrackName_l(audio_channel_mask_t channelMask, int sessionId);
719 virtual void deleteTrackName_l(int name);
720 virtual uint32_t activeSleepTimeUs() const;
721 virtual uint32_t idleSleepTimeUs() const;
722 virtual uint32_t suspendSleepTimeUs() const;
723 virtual void cacheParameters_l();
724
725 // threadLoop snippets
726 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
727 virtual void threadLoop_mix();
728 virtual void threadLoop_sleepTime();
729
Eric Laurent81784c32012-11-19 14:55:58 -0800730 // volumes last sent to audio HAL with stream->set_volume()
731 float mLeftVolFloat;
732 float mRightVolFloat;
733
Eric Laurentbfb1b832013-01-07 09:53:42 -0800734 DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
735 audio_io_handle_t id, uint32_t device, ThreadBase::type_t type);
736 void processVolume_l(Track *track, bool lastTrack);
737
Eric Laurent81784c32012-11-19 14:55:58 -0800738 // prepareTracks_l() tells threadLoop_mix() the name of the single active track
739 sp<Track> mActiveTrack;
740public:
741 virtual bool hasFastMixer() const { return false; }
742};
743
Eric Laurentbfb1b832013-01-07 09:53:42 -0800744class OffloadThread : public DirectOutputThread {
745public:
746
747 OffloadThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
748 audio_io_handle_t id, uint32_t device);
Eric Laurent6a99d202013-10-17 18:59:26 -0700749 virtual ~OffloadThread() {};
Eric Laurentbfb1b832013-01-07 09:53:42 -0800750
751protected:
752 // threadLoop snippets
753 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
754 virtual void threadLoop_exit();
755 virtual void flushOutput_l();
756
757 virtual bool waitingAsyncCallback();
758 virtual bool waitingAsyncCallback_l();
759 virtual bool shouldStandby_l();
760
761private:
762 void flushHw_l();
763
764private:
765 bool mHwPaused;
766 bool mFlushPending;
767 size_t mPausedWriteLength; // length in bytes of write interrupted by pause
768 size_t mPausedBytesRemaining; // bytes still waiting in mixbuffer after resume
Eric Laurentd7e59222013-11-15 12:02:28 -0800769 wp<Track> mPreviousTrack; // used to detect track switch
Eric Laurentbfb1b832013-01-07 09:53:42 -0800770};
771
772class AsyncCallbackThread : public Thread {
773public:
774
Eric Laurent4de95592013-09-26 15:28:21 -0700775 AsyncCallbackThread(const wp<PlaybackThread>& playbackThread);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800776
777 virtual ~AsyncCallbackThread();
778
779 // Thread virtuals
780 virtual bool threadLoop();
781
782 // RefBase
783 virtual void onFirstRef();
784
785 void exit();
Eric Laurent3b4529e2013-09-05 18:09:19 -0700786 void setWriteBlocked(uint32_t sequence);
787 void resetWriteBlocked();
788 void setDraining(uint32_t sequence);
789 void resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800790
791private:
Eric Laurent4de95592013-09-26 15:28:21 -0700792 const wp<PlaybackThread> mPlaybackThread;
Eric Laurent3b4529e2013-09-05 18:09:19 -0700793 // mWriteAckSequence corresponds to the last write sequence passed by the offload thread via
794 // setWriteBlocked(). The sequence is shifted one bit to the left and the lsb is used
795 // to indicate that the callback has been received via resetWriteBlocked()
Eric Laurent4de95592013-09-26 15:28:21 -0700796 uint32_t mWriteAckSequence;
Eric Laurent3b4529e2013-09-05 18:09:19 -0700797 // mDrainSequence corresponds to the last drain sequence passed by the offload thread via
798 // setDraining(). The sequence is shifted one bit to the left and the lsb is used
799 // to indicate that the callback has been received via resetDraining()
Eric Laurent4de95592013-09-26 15:28:21 -0700800 uint32_t mDrainSequence;
801 Condition mWaitWorkCV;
802 Mutex mLock;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800803};
804
Eric Laurent81784c32012-11-19 14:55:58 -0800805class DuplicatingThread : public MixerThread {
806public:
807 DuplicatingThread(const sp<AudioFlinger>& audioFlinger, MixerThread* mainThread,
808 audio_io_handle_t id);
809 virtual ~DuplicatingThread();
810
811 // Thread virtuals
812 void addOutputTrack(MixerThread* thread);
813 void removeOutputTrack(MixerThread* thread);
814 uint32_t waitTimeMs() const { return mWaitTimeMs; }
815protected:
816 virtual uint32_t activeSleepTimeUs() const;
817
818private:
819 bool outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks);
820protected:
821 // threadLoop snippets
822 virtual void threadLoop_mix();
823 virtual void threadLoop_sleepTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800824 virtual ssize_t threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -0800825 virtual void threadLoop_standby();
826 virtual void cacheParameters_l();
827
828private:
829 // called from threadLoop, addOutputTrack, removeOutputTrack
830 virtual void updateWaitTime_l();
831protected:
832 virtual void saveOutputTracks();
833 virtual void clearOutputTracks();
834private:
835
836 uint32_t mWaitTimeMs;
837 SortedVector < sp<OutputTrack> > outputTracks;
838 SortedVector < sp<OutputTrack> > mOutputTracks;
839public:
840 virtual bool hasFastMixer() const { return false; }
841};
842
843
844// record thread
845class RecordThread : public ThreadBase, public AudioBufferProvider
846 // derives from AudioBufferProvider interface for use by resampler
847{
848public:
849
850#include "RecordTracks.h"
851
852 RecordThread(const sp<AudioFlinger>& audioFlinger,
853 AudioStreamIn *input,
854 uint32_t sampleRate,
855 audio_channel_mask_t channelMask,
856 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -0800857 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -0800858 audio_devices_t inDevice
859#ifdef TEE_SINK
860 , const sp<NBAIO_Sink>& teeSink
861#endif
862 );
Eric Laurent81784c32012-11-19 14:55:58 -0800863 virtual ~RecordThread();
864
865 // no addTrack_l ?
866 void destroyTrack_l(const sp<RecordTrack>& track);
867 void removeTrack_l(const sp<RecordTrack>& track);
868
869 void dumpInternals(int fd, const Vector<String16>& args);
870 void dumpTracks(int fd, const Vector<String16>& args);
871
872 // Thread virtuals
873 virtual bool threadLoop();
874 virtual status_t readyToRun();
875
876 // RefBase
877 virtual void onFirstRef();
878
879 virtual status_t initCheck() const { return (mInput == NULL) ? NO_INIT : NO_ERROR; }
880 sp<AudioFlinger::RecordThread::RecordTrack> createRecordTrack_l(
881 const sp<AudioFlinger::Client>& client,
882 uint32_t sampleRate,
883 audio_format_t format,
884 audio_channel_mask_t channelMask,
885 size_t frameCount,
886 int sessionId,
Marco Nelissen9cae2172013-01-14 14:12:05 -0800887 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -0700888 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -0800889 pid_t tid,
890 status_t *status);
891
892 status_t start(RecordTrack* recordTrack,
893 AudioSystem::sync_event_t event,
894 int triggerSession);
895
896 // ask the thread to stop the specified track, and
897 // return true if the caller should then do it's part of the stopping process
Glenn Kastena8356f62013-07-25 14:37:52 -0700898 bool stop(RecordTrack* recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -0800899
900 void dump(int fd, const Vector<String16>& args);
901 AudioStreamIn* clearInput();
902 virtual audio_stream_t* stream() const;
903
904 // AudioBufferProvider interface
905 virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts);
906 virtual void releaseBuffer(AudioBufferProvider::Buffer* buffer);
907
908 virtual bool checkForNewParameters_l();
909 virtual String8 getParameters(const String8& keys);
910 virtual void audioConfigChanged_l(int event, int param = 0);
911 void readInputParameters();
912 virtual unsigned int getInputFramesLost();
913
914 virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
915 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
916 virtual uint32_t hasAudioSession(int sessionId) const;
917
918 // Return the set of unique session IDs across all tracks.
919 // The keys are the session IDs, and the associated values are meaningless.
920 // FIXME replace by Set [and implement Bag/Multiset for other uses].
921 KeyedVector<int, bool> sessionIds() const;
922
923 virtual status_t setSyncEvent(const sp<SyncEvent>& event);
924 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const;
925
926 static void syncStartEventCallback(const wp<SyncEvent>& event);
927 void handleSyncStartEvent(const sp<SyncEvent>& event);
928
Glenn Kasten9b58f632013-07-16 11:37:48 -0700929 virtual size_t frameCount() const { return mFrameCount; }
Glenn Kasten90e58b12013-07-31 16:16:02 -0700930 bool hasFastRecorder() const { return false; }
Glenn Kasten9b58f632013-07-16 11:37:48 -0700931
Eric Laurent81784c32012-11-19 14:55:58 -0800932private:
933 void clearSyncStartEvent();
934
935 // Enter standby if not already in standby, and set mStandby flag
936 void standby();
937
938 // Call the HAL standby method unconditionally, and don't change mStandby flag
939 void inputStandBy();
940
941 AudioStreamIn *mInput;
942 SortedVector < sp<RecordTrack> > mTracks;
943 // mActiveTrack has dual roles: it indicates the current active track, and
944 // is used together with mStartStopCond to indicate start()/stop() progress
945 sp<RecordTrack> mActiveTrack;
946 Condition mStartStopCond;
Glenn Kasten9b58f632013-07-16 11:37:48 -0700947
948 // updated by RecordThread::readInputParameters()
Eric Laurent81784c32012-11-19 14:55:58 -0800949 AudioResampler *mResampler;
Glenn Kasten34af0262013-07-30 11:52:39 -0700950 // interleaved stereo pairs of fixed-point signed Q19.12
Eric Laurent81784c32012-11-19 14:55:58 -0800951 int32_t *mRsmpOutBuffer;
Glenn Kasten34af0262013-07-30 11:52:39 -0700952 int16_t *mRsmpInBuffer; // [mFrameCount * mChannelCount]
Eric Laurent81784c32012-11-19 14:55:58 -0800953 size_t mRsmpInIndex;
Glenn Kasten548efc92012-11-29 08:48:51 -0800954 size_t mBufferSize; // stream buffer size for read()
Eric Laurent81784c32012-11-19 14:55:58 -0800955 const uint32_t mReqChannelCount;
956 const uint32_t mReqSampleRate;
957 ssize_t mBytesRead;
958 // sync event triggering actual audio capture. Frames read before this event will
959 // be dropped and therefore not read by the application.
960 sp<SyncEvent> mSyncStartEvent;
961 // number of captured frames to drop after the start sync event has been received.
962 // when < 0, maximum frames to drop before starting capture even if sync event is
963 // not received
964 ssize_t mFramestoDrop;
965
966 // For dumpsys
967 const sp<NBAIO_Sink> mTeeSink;
Eric Laurent81784c32012-11-19 14:55:58 -0800968};