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