Threads.h revision bfb1b832079bbb9426f72f3863199a54aefd02da
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        OFFLOAD             // Thread class is OffloadThread
33    };
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,
129                // and returns the normal mix buffer's frame count.
130                size_t      frameCount() const { return mNormalFrameCount; }
131                // Return's the HAL's frame count i.e. fast mixer buffer size.
132                size_t      frameCountHAL() const { return mFrameCount; }
133                size_t      frameSize() const { return mFrameSize; }
134
135    // Should be "virtual status_t requestExitAndWait()" and override same
136    // method in Thread, but Thread::requestExitAndWait() is not yet virtual.
137                void        exit();
138    virtual     bool        checkForNewParameters_l() = 0;
139    virtual     status_t    setParameters(const String8& keyValuePairs);
140    virtual     String8     getParameters(const String8& keys) = 0;
141    virtual     void        audioConfigChanged_l(int event, int param = 0) = 0;
142                void        sendIoConfigEvent(int event, int param = 0);
143                void        sendIoConfigEvent_l(int event, int param = 0);
144                void        sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio);
145                void        processConfigEvents();
146
147                // see note at declaration of mStandby, mOutDevice and mInDevice
148                bool        standby() const { return mStandby; }
149                audio_devices_t outDevice() const { return mOutDevice; }
150                audio_devices_t inDevice() const { return mInDevice; }
151
152    virtual     audio_stream_t* stream() const = 0;
153
154                sp<EffectHandle> createEffect_l(
155                                    const sp<AudioFlinger::Client>& client,
156                                    const sp<IEffectClient>& effectClient,
157                                    int32_t priority,
158                                    int sessionId,
159                                    effect_descriptor_t *desc,
160                                    int *enabled,
161                                    status_t *status);
162                void disconnectEffect(const sp< EffectModule>& effect,
163                                      EffectHandle *handle,
164                                      bool unpinIfLast);
165
166                // return values for hasAudioSession (bit field)
167                enum effect_state {
168                    EFFECT_SESSION = 0x1,   // the audio session corresponds to at least one
169                                            // effect
170                    TRACK_SESSION = 0x2     // the audio session corresponds to at least one
171                                            // track
172                };
173
174                // get effect chain corresponding to session Id.
175                sp<EffectChain> getEffectChain(int sessionId);
176                // same as getEffectChain() but must be called with ThreadBase mutex locked
177                sp<EffectChain> getEffectChain_l(int sessionId) const;
178                // add an effect chain to the chain list (mEffectChains)
179    virtual     status_t addEffectChain_l(const sp<EffectChain>& chain) = 0;
180                // remove an effect chain from the chain list (mEffectChains)
181    virtual     size_t removeEffectChain_l(const sp<EffectChain>& chain) = 0;
182                // lock all effect chains Mutexes. Must be called before releasing the
183                // ThreadBase mutex before processing the mixer and effects. This guarantees the
184                // integrity of the chains during the process.
185                // Also sets the parameter 'effectChains' to current value of mEffectChains.
186                void lockEffectChains_l(Vector< sp<EffectChain> >& effectChains);
187                // unlock effect chains after process
188                void unlockEffectChains(const Vector< sp<EffectChain> >& effectChains);
189                // get a copy of mEffectChains vector
190                Vector< sp<EffectChain> > getEffectChains_l() const { return mEffectChains; };
191                // set audio mode to all effect chains
192                void setMode(audio_mode_t mode);
193                // get effect module with corresponding ID on specified audio session
194                sp<AudioFlinger::EffectModule> getEffect(int sessionId, int effectId);
195                sp<AudioFlinger::EffectModule> getEffect_l(int sessionId, int effectId);
196                // add and effect module. Also creates the effect chain is none exists for
197                // the effects audio session
198                status_t addEffect_l(const sp< EffectModule>& effect);
199                // remove and effect module. Also removes the effect chain is this was the last
200                // effect
201                void removeEffect_l(const sp< EffectModule>& effect);
202                // detach all tracks connected to an auxiliary effect
203    virtual     void detachAuxEffect_l(int effectId) {}
204                // returns either EFFECT_SESSION if effects on this audio session exist in one
205                // chain, or TRACK_SESSION if tracks on this audio session exist, or both
206                virtual uint32_t hasAudioSession(int sessionId) const = 0;
207                // the value returned by default implementation is not important as the
208                // strategy is only meaningful for PlaybackThread which implements this method
209                virtual uint32_t getStrategyForSession_l(int sessionId) { return 0; }
210
211                // suspend or restore effect according to the type of effect passed. a NULL
212                // type pointer means suspend all effects in the session
213                void setEffectSuspended(const effect_uuid_t *type,
214                                        bool suspend,
215                                        int sessionId = AUDIO_SESSION_OUTPUT_MIX);
216                // check if some effects must be suspended/restored when an effect is enabled
217                // or disabled
218                void checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
219                                                 bool enabled,
220                                                 int sessionId = AUDIO_SESSION_OUTPUT_MIX);
221                void checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
222                                                   bool enabled,
223                                                   int sessionId = AUDIO_SESSION_OUTPUT_MIX);
224
225                virtual status_t    setSyncEvent(const sp<SyncEvent>& event) = 0;
226                virtual bool        isValidSyncEvent(const sp<SyncEvent>& event) const = 0;
227
228
229    mutable     Mutex                   mLock;
230
231protected:
232
233                // entry describing an effect being suspended in mSuspendedSessions keyed vector
234                class SuspendedSessionDesc : public RefBase {
235                public:
236                    SuspendedSessionDesc() : mRefCount(0) {}
237
238                    int mRefCount;          // number of active suspend requests
239                    effect_uuid_t mType;    // effect type UUID
240                };
241
242                void        acquireWakeLock();
243                void        acquireWakeLock_l();
244                void        releaseWakeLock();
245                void        releaseWakeLock_l();
246                void setEffectSuspended_l(const effect_uuid_t *type,
247                                          bool suspend,
248                                          int sessionId);
249                // updated mSuspendedSessions when an effect suspended or restored
250                void        updateSuspendedSessions_l(const effect_uuid_t *type,
251                                                      bool suspend,
252                                                      int sessionId);
253                // check if some effects must be suspended when an effect chain is added
254                void checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain);
255
256    virtual     void        preExit() { }
257
258    friend class AudioFlinger;      // for mEffectChains
259
260                const type_t            mType;
261
262                // Used by parameters, config events, addTrack_l, exit
263                Condition               mWaitWorkCV;
264
265                const sp<AudioFlinger>  mAudioFlinger;
266                uint32_t                mSampleRate;
267                size_t                  mFrameCount;       // output HAL, direct output, record
268                size_t                  mNormalFrameCount; // normal mixer and effects
269                audio_channel_mask_t    mChannelMask;
270                uint16_t                mChannelCount;
271                size_t                  mFrameSize;
272                audio_format_t          mFormat;
273
274                // Parameter sequence by client: binder thread calling setParameters():
275                //  1. Lock mLock
276                //  2. Append to mNewParameters
277                //  3. mWaitWorkCV.signal
278                //  4. mParamCond.waitRelative with timeout
279                //  5. read mParamStatus
280                //  6. mWaitWorkCV.signal
281                //  7. Unlock
282                //
283                // Parameter sequence by server: threadLoop calling checkForNewParameters_l():
284                // 1. Lock mLock
285                // 2. If there is an entry in mNewParameters proceed ...
286                // 2. Read first entry in mNewParameters
287                // 3. Process
288                // 4. Remove first entry from mNewParameters
289                // 5. Set mParamStatus
290                // 6. mParamCond.signal
291                // 7. mWaitWorkCV.wait with timeout (this is to avoid overwriting mParamStatus)
292                // 8. Unlock
293                Condition               mParamCond;
294                Vector<String8>         mNewParameters;
295                status_t                mParamStatus;
296
297                // vector owns each ConfigEvent *, so must delete after removing
298                Vector<ConfigEvent *>     mConfigEvents;
299
300                // These fields are written and read by thread itself without lock or barrier,
301                // and read by other threads without lock or barrier via standby() , outDevice()
302                // and inDevice().
303                // Because of the absence of a lock or barrier, any other thread that reads
304                // these fields must use the information in isolation, or be prepared to deal
305                // with possibility that it might be inconsistent with other information.
306                bool                    mStandby;   // Whether thread is currently in standby.
307                audio_devices_t         mOutDevice;   // output device
308                audio_devices_t         mInDevice;    // input device
309                audio_source_t          mAudioSource; // (see audio.h, audio_source_t)
310
311                const audio_io_handle_t mId;
312                Vector< sp<EffectChain> > mEffectChains;
313
314                static const int        kNameLength = 16;   // prctl(PR_SET_NAME) limit
315                char                    mName[kNameLength];
316                sp<IPowerManager>       mPowerManager;
317                sp<IBinder>             mWakeLockToken;
318                const sp<PMDeathRecipient> mDeathRecipient;
319                // list of suspended effects per session and per type. The first vector is
320                // keyed by session ID, the second by type UUID timeLow field
321                KeyedVector< int, KeyedVector< int, sp<SuspendedSessionDesc> > >
322                                        mSuspendedSessions;
323                static const size_t     kLogSize = 4 * 1024;
324                sp<NBLog::Writer>       mNBLogWriter;
325};
326
327// --- PlaybackThread ---
328class PlaybackThread : public ThreadBase {
329public:
330
331#include "PlaybackTracks.h"
332
333    enum mixer_state {
334        MIXER_IDLE,             // no active tracks
335        MIXER_TRACKS_ENABLED,   // at least one active track, but no track has any data ready
336        MIXER_TRACKS_READY,      // at least one active track, and at least one track has data
337        MIXER_DRAIN_TRACK,      // drain currently playing track
338        MIXER_DRAIN_ALL,        // fully drain the hardware
339        // standby mode does not have an enum value
340        // suspend by audio policy manager is orthogonal to mixer state
341    };
342
343    // retry count before removing active track in case of underrun on offloaded thread:
344    // we need to make sure that AudioTrack client has enough time to send large buffers
345//FIXME may be more appropriate if expressed in time units. Need to revise how underrun is handled
346    // for offloaded tracks
347    static const int8_t kMaxTrackRetriesOffload = 20;
348
349    PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
350                   audio_io_handle_t id, audio_devices_t device, type_t type);
351    virtual             ~PlaybackThread();
352
353                void        dump(int fd, const Vector<String16>& args);
354
355    // Thread virtuals
356    virtual     status_t    readyToRun();
357    virtual     bool        threadLoop();
358
359    // RefBase
360    virtual     void        onFirstRef();
361
362protected:
363    // Code snippets that were lifted up out of threadLoop()
364    virtual     void        threadLoop_mix() = 0;
365    virtual     void        threadLoop_sleepTime() = 0;
366    virtual     ssize_t     threadLoop_write();
367    virtual     void        threadLoop_drain();
368    virtual     void        threadLoop_standby();
369    virtual     void        threadLoop_exit();
370    virtual     void        threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
371
372                // prepareTracks_l reads and writes mActiveTracks, and returns
373                // the pending set of tracks to remove via Vector 'tracksToRemove'.  The caller
374                // is responsible for clearing or destroying this Vector later on, when it
375                // is safe to do so. That will drop the final ref count and destroy the tracks.
376    virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove) = 0;
377                void        removeTracks_l(const Vector< sp<Track> >& tracksToRemove);
378
379                void        writeCallback();
380                void        setWriteBlocked(bool value);
381                void        drainCallback();
382                void        setDraining(bool value);
383
384    static      int         asyncCallback(stream_callback_event_t event, void *param, void *cookie);
385
386    virtual     bool        waitingAsyncCallback();
387    virtual     bool        waitingAsyncCallback_l();
388    virtual     bool        shouldStandby_l();
389
390
391    // ThreadBase virtuals
392    virtual     void        preExit();
393
394public:
395
396    virtual     status_t    initCheck() const { return (mOutput == NULL) ? NO_INIT : NO_ERROR; }
397
398                // return estimated latency in milliseconds, as reported by HAL
399                uint32_t    latency() const;
400                // same, but lock must already be held
401                uint32_t    latency_l() const;
402
403                void        setMasterVolume(float value);
404                void        setMasterMute(bool muted);
405
406                void        setStreamVolume(audio_stream_type_t stream, float value);
407                void        setStreamMute(audio_stream_type_t stream, bool muted);
408
409                float       streamVolume(audio_stream_type_t stream) const;
410
411                sp<Track>   createTrack_l(
412                                const sp<AudioFlinger::Client>& client,
413                                audio_stream_type_t streamType,
414                                uint32_t sampleRate,
415                                audio_format_t format,
416                                audio_channel_mask_t channelMask,
417                                size_t frameCount,
418                                const sp<IMemory>& sharedBuffer,
419                                int sessionId,
420                                IAudioFlinger::track_flags_t *flags,
421                                pid_t tid,
422                                status_t *status);
423
424                AudioStreamOut* getOutput() const;
425                AudioStreamOut* clearOutput();
426                virtual audio_stream_t* stream() const;
427
428                // a very large number of suspend() will eventually wraparound, but unlikely
429                void        suspend() { (void) android_atomic_inc(&mSuspended); }
430                void        restore()
431                                {
432                                    // if restore() is done without suspend(), get back into
433                                    // range so that the next suspend() will operate correctly
434                                    if (android_atomic_dec(&mSuspended) <= 0) {
435                                        android_atomic_release_store(0, &mSuspended);
436                                    }
437                                }
438                bool        isSuspended() const
439                                { return android_atomic_acquire_load(&mSuspended) > 0; }
440
441    virtual     String8     getParameters(const String8& keys);
442    virtual     void        audioConfigChanged_l(int event, int param = 0);
443                status_t    getRenderPosition(size_t *halFrames, size_t *dspFrames);
444                int16_t     *mixBuffer() const { return mMixBuffer; };
445
446    virtual     void detachAuxEffect_l(int effectId);
447                status_t attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track> track,
448                        int EffectId);
449                status_t attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track> track,
450                        int EffectId);
451
452                virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
453                virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
454                virtual uint32_t hasAudioSession(int sessionId) const;
455                virtual uint32_t getStrategyForSession_l(int sessionId);
456
457
458                virtual status_t setSyncEvent(const sp<SyncEvent>& event);
459                virtual bool     isValidSyncEvent(const sp<SyncEvent>& event) const;
460
461                // called with AudioFlinger lock held
462                        void     invalidateTracks(audio_stream_type_t streamType);
463
464
465protected:
466    int16_t*                        mMixBuffer;         // frame size aligned mix buffer
467    int8_t*                         mAllocMixBuffer;    // mixer buffer allocation address
468
469    // suspend count, > 0 means suspended.  While suspended, the thread continues to pull from
470    // tracks and mix, but doesn't write to HAL.  A2DP and SCO HAL implementations can't handle
471    // concurrent use of both of them, so Audio Policy Service suspends one of the threads to
472    // workaround that restriction.
473    // 'volatile' means accessed via atomic operations and no lock.
474    volatile int32_t                mSuspended;
475
476    // FIXME overflows every 6+ hours at 44.1 kHz stereo 16-bit samples
477    // mFramesWritten would be better, or 64-bit even better
478    size_t                          mBytesWritten;
479private:
480    // mMasterMute is in both PlaybackThread and in AudioFlinger.  When a
481    // PlaybackThread needs to find out if master-muted, it checks it's local
482    // copy rather than the one in AudioFlinger.  This optimization saves a lock.
483    bool                            mMasterMute;
484                void        setMasterMute_l(bool muted) { mMasterMute = muted; }
485protected:
486    SortedVector< wp<Track> >       mActiveTracks;  // FIXME check if this could be sp<>
487
488    // Allocate a track name for a given channel mask.
489    //   Returns name >= 0 if successful, -1 on failure.
490    virtual int             getTrackName_l(audio_channel_mask_t channelMask, int sessionId) = 0;
491    virtual void            deleteTrackName_l(int name) = 0;
492
493    // Time to sleep between cycles when:
494    virtual uint32_t        activeSleepTimeUs() const;      // mixer state MIXER_TRACKS_ENABLED
495    virtual uint32_t        idleSleepTimeUs() const = 0;    // mixer state MIXER_IDLE
496    virtual uint32_t        suspendSleepTimeUs() const = 0; // audio policy manager suspended us
497    // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write()
498    // No sleep in standby mode; waits on a condition
499
500    // Code snippets that are temporarily lifted up out of threadLoop() until the merge
501                void        checkSilentMode_l();
502
503    // Non-trivial for DUPLICATING only
504    virtual     void        saveOutputTracks() { }
505    virtual     void        clearOutputTracks() { }
506
507    // Cache various calculated values, at threadLoop() entry and after a parameter change
508    virtual     void        cacheParameters_l();
509
510    virtual     uint32_t    correctLatency_l(uint32_t latency) const;
511
512private:
513
514    friend class AudioFlinger;      // for numerous
515
516    PlaybackThread(const Client&);
517    PlaybackThread& operator = (const PlaybackThread&);
518
519    status_t    addTrack_l(const sp<Track>& track);
520    bool        destroyTrack_l(const sp<Track>& track);
521    void        removeTrack_l(const sp<Track>& track);
522    void        signal_l();
523
524    void        readOutputParameters();
525
526    virtual void dumpInternals(int fd, const Vector<String16>& args);
527    void        dumpTracks(int fd, const Vector<String16>& args);
528
529    SortedVector< sp<Track> >       mTracks;
530    // mStreamTypes[] uses 1 additional stream type internally for the OutputTrack used by
531    // DuplicatingThread
532    stream_type_t                   mStreamTypes[AUDIO_STREAM_CNT + 1];
533    AudioStreamOut                  *mOutput;
534
535    float                           mMasterVolume;
536    nsecs_t                         mLastWriteTime;
537    int                             mNumWrites;
538    int                             mNumDelayedWrites;
539    bool                            mInWrite;
540
541    // FIXME rename these former local variables of threadLoop to standard "m" names
542    nsecs_t                         standbyTime;
543    size_t                          mixBufferSize;
544
545    // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l()
546    uint32_t                        activeSleepTime;
547    uint32_t                        idleSleepTime;
548
549    uint32_t                        sleepTime;
550
551    // mixer status returned by prepareTracks_l()
552    mixer_state                     mMixerStatus; // current cycle
553                                                  // previous cycle when in prepareTracks_l()
554    mixer_state                     mMixerStatusIgnoringFastTracks;
555                                                  // FIXME or a separate ready state per track
556
557    // FIXME move these declarations into the specific sub-class that needs them
558    // MIXER only
559    uint32_t                        sleepTimeShift;
560
561    // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value
562    nsecs_t                         standbyDelay;
563
564    // MIXER only
565    nsecs_t                         maxPeriod;
566
567    // DUPLICATING only
568    uint32_t                        writeFrames;
569
570    size_t                          mBytesRemaining;
571    size_t                          mCurrentWriteLength;
572    bool                            mUseAsyncWrite;
573    bool                            mWriteBlocked;
574    bool                            mDraining;
575    bool                            mSignalPending;
576    sp<AsyncCallbackThread>         mCallbackThread;
577
578private:
579    // The HAL output sink is treated as non-blocking, but current implementation is blocking
580    sp<NBAIO_Sink>          mOutputSink;
581    // If a fast mixer is present, the blocking pipe sink, otherwise clear
582    sp<NBAIO_Sink>          mPipeSink;
583    // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink
584    sp<NBAIO_Sink>          mNormalSink;
585#ifdef TEE_SINK
586    // For dumpsys
587    sp<NBAIO_Sink>          mTeeSink;
588    sp<NBAIO_Source>        mTeeSource;
589#endif
590    uint32_t                mScreenState;   // cached copy of gScreenState
591    static const size_t     kFastMixerLogSize = 4 * 1024;
592    sp<NBLog::Writer>       mFastMixerNBLogWriter;
593public:
594    virtual     bool        hasFastMixer() const = 0;
595    virtual     FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const
596                                { FastTrackUnderruns dummy; return dummy; }
597
598protected:
599                // accessed by both binder threads and within threadLoop(), lock on mutex needed
600                unsigned    mFastTrackAvailMask;    // bit i set if fast track [i] is available
601    virtual     void        flushOutput_l();
602};
603
604class MixerThread : public PlaybackThread {
605public:
606    MixerThread(const sp<AudioFlinger>& audioFlinger,
607                AudioStreamOut* output,
608                audio_io_handle_t id,
609                audio_devices_t device,
610                type_t type = MIXER);
611    virtual             ~MixerThread();
612
613    // Thread virtuals
614
615    virtual     bool        checkForNewParameters_l();
616    virtual     void        dumpInternals(int fd, const Vector<String16>& args);
617
618protected:
619    virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
620    virtual     int         getTrackName_l(audio_channel_mask_t channelMask, int sessionId);
621    virtual     void        deleteTrackName_l(int name);
622    virtual     uint32_t    idleSleepTimeUs() const;
623    virtual     uint32_t    suspendSleepTimeUs() const;
624    virtual     void        cacheParameters_l();
625
626    // threadLoop snippets
627    virtual     ssize_t     threadLoop_write();
628    virtual     void        threadLoop_standby();
629    virtual     void        threadLoop_mix();
630    virtual     void        threadLoop_sleepTime();
631    virtual     void        threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
632    virtual     uint32_t    correctLatency_l(uint32_t latency) const;
633
634                AudioMixer* mAudioMixer;    // normal mixer
635private:
636                // one-time initialization, no locks required
637                FastMixer*  mFastMixer;         // non-NULL if there is also a fast mixer
638                sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread
639
640                // contents are not guaranteed to be consistent, no locks required
641                FastMixerDumpState mFastMixerDumpState;
642#ifdef STATE_QUEUE_DUMP
643                StateQueueObserverDump mStateQueueObserverDump;
644                StateQueueMutatorDump  mStateQueueMutatorDump;
645#endif
646                AudioWatchdogDump mAudioWatchdogDump;
647
648                // accessible only within the threadLoop(), no locks required
649                //          mFastMixer->sq()    // for mutating and pushing state
650                int32_t     mFastMixerFutex;    // for cold idle
651
652public:
653    virtual     bool        hasFastMixer() const { return mFastMixer != NULL; }
654    virtual     FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const {
655                              ALOG_ASSERT(fastIndex < FastMixerState::kMaxFastTracks);
656                              return mFastMixerDumpState.mTracks[fastIndex].mUnderruns;
657                            }
658};
659
660class DirectOutputThread : public PlaybackThread {
661public:
662
663    DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
664                       audio_io_handle_t id, audio_devices_t device);
665    virtual                 ~DirectOutputThread();
666
667    // Thread virtuals
668
669    virtual     bool        checkForNewParameters_l();
670
671protected:
672    virtual     int         getTrackName_l(audio_channel_mask_t channelMask, int sessionId);
673    virtual     void        deleteTrackName_l(int name);
674    virtual     uint32_t    activeSleepTimeUs() const;
675    virtual     uint32_t    idleSleepTimeUs() const;
676    virtual     uint32_t    suspendSleepTimeUs() const;
677    virtual     void        cacheParameters_l();
678
679    // threadLoop snippets
680    virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
681    virtual     void        threadLoop_mix();
682    virtual     void        threadLoop_sleepTime();
683
684    // volumes last sent to audio HAL with stream->set_volume()
685    float mLeftVolFloat;
686    float mRightVolFloat;
687
688    DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
689                        audio_io_handle_t id, uint32_t device, ThreadBase::type_t type);
690    void processVolume_l(Track *track, bool lastTrack);
691
692    // prepareTracks_l() tells threadLoop_mix() the name of the single active track
693    sp<Track>               mActiveTrack;
694public:
695    virtual     bool        hasFastMixer() const { return false; }
696};
697
698class OffloadThread : public DirectOutputThread {
699public:
700
701    OffloadThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
702                        audio_io_handle_t id, uint32_t device);
703    virtual                 ~OffloadThread();
704
705protected:
706    // threadLoop snippets
707    virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
708    virtual     void        threadLoop_exit();
709    virtual     void        flushOutput_l();
710
711    virtual     bool        waitingAsyncCallback();
712    virtual     bool        waitingAsyncCallback_l();
713    virtual     bool        shouldStandby_l();
714
715private:
716                void        flushHw_l();
717
718private:
719    bool        mHwPaused;
720    bool        mFlushPending;
721    size_t      mPausedWriteLength;     // length in bytes of write interrupted by pause
722    size_t      mPausedBytesRemaining;  // bytes still waiting in mixbuffer after resume
723    sp<Track>   mPreviousTrack;         // used to detect track switch
724};
725
726class AsyncCallbackThread : public Thread {
727public:
728
729    AsyncCallbackThread(const sp<OffloadThread>& offloadThread);
730
731    virtual             ~AsyncCallbackThread();
732
733    // Thread virtuals
734    virtual bool        threadLoop();
735
736    // RefBase
737    virtual void        onFirstRef();
738
739            void        exit();
740            void        setWriteBlocked(bool value);
741            void        setDraining(bool value);
742
743private:
744    wp<OffloadThread>   mOffloadThread;
745    bool                mWriteBlocked;
746    bool                mDraining;
747    Condition           mWaitWorkCV;
748    Mutex               mLock;
749};
750
751class DuplicatingThread : public MixerThread {
752public:
753    DuplicatingThread(const sp<AudioFlinger>& audioFlinger, MixerThread* mainThread,
754                      audio_io_handle_t id);
755    virtual                 ~DuplicatingThread();
756
757    // Thread virtuals
758                void        addOutputTrack(MixerThread* thread);
759                void        removeOutputTrack(MixerThread* thread);
760                uint32_t    waitTimeMs() const { return mWaitTimeMs; }
761protected:
762    virtual     uint32_t    activeSleepTimeUs() const;
763
764private:
765                bool        outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks);
766protected:
767    // threadLoop snippets
768    virtual     void        threadLoop_mix();
769    virtual     void        threadLoop_sleepTime();
770    virtual     ssize_t     threadLoop_write();
771    virtual     void        threadLoop_standby();
772    virtual     void        cacheParameters_l();
773
774private:
775    // called from threadLoop, addOutputTrack, removeOutputTrack
776    virtual     void        updateWaitTime_l();
777protected:
778    virtual     void        saveOutputTracks();
779    virtual     void        clearOutputTracks();
780private:
781
782                uint32_t    mWaitTimeMs;
783    SortedVector < sp<OutputTrack> >  outputTracks;
784    SortedVector < sp<OutputTrack> >  mOutputTracks;
785public:
786    virtual     bool        hasFastMixer() const { return false; }
787};
788
789
790// record thread
791class RecordThread : public ThreadBase, public AudioBufferProvider
792                        // derives from AudioBufferProvider interface for use by resampler
793{
794public:
795
796#include "RecordTracks.h"
797
798            RecordThread(const sp<AudioFlinger>& audioFlinger,
799                    AudioStreamIn *input,
800                    uint32_t sampleRate,
801                    audio_channel_mask_t channelMask,
802                    audio_io_handle_t id,
803                    audio_devices_t outDevice,
804                    audio_devices_t inDevice
805#ifdef TEE_SINK
806                    , const sp<NBAIO_Sink>& teeSink
807#endif
808                    );
809            virtual     ~RecordThread();
810
811    // no addTrack_l ?
812    void        destroyTrack_l(const sp<RecordTrack>& track);
813    void        removeTrack_l(const sp<RecordTrack>& track);
814
815    void        dumpInternals(int fd, const Vector<String16>& args);
816    void        dumpTracks(int fd, const Vector<String16>& args);
817
818    // Thread virtuals
819    virtual bool        threadLoop();
820    virtual status_t    readyToRun();
821
822    // RefBase
823    virtual void        onFirstRef();
824
825    virtual status_t    initCheck() const { return (mInput == NULL) ? NO_INIT : NO_ERROR; }
826            sp<AudioFlinger::RecordThread::RecordTrack>  createRecordTrack_l(
827                    const sp<AudioFlinger::Client>& client,
828                    uint32_t sampleRate,
829                    audio_format_t format,
830                    audio_channel_mask_t channelMask,
831                    size_t frameCount,
832                    int sessionId,
833                    IAudioFlinger::track_flags_t flags,
834                    pid_t tid,
835                    status_t *status);
836
837            status_t    start(RecordTrack* recordTrack,
838                              AudioSystem::sync_event_t event,
839                              int triggerSession);
840
841            // ask the thread to stop the specified track, and
842            // return true if the caller should then do it's part of the stopping process
843            bool        stop_l(RecordTrack* recordTrack);
844
845            void        dump(int fd, const Vector<String16>& args);
846            AudioStreamIn* clearInput();
847            virtual audio_stream_t* stream() const;
848
849    // AudioBufferProvider interface
850    virtual status_t    getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts);
851    virtual void        releaseBuffer(AudioBufferProvider::Buffer* buffer);
852
853    virtual bool        checkForNewParameters_l();
854    virtual String8     getParameters(const String8& keys);
855    virtual void        audioConfigChanged_l(int event, int param = 0);
856            void        readInputParameters();
857    virtual unsigned int  getInputFramesLost();
858
859    virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
860    virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
861    virtual uint32_t hasAudioSession(int sessionId) const;
862
863            // Return the set of unique session IDs across all tracks.
864            // The keys are the session IDs, and the associated values are meaningless.
865            // FIXME replace by Set [and implement Bag/Multiset for other uses].
866            KeyedVector<int, bool> sessionIds() const;
867
868    virtual status_t setSyncEvent(const sp<SyncEvent>& event);
869    virtual bool     isValidSyncEvent(const sp<SyncEvent>& event) const;
870
871    static void syncStartEventCallback(const wp<SyncEvent>& event);
872           void handleSyncStartEvent(const sp<SyncEvent>& event);
873
874private:
875            void clearSyncStartEvent();
876
877            // Enter standby if not already in standby, and set mStandby flag
878            void standby();
879
880            // Call the HAL standby method unconditionally, and don't change mStandby flag
881            void inputStandBy();
882
883            AudioStreamIn                       *mInput;
884            SortedVector < sp<RecordTrack> >    mTracks;
885            // mActiveTrack has dual roles:  it indicates the current active track, and
886            // is used together with mStartStopCond to indicate start()/stop() progress
887            sp<RecordTrack>                     mActiveTrack;
888            Condition                           mStartStopCond;
889            AudioResampler                      *mResampler;
890            int32_t                             *mRsmpOutBuffer;
891            int16_t                             *mRsmpInBuffer;
892            size_t                              mRsmpInIndex;
893            size_t                              mInputBytes;
894            const uint32_t                      mReqChannelCount;
895            const uint32_t                      mReqSampleRate;
896            ssize_t                             mBytesRead;
897            // sync event triggering actual audio capture. Frames read before this event will
898            // be dropped and therefore not read by the application.
899            sp<SyncEvent>                       mSyncStartEvent;
900            // number of captured frames to drop after the start sync event has been received.
901            // when < 0, maximum frames to drop before starting capture even if sync event is
902            // not received
903            ssize_t                             mFramestoDrop;
904
905            // For dumpsys
906            const sp<NBAIO_Sink>                mTeeSink;
907};
908