blob: e15d98adeeafd435b96e63cc4f4c3b91942f5f9e [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
31 RECORD // Thread class is RecordThread
32 };
33
34 ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
35 audio_devices_t outDevice, audio_devices_t inDevice, type_t type);
36 virtual ~ThreadBase();
37
38 void dumpBase(int fd, const Vector<String16>& args);
39 void dumpEffectChains(int fd, const Vector<String16>& args);
40
41 void clearPowerManager();
42
43 // base for record and playback
44 enum {
45 CFG_EVENT_IO,
46 CFG_EVENT_PRIO
47 };
48
49 class ConfigEvent {
50 public:
51 ConfigEvent(int type) : mType(type) {}
52 virtual ~ConfigEvent() {}
53
54 int type() const { return mType; }
55
56 virtual void dump(char *buffer, size_t size) = 0;
57
58 private:
59 const int mType;
60 };
61
62 class IoConfigEvent : public ConfigEvent {
63 public:
64 IoConfigEvent(int event, int param) :
65 ConfigEvent(CFG_EVENT_IO), mEvent(event), mParam(event) {}
66 virtual ~IoConfigEvent() {}
67
68 int event() const { return mEvent; }
69 int param() const { return mParam; }
70
71 virtual void dump(char *buffer, size_t size) {
72 snprintf(buffer, size, "IO event: event %d, param %d\n", mEvent, mParam);
73 }
74
75 private:
76 const int mEvent;
77 const int mParam;
78 };
79
80 class PrioConfigEvent : public ConfigEvent {
81 public:
82 PrioConfigEvent(pid_t pid, pid_t tid, int32_t prio) :
83 ConfigEvent(CFG_EVENT_PRIO), mPid(pid), mTid(tid), mPrio(prio) {}
84 virtual ~PrioConfigEvent() {}
85
86 pid_t pid() const { return mPid; }
87 pid_t tid() const { return mTid; }
88 int32_t prio() const { return mPrio; }
89
90 virtual void dump(char *buffer, size_t size) {
91 snprintf(buffer, size, "Prio event: pid %d, tid %d, prio %d\n", mPid, mTid, mPrio);
92 }
93
94 private:
95 const pid_t mPid;
96 const pid_t mTid;
97 const int32_t mPrio;
98 };
99
100
101 class PMDeathRecipient : public IBinder::DeathRecipient {
102 public:
103 PMDeathRecipient(const wp<ThreadBase>& thread) : mThread(thread) {}
104 virtual ~PMDeathRecipient() {}
105
106 // IBinder::DeathRecipient
107 virtual void binderDied(const wp<IBinder>& who);
108
109 private:
110 PMDeathRecipient(const PMDeathRecipient&);
111 PMDeathRecipient& operator = (const PMDeathRecipient&);
112
113 wp<ThreadBase> mThread;
114 };
115
116 virtual status_t initCheck() const = 0;
117
118 // static externally-visible
119 type_t type() const { return mType; }
120 audio_io_handle_t id() const { return mId;}
121
122 // dynamic externally-visible
123 uint32_t sampleRate() const { return mSampleRate; }
124 uint32_t channelCount() const { return mChannelCount; }
125 audio_channel_mask_t channelMask() const { return mChannelMask; }
126 audio_format_t format() const { return mFormat; }
127 // Called by AudioFlinger::frameCount(audio_io_handle_t output) and effects,
128 // and returns the normal mix buffer's frame count.
129 size_t frameCount() const { return mNormalFrameCount; }
130 // Return's the HAL's frame count i.e. fast mixer buffer size.
131 size_t frameCountHAL() const { return mFrameCount; }
132
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);
187 // set audio mode to all effect chains
188 void setMode(audio_mode_t mode);
189 // get effect module with corresponding ID on specified audio session
190 sp<AudioFlinger::EffectModule> getEffect(int sessionId, int effectId);
191 sp<AudioFlinger::EffectModule> getEffect_l(int sessionId, int effectId);
192 // add and effect module. Also creates the effect chain is none exists for
193 // the effects audio session
194 status_t addEffect_l(const sp< EffectModule>& effect);
195 // remove and effect module. Also removes the effect chain is this was the last
196 // effect
197 void removeEffect_l(const sp< EffectModule>& effect);
198 // detach all tracks connected to an auxiliary effect
199 virtual void detachAuxEffect_l(int effectId) {}
200 // returns either EFFECT_SESSION if effects on this audio session exist in one
201 // chain, or TRACK_SESSION if tracks on this audio session exist, or both
202 virtual uint32_t hasAudioSession(int sessionId) const = 0;
203 // the value returned by default implementation is not important as the
204 // strategy is only meaningful for PlaybackThread which implements this method
205 virtual uint32_t getStrategyForSession_l(int sessionId) { return 0; }
206
207 // suspend or restore effect according to the type of effect passed. a NULL
208 // type pointer means suspend all effects in the session
209 void setEffectSuspended(const effect_uuid_t *type,
210 bool suspend,
211 int sessionId = AUDIO_SESSION_OUTPUT_MIX);
212 // check if some effects must be suspended/restored when an effect is enabled
213 // or disabled
214 void checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
215 bool enabled,
216 int sessionId = AUDIO_SESSION_OUTPUT_MIX);
217 void checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
218 bool enabled,
219 int sessionId = AUDIO_SESSION_OUTPUT_MIX);
220
221 virtual status_t setSyncEvent(const sp<SyncEvent>& event) = 0;
222 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const = 0;
223
224
225 mutable Mutex mLock;
226
227protected:
228
229 // entry describing an effect being suspended in mSuspendedSessions keyed vector
230 class SuspendedSessionDesc : public RefBase {
231 public:
232 SuspendedSessionDesc() : mRefCount(0) {}
233
234 int mRefCount; // number of active suspend requests
235 effect_uuid_t mType; // effect type UUID
236 };
237
238 void acquireWakeLock();
239 void acquireWakeLock_l();
240 void releaseWakeLock();
241 void releaseWakeLock_l();
242 void setEffectSuspended_l(const effect_uuid_t *type,
243 bool suspend,
244 int sessionId);
245 // updated mSuspendedSessions when an effect suspended or restored
246 void updateSuspendedSessions_l(const effect_uuid_t *type,
247 bool suspend,
248 int sessionId);
249 // check if some effects must be suspended when an effect chain is added
250 void checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain);
251
252 virtual void preExit() { }
253
254 friend class AudioFlinger; // for mEffectChains
255
256 const type_t mType;
257
258 // Used by parameters, config events, addTrack_l, exit
259 Condition mWaitWorkCV;
260
261 const sp<AudioFlinger> mAudioFlinger;
262 uint32_t mSampleRate;
263 size_t mFrameCount; // output HAL, direct output, record
264 size_t mNormalFrameCount; // normal mixer and effects
265 audio_channel_mask_t mChannelMask;
266 uint16_t mChannelCount;
267 size_t mFrameSize;
268 audio_format_t mFormat;
269
270 // Parameter sequence by client: binder thread calling setParameters():
271 // 1. Lock mLock
272 // 2. Append to mNewParameters
273 // 3. mWaitWorkCV.signal
274 // 4. mParamCond.waitRelative with timeout
275 // 5. read mParamStatus
276 // 6. mWaitWorkCV.signal
277 // 7. Unlock
278 //
279 // Parameter sequence by server: threadLoop calling checkForNewParameters_l():
280 // 1. Lock mLock
281 // 2. If there is an entry in mNewParameters proceed ...
282 // 2. Read first entry in mNewParameters
283 // 3. Process
284 // 4. Remove first entry from mNewParameters
285 // 5. Set mParamStatus
286 // 6. mParamCond.signal
287 // 7. mWaitWorkCV.wait with timeout (this is to avoid overwriting mParamStatus)
288 // 8. Unlock
289 Condition mParamCond;
290 Vector<String8> mNewParameters;
291 status_t mParamStatus;
292
293 Vector<ConfigEvent *> mConfigEvents;
294
295 // These fields are written and read by thread itself without lock or barrier,
296 // and read by other threads without lock or barrier via standby() , outDevice()
297 // and inDevice().
298 // Because of the absence of a lock or barrier, any other thread that reads
299 // these fields must use the information in isolation, or be prepared to deal
300 // with possibility that it might be inconsistent with other information.
301 bool mStandby; // Whether thread is currently in standby.
302 audio_devices_t mOutDevice; // output device
303 audio_devices_t mInDevice; // input device
304 audio_source_t mAudioSource; // (see audio.h, audio_source_t)
305
306 const audio_io_handle_t mId;
307 Vector< sp<EffectChain> > mEffectChains;
308
309 static const int kNameLength = 16; // prctl(PR_SET_NAME) limit
310 char mName[kNameLength];
311 sp<IPowerManager> mPowerManager;
312 sp<IBinder> mWakeLockToken;
313 const sp<PMDeathRecipient> mDeathRecipient;
314 // list of suspended effects per session and per type. The first vector is
315 // keyed by session ID, the second by type UUID timeLow field
316 KeyedVector< int, KeyedVector< int, sp<SuspendedSessionDesc> > >
317 mSuspendedSessions;
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800318 static const size_t kLogSize = 4 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -0800319 sp<NBLog::Writer> mNBLogWriter;
Eric Laurent81784c32012-11-19 14:55:58 -0800320};
321
322// --- PlaybackThread ---
323class PlaybackThread : public ThreadBase {
324public:
325
326#include "PlaybackTracks.h"
327
328 enum mixer_state {
329 MIXER_IDLE, // no active tracks
330 MIXER_TRACKS_ENABLED, // at least one active track, but no track has any data ready
331 MIXER_TRACKS_READY // at least one active track, and at least one track has data
332 // standby mode does not have an enum value
333 // suspend by audio policy manager is orthogonal to mixer state
334 };
335
336 PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
337 audio_io_handle_t id, audio_devices_t device, type_t type);
338 virtual ~PlaybackThread();
339
340 void dump(int fd, const Vector<String16>& args);
341
342 // Thread virtuals
343 virtual status_t readyToRun();
344 virtual bool threadLoop();
345
346 // RefBase
347 virtual void onFirstRef();
348
349protected:
350 // Code snippets that were lifted up out of threadLoop()
351 virtual void threadLoop_mix() = 0;
352 virtual void threadLoop_sleepTime() = 0;
353 virtual void threadLoop_write();
354 virtual void threadLoop_standby();
355 virtual void threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
356
357 // prepareTracks_l reads and writes mActiveTracks, and returns
358 // the pending set of tracks to remove via Vector 'tracksToRemove'. The caller
359 // is responsible for clearing or destroying this Vector later on, when it
360 // is safe to do so. That will drop the final ref count and destroy the tracks.
361 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove) = 0;
362
363 // ThreadBase virtuals
364 virtual void preExit();
365
366public:
367
368 virtual status_t initCheck() const { return (mOutput == NULL) ? NO_INIT : NO_ERROR; }
369
370 // return estimated latency in milliseconds, as reported by HAL
371 uint32_t latency() const;
372 // same, but lock must already be held
373 uint32_t latency_l() const;
374
375 void setMasterVolume(float value);
376 void setMasterMute(bool muted);
377
378 void setStreamVolume(audio_stream_type_t stream, float value);
379 void setStreamMute(audio_stream_type_t stream, bool muted);
380
381 float streamVolume(audio_stream_type_t stream) const;
382
383 sp<Track> createTrack_l(
384 const sp<AudioFlinger::Client>& client,
385 audio_stream_type_t streamType,
386 uint32_t sampleRate,
387 audio_format_t format,
388 audio_channel_mask_t channelMask,
389 size_t frameCount,
390 const sp<IMemory>& sharedBuffer,
391 int sessionId,
392 IAudioFlinger::track_flags_t *flags,
393 pid_t tid,
394 status_t *status);
395
396 AudioStreamOut* getOutput() const;
397 AudioStreamOut* clearOutput();
398 virtual audio_stream_t* stream() const;
399
400 // a very large number of suspend() will eventually wraparound, but unlikely
401 void suspend() { (void) android_atomic_inc(&mSuspended); }
402 void restore()
403 {
404 // if restore() is done without suspend(), get back into
405 // range so that the next suspend() will operate correctly
406 if (android_atomic_dec(&mSuspended) <= 0) {
407 android_atomic_release_store(0, &mSuspended);
408 }
409 }
410 bool isSuspended() const
411 { return android_atomic_acquire_load(&mSuspended) > 0; }
412
413 virtual String8 getParameters(const String8& keys);
414 virtual void audioConfigChanged_l(int event, int param = 0);
415 status_t getRenderPosition(size_t *halFrames, size_t *dspFrames);
416 int16_t *mixBuffer() const { return mMixBuffer; };
417
418 virtual void detachAuxEffect_l(int effectId);
419 status_t attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track> track,
420 int EffectId);
421 status_t attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track> track,
422 int EffectId);
423
424 virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
425 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
426 virtual uint32_t hasAudioSession(int sessionId) const;
427 virtual uint32_t getStrategyForSession_l(int sessionId);
428
429
430 virtual status_t setSyncEvent(const sp<SyncEvent>& event);
431 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const;
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700432
433 // called with AudioFlinger lock held
Eric Laurent81784c32012-11-19 14:55:58 -0800434 void invalidateTracks(audio_stream_type_t streamType);
435
436
437protected:
438 int16_t* mMixBuffer;
439
440 // suspend count, > 0 means suspended. While suspended, the thread continues to pull from
441 // tracks and mix, but doesn't write to HAL. A2DP and SCO HAL implementations can't handle
442 // concurrent use of both of them, so Audio Policy Service suspends one of the threads to
443 // workaround that restriction.
444 // 'volatile' means accessed via atomic operations and no lock.
445 volatile int32_t mSuspended;
446
447 // FIXME overflows every 6+ hours at 44.1 kHz stereo 16-bit samples
448 // mFramesWritten would be better, or 64-bit even better
449 size_t mBytesWritten;
450private:
451 // mMasterMute is in both PlaybackThread and in AudioFlinger. When a
452 // PlaybackThread needs to find out if master-muted, it checks it's local
453 // copy rather than the one in AudioFlinger. This optimization saves a lock.
454 bool mMasterMute;
455 void setMasterMute_l(bool muted) { mMasterMute = muted; }
456protected:
457 SortedVector< wp<Track> > mActiveTracks; // FIXME check if this could be sp<>
458
459 // Allocate a track name for a given channel mask.
460 // Returns name >= 0 if successful, -1 on failure.
461 virtual int getTrackName_l(audio_channel_mask_t channelMask, int sessionId) = 0;
462 virtual void deleteTrackName_l(int name) = 0;
463
464 // Time to sleep between cycles when:
465 virtual uint32_t activeSleepTimeUs() const; // mixer state MIXER_TRACKS_ENABLED
466 virtual uint32_t idleSleepTimeUs() const = 0; // mixer state MIXER_IDLE
467 virtual uint32_t suspendSleepTimeUs() const = 0; // audio policy manager suspended us
468 // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write()
469 // No sleep in standby mode; waits on a condition
470
471 // Code snippets that are temporarily lifted up out of threadLoop() until the merge
472 void checkSilentMode_l();
473
474 // Non-trivial for DUPLICATING only
475 virtual void saveOutputTracks() { }
476 virtual void clearOutputTracks() { }
477
478 // Cache various calculated values, at threadLoop() entry and after a parameter change
479 virtual void cacheParameters_l();
480
481 virtual uint32_t correctLatency_l(uint32_t latency) const;
482
483private:
484
485 friend class AudioFlinger; // for numerous
486
487 PlaybackThread(const Client&);
488 PlaybackThread& operator = (const PlaybackThread&);
489
490 status_t addTrack_l(const sp<Track>& track);
491 void destroyTrack_l(const sp<Track>& track);
492 void removeTrack_l(const sp<Track>& track);
493
494 void readOutputParameters();
495
496 virtual void dumpInternals(int fd, const Vector<String16>& args);
497 void dumpTracks(int fd, const Vector<String16>& args);
498
499 SortedVector< sp<Track> > mTracks;
500 // mStreamTypes[] uses 1 additional stream type internally for the OutputTrack used by
501 // DuplicatingThread
502 stream_type_t mStreamTypes[AUDIO_STREAM_CNT + 1];
503 AudioStreamOut *mOutput;
504
505 float mMasterVolume;
506 nsecs_t mLastWriteTime;
507 int mNumWrites;
508 int mNumDelayedWrites;
509 bool mInWrite;
510
511 // FIXME rename these former local variables of threadLoop to standard "m" names
512 nsecs_t standbyTime;
513 size_t mixBufferSize;
514
515 // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l()
516 uint32_t activeSleepTime;
517 uint32_t idleSleepTime;
518
519 uint32_t sleepTime;
520
521 // mixer status returned by prepareTracks_l()
522 mixer_state mMixerStatus; // current cycle
523 // previous cycle when in prepareTracks_l()
524 mixer_state mMixerStatusIgnoringFastTracks;
525 // FIXME or a separate ready state per track
526
527 // FIXME move these declarations into the specific sub-class that needs them
528 // MIXER only
529 uint32_t sleepTimeShift;
530
531 // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value
532 nsecs_t standbyDelay;
533
534 // MIXER only
535 nsecs_t maxPeriod;
536
537 // DUPLICATING only
538 uint32_t writeFrames;
539
540private:
541 // The HAL output sink is treated as non-blocking, but current implementation is blocking
542 sp<NBAIO_Sink> mOutputSink;
543 // If a fast mixer is present, the blocking pipe sink, otherwise clear
544 sp<NBAIO_Sink> mPipeSink;
545 // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink
546 sp<NBAIO_Sink> mNormalSink;
Glenn Kasten46909e72013-02-26 09:20:22 -0800547#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -0800548 // For dumpsys
549 sp<NBAIO_Sink> mTeeSink;
550 sp<NBAIO_Source> mTeeSource;
Glenn Kasten46909e72013-02-26 09:20:22 -0800551#endif
Eric Laurent81784c32012-11-19 14:55:58 -0800552 uint32_t mScreenState; // cached copy of gScreenState
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800553 static const size_t kFastMixerLogSize = 4 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -0800554 sp<NBLog::Writer> mFastMixerNBLogWriter;
Eric Laurent81784c32012-11-19 14:55:58 -0800555public:
556 virtual bool hasFastMixer() const = 0;
557 virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const
558 { FastTrackUnderruns dummy; return dummy; }
559
560protected:
561 // accessed by both binder threads and within threadLoop(), lock on mutex needed
562 unsigned mFastTrackAvailMask; // bit i set if fast track [i] is available
563
564};
565
566class MixerThread : public PlaybackThread {
567public:
568 MixerThread(const sp<AudioFlinger>& audioFlinger,
569 AudioStreamOut* output,
570 audio_io_handle_t id,
571 audio_devices_t device,
572 type_t type = MIXER);
573 virtual ~MixerThread();
574
575 // Thread virtuals
576
577 virtual bool checkForNewParameters_l();
578 virtual void dumpInternals(int fd, const Vector<String16>& args);
579
580protected:
581 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
582 virtual int getTrackName_l(audio_channel_mask_t channelMask, int sessionId);
583 virtual void deleteTrackName_l(int name);
584 virtual uint32_t idleSleepTimeUs() const;
585 virtual uint32_t suspendSleepTimeUs() const;
586 virtual void cacheParameters_l();
587
588 // threadLoop snippets
589 virtual void threadLoop_write();
590 virtual void threadLoop_standby();
591 virtual void threadLoop_mix();
592 virtual void threadLoop_sleepTime();
593 virtual void threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
594 virtual uint32_t correctLatency_l(uint32_t latency) const;
595
596 AudioMixer* mAudioMixer; // normal mixer
597private:
598 // one-time initialization, no locks required
599 FastMixer* mFastMixer; // non-NULL if there is also a fast mixer
600 sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread
601
602 // contents are not guaranteed to be consistent, no locks required
603 FastMixerDumpState mFastMixerDumpState;
604#ifdef STATE_QUEUE_DUMP
605 StateQueueObserverDump mStateQueueObserverDump;
606 StateQueueMutatorDump mStateQueueMutatorDump;
607#endif
608 AudioWatchdogDump mAudioWatchdogDump;
609
610 // accessible only within the threadLoop(), no locks required
611 // mFastMixer->sq() // for mutating and pushing state
612 int32_t mFastMixerFutex; // for cold idle
613
614public:
615 virtual bool hasFastMixer() const { return mFastMixer != NULL; }
616 virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const {
617 ALOG_ASSERT(fastIndex < FastMixerState::kMaxFastTracks);
618 return mFastMixerDumpState.mTracks[fastIndex].mUnderruns;
619 }
620};
621
622class DirectOutputThread : public PlaybackThread {
623public:
624
625 DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
626 audio_io_handle_t id, audio_devices_t device);
627 virtual ~DirectOutputThread();
628
629 // Thread virtuals
630
631 virtual bool checkForNewParameters_l();
632
633protected:
634 virtual int getTrackName_l(audio_channel_mask_t channelMask, int sessionId);
635 virtual void deleteTrackName_l(int name);
636 virtual uint32_t activeSleepTimeUs() const;
637 virtual uint32_t idleSleepTimeUs() const;
638 virtual uint32_t suspendSleepTimeUs() const;
639 virtual void cacheParameters_l();
640
641 // threadLoop snippets
642 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
643 virtual void threadLoop_mix();
644 virtual void threadLoop_sleepTime();
645
646private:
647 // volumes last sent to audio HAL with stream->set_volume()
648 float mLeftVolFloat;
649 float mRightVolFloat;
650
651 // prepareTracks_l() tells threadLoop_mix() the name of the single active track
652 sp<Track> mActiveTrack;
653public:
654 virtual bool hasFastMixer() const { return false; }
655};
656
657class DuplicatingThread : public MixerThread {
658public:
659 DuplicatingThread(const sp<AudioFlinger>& audioFlinger, MixerThread* mainThread,
660 audio_io_handle_t id);
661 virtual ~DuplicatingThread();
662
663 // Thread virtuals
664 void addOutputTrack(MixerThread* thread);
665 void removeOutputTrack(MixerThread* thread);
666 uint32_t waitTimeMs() const { return mWaitTimeMs; }
667protected:
668 virtual uint32_t activeSleepTimeUs() const;
669
670private:
671 bool outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks);
672protected:
673 // threadLoop snippets
674 virtual void threadLoop_mix();
675 virtual void threadLoop_sleepTime();
676 virtual void threadLoop_write();
677 virtual void threadLoop_standby();
678 virtual void cacheParameters_l();
679
680private:
681 // called from threadLoop, addOutputTrack, removeOutputTrack
682 virtual void updateWaitTime_l();
683protected:
684 virtual void saveOutputTracks();
685 virtual void clearOutputTracks();
686private:
687
688 uint32_t mWaitTimeMs;
689 SortedVector < sp<OutputTrack> > outputTracks;
690 SortedVector < sp<OutputTrack> > mOutputTracks;
691public:
692 virtual bool hasFastMixer() const { return false; }
693};
694
695
696// record thread
697class RecordThread : public ThreadBase, public AudioBufferProvider
698 // derives from AudioBufferProvider interface for use by resampler
699{
700public:
701
702#include "RecordTracks.h"
703
704 RecordThread(const sp<AudioFlinger>& audioFlinger,
705 AudioStreamIn *input,
706 uint32_t sampleRate,
707 audio_channel_mask_t channelMask,
708 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -0800709 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -0800710 audio_devices_t inDevice
711#ifdef TEE_SINK
712 , const sp<NBAIO_Sink>& teeSink
713#endif
714 );
Eric Laurent81784c32012-11-19 14:55:58 -0800715 virtual ~RecordThread();
716
717 // no addTrack_l ?
718 void destroyTrack_l(const sp<RecordTrack>& track);
719 void removeTrack_l(const sp<RecordTrack>& track);
720
721 void dumpInternals(int fd, const Vector<String16>& args);
722 void dumpTracks(int fd, const Vector<String16>& args);
723
724 // Thread virtuals
725 virtual bool threadLoop();
726 virtual status_t readyToRun();
727
728 // RefBase
729 virtual void onFirstRef();
730
731 virtual status_t initCheck() const { return (mInput == NULL) ? NO_INIT : NO_ERROR; }
732 sp<AudioFlinger::RecordThread::RecordTrack> createRecordTrack_l(
733 const sp<AudioFlinger::Client>& client,
734 uint32_t sampleRate,
735 audio_format_t format,
736 audio_channel_mask_t channelMask,
737 size_t frameCount,
738 int sessionId,
739 IAudioFlinger::track_flags_t flags,
740 pid_t tid,
741 status_t *status);
742
743 status_t start(RecordTrack* recordTrack,
744 AudioSystem::sync_event_t event,
745 int triggerSession);
746
747 // ask the thread to stop the specified track, and
748 // return true if the caller should then do it's part of the stopping process
749 bool stop_l(RecordTrack* recordTrack);
750
751 void dump(int fd, const Vector<String16>& args);
752 AudioStreamIn* clearInput();
753 virtual audio_stream_t* stream() const;
754
755 // AudioBufferProvider interface
756 virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts);
757 virtual void releaseBuffer(AudioBufferProvider::Buffer* buffer);
758
759 virtual bool checkForNewParameters_l();
760 virtual String8 getParameters(const String8& keys);
761 virtual void audioConfigChanged_l(int event, int param = 0);
762 void readInputParameters();
763 virtual unsigned int getInputFramesLost();
764
765 virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
766 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
767 virtual uint32_t hasAudioSession(int sessionId) const;
768
769 // Return the set of unique session IDs across all tracks.
770 // The keys are the session IDs, and the associated values are meaningless.
771 // FIXME replace by Set [and implement Bag/Multiset for other uses].
772 KeyedVector<int, bool> sessionIds() const;
773
774 virtual status_t setSyncEvent(const sp<SyncEvent>& event);
775 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const;
776
777 static void syncStartEventCallback(const wp<SyncEvent>& event);
778 void handleSyncStartEvent(const sp<SyncEvent>& event);
779
780private:
781 void clearSyncStartEvent();
782
783 // Enter standby if not already in standby, and set mStandby flag
784 void standby();
785
786 // Call the HAL standby method unconditionally, and don't change mStandby flag
787 void inputStandBy();
788
789 AudioStreamIn *mInput;
790 SortedVector < sp<RecordTrack> > mTracks;
791 // mActiveTrack has dual roles: it indicates the current active track, and
792 // is used together with mStartStopCond to indicate start()/stop() progress
793 sp<RecordTrack> mActiveTrack;
794 Condition mStartStopCond;
795 AudioResampler *mResampler;
796 int32_t *mRsmpOutBuffer;
797 int16_t *mRsmpInBuffer;
798 size_t mRsmpInIndex;
799 size_t mInputBytes;
800 const uint32_t mReqChannelCount;
801 const uint32_t mReqSampleRate;
802 ssize_t mBytesRead;
803 // sync event triggering actual audio capture. Frames read before this event will
804 // be dropped and therefore not read by the application.
805 sp<SyncEvent> mSyncStartEvent;
806 // number of captured frames to drop after the start sync event has been received.
807 // when < 0, maximum frames to drop before starting capture even if sync event is
808 // not received
809 ssize_t mFramestoDrop;
810
811 // For dumpsys
812 const sp<NBAIO_Sink> mTeeSink;
813};