Threads.h revision 34af02647b387a252fb02bab8e2cb9f7bd9c8abb
1/*
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 owns each ConfigEvent *, so must delete after removing
294                Vector<ConfigEvent *>     mConfigEvents;
295
296                // These fields are written and read by thread itself without lock or barrier,
297                // and read by other threads without lock or barrier via standby() , outDevice()
298                // and inDevice().
299                // Because of the absence of a lock or barrier, any other thread that reads
300                // these fields must use the information in isolation, or be prepared to deal
301                // with possibility that it might be inconsistent with other information.
302                bool                    mStandby;   // Whether thread is currently in standby.
303                audio_devices_t         mOutDevice;   // output device
304                audio_devices_t         mInDevice;    // input device
305                audio_source_t          mAudioSource; // (see audio.h, audio_source_t)
306
307                const audio_io_handle_t mId;
308                Vector< sp<EffectChain> > mEffectChains;
309
310                static const int        kNameLength = 16;   // prctl(PR_SET_NAME) limit
311                char                    mName[kNameLength];
312                sp<IPowerManager>       mPowerManager;
313                sp<IBinder>             mWakeLockToken;
314                const sp<PMDeathRecipient> mDeathRecipient;
315                // list of suspended effects per session and per type. The first vector is
316                // keyed by session ID, the second by type UUID timeLow field
317                KeyedVector< int, KeyedVector< int, sp<SuspendedSessionDesc> > >
318                                        mSuspendedSessions;
319                static const size_t     kLogSize = 4 * 1024;
320                sp<NBLog::Writer>       mNBLogWriter;
321};
322
323// --- PlaybackThread ---
324class PlaybackThread : public ThreadBase {
325public:
326
327#include "PlaybackTracks.h"
328
329    enum mixer_state {
330        MIXER_IDLE,             // no active tracks
331        MIXER_TRACKS_ENABLED,   // at least one active track, but no track has any data ready
332        MIXER_TRACKS_READY      // at least one active track, and at least one track has data
333        // standby mode does not have an enum value
334        // suspend by audio policy manager is orthogonal to mixer state
335    };
336
337    PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
338                   audio_io_handle_t id, audio_devices_t device, type_t type);
339    virtual             ~PlaybackThread();
340
341                void        dump(int fd, const Vector<String16>& args);
342
343    // Thread virtuals
344    virtual     status_t    readyToRun();
345    virtual     bool        threadLoop();
346
347    // RefBase
348    virtual     void        onFirstRef();
349
350protected:
351    // Code snippets that were lifted up out of threadLoop()
352    virtual     void        threadLoop_mix() = 0;
353    virtual     void        threadLoop_sleepTime() = 0;
354    virtual     void        threadLoop_write();
355    virtual     void        threadLoop_standby();
356    virtual     void        threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
357
358                // prepareTracks_l reads and writes mActiveTracks, and returns
359                // the pending set of tracks to remove via Vector 'tracksToRemove'.  The caller
360                // is responsible for clearing or destroying this Vector later on, when it
361                // is safe to do so. That will drop the final ref count and destroy the tracks.
362    virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove) = 0;
363
364    // ThreadBase virtuals
365    virtual     void        preExit();
366
367public:
368
369    virtual     status_t    initCheck() const { return (mOutput == NULL) ? NO_INIT : NO_ERROR; }
370
371                // return estimated latency in milliseconds, as reported by HAL
372                uint32_t    latency() const;
373                // same, but lock must already be held
374                uint32_t    latency_l() const;
375
376                void        setMasterVolume(float value);
377                void        setMasterMute(bool muted);
378
379                void        setStreamVolume(audio_stream_type_t stream, float value);
380                void        setStreamMute(audio_stream_type_t stream, bool muted);
381
382                float       streamVolume(audio_stream_type_t stream) const;
383
384                sp<Track>   createTrack_l(
385                                const sp<AudioFlinger::Client>& client,
386                                audio_stream_type_t streamType,
387                                uint32_t sampleRate,
388                                audio_format_t format,
389                                audio_channel_mask_t channelMask,
390                                size_t frameCount,
391                                const sp<IMemory>& sharedBuffer,
392                                int sessionId,
393                                IAudioFlinger::track_flags_t *flags,
394                                pid_t tid,
395                                status_t *status);
396
397                AudioStreamOut* getOutput() const;
398                AudioStreamOut* clearOutput();
399                virtual audio_stream_t* stream() const;
400
401                // a very large number of suspend() will eventually wraparound, but unlikely
402                void        suspend() { (void) android_atomic_inc(&mSuspended); }
403                void        restore()
404                                {
405                                    // if restore() is done without suspend(), get back into
406                                    // range so that the next suspend() will operate correctly
407                                    if (android_atomic_dec(&mSuspended) <= 0) {
408                                        android_atomic_release_store(0, &mSuspended);
409                                    }
410                                }
411                bool        isSuspended() const
412                                { return android_atomic_acquire_load(&mSuspended) > 0; }
413
414    virtual     String8     getParameters(const String8& keys);
415    virtual     void        audioConfigChanged_l(int event, int param = 0);
416                status_t    getRenderPosition(size_t *halFrames, size_t *dspFrames);
417                int16_t     *mixBuffer() const { return mMixBuffer; };
418
419    virtual     void detachAuxEffect_l(int effectId);
420                status_t attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track> track,
421                        int EffectId);
422                status_t attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track> track,
423                        int EffectId);
424
425                virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
426                virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
427                virtual uint32_t hasAudioSession(int sessionId) const;
428                virtual uint32_t getStrategyForSession_l(int sessionId);
429
430
431                virtual status_t setSyncEvent(const sp<SyncEvent>& event);
432                virtual bool     isValidSyncEvent(const sp<SyncEvent>& event) const;
433
434                // called with AudioFlinger lock held
435                        void     invalidateTracks(audio_stream_type_t streamType);
436
437
438protected:
439    int16_t*                        mMixBuffer;
440
441    // suspend count, > 0 means suspended.  While suspended, the thread continues to pull from
442    // tracks and mix, but doesn't write to HAL.  A2DP and SCO HAL implementations can't handle
443    // concurrent use of both of them, so Audio Policy Service suspends one of the threads to
444    // workaround that restriction.
445    // 'volatile' means accessed via atomic operations and no lock.
446    volatile int32_t                mSuspended;
447
448    // FIXME overflows every 6+ hours at 44.1 kHz stereo 16-bit samples
449    // mFramesWritten would be better, or 64-bit even better
450    size_t                          mBytesWritten;
451private:
452    // mMasterMute is in both PlaybackThread and in AudioFlinger.  When a
453    // PlaybackThread needs to find out if master-muted, it checks it's local
454    // copy rather than the one in AudioFlinger.  This optimization saves a lock.
455    bool                            mMasterMute;
456                void        setMasterMute_l(bool muted) { mMasterMute = muted; }
457protected:
458    SortedVector< wp<Track> >       mActiveTracks;  // FIXME check if this could be sp<>
459
460    // Allocate a track name for a given channel mask.
461    //   Returns name >= 0 if successful, -1 on failure.
462    virtual int             getTrackName_l(audio_channel_mask_t channelMask, int sessionId) = 0;
463    virtual void            deleteTrackName_l(int name) = 0;
464
465    // Time to sleep between cycles when:
466    virtual uint32_t        activeSleepTimeUs() const;      // mixer state MIXER_TRACKS_ENABLED
467    virtual uint32_t        idleSleepTimeUs() const = 0;    // mixer state MIXER_IDLE
468    virtual uint32_t        suspendSleepTimeUs() const = 0; // audio policy manager suspended us
469    // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write()
470    // No sleep in standby mode; waits on a condition
471
472    // Code snippets that are temporarily lifted up out of threadLoop() until the merge
473                void        checkSilentMode_l();
474
475    // Non-trivial for DUPLICATING only
476    virtual     void        saveOutputTracks() { }
477    virtual     void        clearOutputTracks() { }
478
479    // Cache various calculated values, at threadLoop() entry and after a parameter change
480    virtual     void        cacheParameters_l();
481
482    virtual     uint32_t    correctLatency_l(uint32_t latency) const;
483
484private:
485
486    friend class AudioFlinger;      // for numerous
487
488    PlaybackThread(const Client&);
489    PlaybackThread& operator = (const PlaybackThread&);
490
491    status_t    addTrack_l(const sp<Track>& track);
492    void        destroyTrack_l(const sp<Track>& track);
493    void        removeTrack_l(const sp<Track>& track);
494
495    void        readOutputParameters();
496
497    virtual void dumpInternals(int fd, const Vector<String16>& args);
498    void        dumpTracks(int fd, const Vector<String16>& args);
499
500    SortedVector< sp<Track> >       mTracks;
501    // mStreamTypes[] uses 1 additional stream type internally for the OutputTrack used by
502    // DuplicatingThread
503    stream_type_t                   mStreamTypes[AUDIO_STREAM_CNT + 1];
504    AudioStreamOut                  *mOutput;
505
506    float                           mMasterVolume;
507    nsecs_t                         mLastWriteTime;
508    int                             mNumWrites;
509    int                             mNumDelayedWrites;
510    bool                            mInWrite;
511
512    // FIXME rename these former local variables of threadLoop to standard "m" names
513    nsecs_t                         standbyTime;
514    size_t                          mixBufferSize;
515
516    // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l()
517    uint32_t                        activeSleepTime;
518    uint32_t                        idleSleepTime;
519
520    uint32_t                        sleepTime;
521
522    // mixer status returned by prepareTracks_l()
523    mixer_state                     mMixerStatus; // current cycle
524                                                  // previous cycle when in prepareTracks_l()
525    mixer_state                     mMixerStatusIgnoringFastTracks;
526                                                  // FIXME or a separate ready state per track
527
528    // FIXME move these declarations into the specific sub-class that needs them
529    // MIXER only
530    uint32_t                        sleepTimeShift;
531
532    // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value
533    nsecs_t                         standbyDelay;
534
535    // MIXER only
536    nsecs_t                         maxPeriod;
537
538    // DUPLICATING only
539    uint32_t                        writeFrames;
540
541private:
542    // The HAL output sink is treated as non-blocking, but current implementation is blocking
543    sp<NBAIO_Sink>          mOutputSink;
544    // If a fast mixer is present, the blocking pipe sink, otherwise clear
545    sp<NBAIO_Sink>          mPipeSink;
546    // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink
547    sp<NBAIO_Sink>          mNormalSink;
548#ifdef TEE_SINK
549    // For dumpsys
550    sp<NBAIO_Sink>          mTeeSink;
551    sp<NBAIO_Source>        mTeeSource;
552#endif
553    uint32_t                mScreenState;   // cached copy of gScreenState
554    static const size_t     kFastMixerLogSize = 4 * 1024;
555    sp<NBLog::Writer>       mFastMixerNBLogWriter;
556public:
557    virtual     bool        hasFastMixer() const = 0;
558    virtual     FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const
559                                { FastTrackUnderruns dummy; return dummy; }
560
561protected:
562                // accessed by both binder threads and within threadLoop(), lock on mutex needed
563                unsigned    mFastTrackAvailMask;    // bit i set if fast track [i] is available
564
565};
566
567class MixerThread : public PlaybackThread {
568public:
569    MixerThread(const sp<AudioFlinger>& audioFlinger,
570                AudioStreamOut* output,
571                audio_io_handle_t id,
572                audio_devices_t device,
573                type_t type = MIXER);
574    virtual             ~MixerThread();
575
576    // Thread virtuals
577
578    virtual     bool        checkForNewParameters_l();
579    virtual     void        dumpInternals(int fd, const Vector<String16>& args);
580
581protected:
582    virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
583    virtual     int         getTrackName_l(audio_channel_mask_t channelMask, int sessionId);
584    virtual     void        deleteTrackName_l(int name);
585    virtual     uint32_t    idleSleepTimeUs() const;
586    virtual     uint32_t    suspendSleepTimeUs() const;
587    virtual     void        cacheParameters_l();
588
589    // threadLoop snippets
590    virtual     void        threadLoop_write();
591    virtual     void        threadLoop_standby();
592    virtual     void        threadLoop_mix();
593    virtual     void        threadLoop_sleepTime();
594    virtual     void        threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
595    virtual     uint32_t    correctLatency_l(uint32_t latency) const;
596
597                AudioMixer* mAudioMixer;    // normal mixer
598private:
599                // one-time initialization, no locks required
600                FastMixer*  mFastMixer;         // non-NULL if there is also a fast mixer
601                sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread
602
603                // contents are not guaranteed to be consistent, no locks required
604                FastMixerDumpState mFastMixerDumpState;
605#ifdef STATE_QUEUE_DUMP
606                StateQueueObserverDump mStateQueueObserverDump;
607                StateQueueMutatorDump  mStateQueueMutatorDump;
608#endif
609                AudioWatchdogDump mAudioWatchdogDump;
610
611                // accessible only within the threadLoop(), no locks required
612                //          mFastMixer->sq()    // for mutating and pushing state
613                int32_t     mFastMixerFutex;    // for cold idle
614
615public:
616    virtual     bool        hasFastMixer() const { return mFastMixer != NULL; }
617    virtual     FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const {
618                              ALOG_ASSERT(fastIndex < FastMixerState::kMaxFastTracks);
619                              return mFastMixerDumpState.mTracks[fastIndex].mUnderruns;
620                            }
621};
622
623class DirectOutputThread : public PlaybackThread {
624public:
625
626    DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
627                       audio_io_handle_t id, audio_devices_t device);
628    virtual                 ~DirectOutputThread();
629
630    // Thread virtuals
631
632    virtual     bool        checkForNewParameters_l();
633
634protected:
635    virtual     int         getTrackName_l(audio_channel_mask_t channelMask, int sessionId);
636    virtual     void        deleteTrackName_l(int name);
637    virtual     uint32_t    activeSleepTimeUs() const;
638    virtual     uint32_t    idleSleepTimeUs() const;
639    virtual     uint32_t    suspendSleepTimeUs() const;
640    virtual     void        cacheParameters_l();
641
642    // threadLoop snippets
643    virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
644    virtual     void        threadLoop_mix();
645    virtual     void        threadLoop_sleepTime();
646
647private:
648    // volumes last sent to audio HAL with stream->set_volume()
649    float mLeftVolFloat;
650    float mRightVolFloat;
651
652    // prepareTracks_l() tells threadLoop_mix() the name of the single active track
653    sp<Track>               mActiveTrack;
654public:
655    virtual     bool        hasFastMixer() const { return false; }
656};
657
658class DuplicatingThread : public MixerThread {
659public:
660    DuplicatingThread(const sp<AudioFlinger>& audioFlinger, MixerThread* mainThread,
661                      audio_io_handle_t id);
662    virtual                 ~DuplicatingThread();
663
664    // Thread virtuals
665                void        addOutputTrack(MixerThread* thread);
666                void        removeOutputTrack(MixerThread* thread);
667                uint32_t    waitTimeMs() const { return mWaitTimeMs; }
668protected:
669    virtual     uint32_t    activeSleepTimeUs() const;
670
671private:
672                bool        outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks);
673protected:
674    // threadLoop snippets
675    virtual     void        threadLoop_mix();
676    virtual     void        threadLoop_sleepTime();
677    virtual     void        threadLoop_write();
678    virtual     void        threadLoop_standby();
679    virtual     void        cacheParameters_l();
680
681private:
682    // called from threadLoop, addOutputTrack, removeOutputTrack
683    virtual     void        updateWaitTime_l();
684protected:
685    virtual     void        saveOutputTracks();
686    virtual     void        clearOutputTracks();
687private:
688
689                uint32_t    mWaitTimeMs;
690    SortedVector < sp<OutputTrack> >  outputTracks;
691    SortedVector < sp<OutputTrack> >  mOutputTracks;
692public:
693    virtual     bool        hasFastMixer() const { return false; }
694};
695
696
697// record thread
698class RecordThread : public ThreadBase, public AudioBufferProvider
699                        // derives from AudioBufferProvider interface for use by resampler
700{
701public:
702
703#include "RecordTracks.h"
704
705            RecordThread(const sp<AudioFlinger>& audioFlinger,
706                    AudioStreamIn *input,
707                    uint32_t sampleRate,
708                    audio_channel_mask_t channelMask,
709                    audio_io_handle_t id,
710                    audio_devices_t outDevice,
711                    audio_devices_t inDevice
712#ifdef TEE_SINK
713                    , const sp<NBAIO_Sink>& teeSink
714#endif
715                    );
716            virtual     ~RecordThread();
717
718    // no addTrack_l ?
719    void        destroyTrack_l(const sp<RecordTrack>& track);
720    void        removeTrack_l(const sp<RecordTrack>& track);
721
722    void        dumpInternals(int fd, const Vector<String16>& args);
723    void        dumpTracks(int fd, const Vector<String16>& args);
724
725    // Thread virtuals
726    virtual bool        threadLoop();
727    virtual status_t    readyToRun();
728
729    // RefBase
730    virtual void        onFirstRef();
731
732    virtual status_t    initCheck() const { return (mInput == NULL) ? NO_INIT : NO_ERROR; }
733            sp<AudioFlinger::RecordThread::RecordTrack>  createRecordTrack_l(
734                    const sp<AudioFlinger::Client>& client,
735                    uint32_t sampleRate,
736                    audio_format_t format,
737                    audio_channel_mask_t channelMask,
738                    size_t frameCount,
739                    int sessionId,
740                    IAudioFlinger::track_flags_t flags,
741                    pid_t tid,
742                    status_t *status);
743
744            status_t    start(RecordTrack* recordTrack,
745                              AudioSystem::sync_event_t event,
746                              int triggerSession);
747
748            // ask the thread to stop the specified track, and
749            // return true if the caller should then do it's part of the stopping process
750            bool        stop_l(RecordTrack* recordTrack);
751
752            void        dump(int fd, const Vector<String16>& args);
753            AudioStreamIn* clearInput();
754            virtual audio_stream_t* stream() const;
755
756    // AudioBufferProvider interface
757    virtual status_t    getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts);
758    virtual void        releaseBuffer(AudioBufferProvider::Buffer* buffer);
759
760    virtual bool        checkForNewParameters_l();
761    virtual String8     getParameters(const String8& keys);
762    virtual void        audioConfigChanged_l(int event, int param = 0);
763            void        readInputParameters();
764    virtual unsigned int  getInputFramesLost();
765
766    virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
767    virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
768    virtual uint32_t hasAudioSession(int sessionId) const;
769
770            // Return the set of unique session IDs across all tracks.
771            // The keys are the session IDs, and the associated values are meaningless.
772            // FIXME replace by Set [and implement Bag/Multiset for other uses].
773            KeyedVector<int, bool> sessionIds() const;
774
775    virtual status_t setSyncEvent(const sp<SyncEvent>& event);
776    virtual bool     isValidSyncEvent(const sp<SyncEvent>& event) const;
777
778    static void syncStartEventCallback(const wp<SyncEvent>& event);
779           void handleSyncStartEvent(const sp<SyncEvent>& event);
780
781private:
782            void clearSyncStartEvent();
783
784            // Enter standby if not already in standby, and set mStandby flag
785            void standby();
786
787            // Call the HAL standby method unconditionally, and don't change mStandby flag
788            void inputStandBy();
789
790            AudioStreamIn                       *mInput;
791            SortedVector < sp<RecordTrack> >    mTracks;
792            // mActiveTrack has dual roles:  it indicates the current active track, and
793            // is used together with mStartStopCond to indicate start()/stop() progress
794            sp<RecordTrack>                     mActiveTrack;
795            Condition                           mStartStopCond;
796            AudioResampler                      *mResampler;
797            // interleaved stereo pairs of fixed-point signed Q19.12
798            int32_t                             *mRsmpOutBuffer;
799            int16_t                             *mRsmpInBuffer; // [mFrameCount * mChannelCount]
800            size_t                              mRsmpInIndex;
801            size_t                              mInputBytes;
802            const uint32_t                      mReqChannelCount;
803            const uint32_t                      mReqSampleRate;
804            ssize_t                             mBytesRead;
805            // sync event triggering actual audio capture. Frames read before this event will
806            // be dropped and therefore not read by the application.
807            sp<SyncEvent>                       mSyncStartEvent;
808            // number of captured frames to drop after the start sync event has been received.
809            // when < 0, maximum frames to drop before starting capture even if sync event is
810            // not received
811            ssize_t                             mFramestoDrop;
812
813            // For dumpsys
814            const sp<NBAIO_Sink>                mTeeSink;
815};
816