Threads.h revision e198c360d5e75a9b2097844c495c10902e7e8500
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    virtual status_t    readyToRun();
40
41    void dumpBase(int fd, const Vector<String16>& args);
42    void dumpEffectChains(int fd, const Vector<String16>& args);
43
44    void clearPowerManager();
45
46    // base for record and playback
47    enum {
48        CFG_EVENT_IO,
49        CFG_EVENT_PRIO
50    };
51
52    class ConfigEvent {
53    public:
54        ConfigEvent(int type) : mType(type) {}
55        virtual ~ConfigEvent() {}
56
57                 int type() const { return mType; }
58
59        virtual  void dump(char *buffer, size_t size) = 0;
60
61    private:
62        const int mType;
63    };
64
65    class IoConfigEvent : public ConfigEvent {
66    public:
67        IoConfigEvent(int event, int param) :
68            ConfigEvent(CFG_EVENT_IO), mEvent(event), mParam(event) {}
69        virtual ~IoConfigEvent() {}
70
71                int event() const { return mEvent; }
72                int param() const { return mParam; }
73
74        virtual  void dump(char *buffer, size_t size) {
75            snprintf(buffer, size, "IO event: event %d, param %d\n", mEvent, mParam);
76        }
77
78    private:
79        const int mEvent;
80        const int mParam;
81    };
82
83    class PrioConfigEvent : public ConfigEvent {
84    public:
85        PrioConfigEvent(pid_t pid, pid_t tid, int32_t prio) :
86            ConfigEvent(CFG_EVENT_PRIO), mPid(pid), mTid(tid), mPrio(prio) {}
87        virtual ~PrioConfigEvent() {}
88
89                pid_t pid() const { return mPid; }
90                pid_t tid() const { return mTid; }
91                int32_t prio() const { return mPrio; }
92
93        virtual  void dump(char *buffer, size_t size) {
94            snprintf(buffer, size, "Prio event: pid %d, tid %d, prio %d\n", mPid, mTid, mPrio);
95        }
96
97    private:
98        const pid_t mPid;
99        const pid_t mTid;
100        const int32_t mPrio;
101    };
102
103
104    class PMDeathRecipient : public IBinder::DeathRecipient {
105    public:
106                    PMDeathRecipient(const wp<ThreadBase>& thread) : mThread(thread) {}
107        virtual     ~PMDeathRecipient() {}
108
109        // IBinder::DeathRecipient
110        virtual     void        binderDied(const wp<IBinder>& who);
111
112    private:
113                    PMDeathRecipient(const PMDeathRecipient&);
114                    PMDeathRecipient& operator = (const PMDeathRecipient&);
115
116        wp<ThreadBase> mThread;
117    };
118
119    virtual     status_t    initCheck() const = 0;
120
121                // static externally-visible
122                type_t      type() const { return mType; }
123                audio_io_handle_t id() const { return mId;}
124
125                // dynamic externally-visible
126                uint32_t    sampleRate() const { return mSampleRate; }
127                uint32_t    channelCount() const { return mChannelCount; }
128                audio_channel_mask_t channelMask() const { return mChannelMask; }
129                audio_format_t format() const { return mFormat; }
130                // Called by AudioFlinger::frameCount(audio_io_handle_t output) and effects,
131                // and returns the [normal mix] buffer's frame count.
132    virtual     size_t      frameCount() const = 0;
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 /*non-NULL*/);
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
267                // updated by PlaybackThread::readOutputParameters() or
268                // RecordThread::readInputParameters()
269                uint32_t                mSampleRate;
270                size_t                  mFrameCount;       // output HAL, direct output, record
271                audio_channel_mask_t    mChannelMask;
272                uint32_t                mChannelCount;
273                size_t                  mFrameSize;
274                audio_format_t          mFormat;
275                size_t                  mBufferSize;       // HAL buffer size for read() or write()
276
277                // Parameter sequence by client: binder thread calling setParameters():
278                //  1. Lock mLock
279                //  2. Append to mNewParameters
280                //  3. mWaitWorkCV.signal
281                //  4. mParamCond.waitRelative with timeout
282                //  5. read mParamStatus
283                //  6. mWaitWorkCV.signal
284                //  7. Unlock
285                //
286                // Parameter sequence by server: threadLoop calling checkForNewParameters_l():
287                // 1. Lock mLock
288                // 2. If there is an entry in mNewParameters proceed ...
289                // 2. Read first entry in mNewParameters
290                // 3. Process
291                // 4. Remove first entry from mNewParameters
292                // 5. Set mParamStatus
293                // 6. mParamCond.signal
294                // 7. mWaitWorkCV.wait with timeout (this is to avoid overwriting mParamStatus)
295                // 8. Unlock
296                Condition               mParamCond;
297                Vector<String8>         mNewParameters;
298                status_t                mParamStatus;
299
300                // vector owns each ConfigEvent *, so must delete after removing
301                Vector<ConfigEvent *>     mConfigEvents;
302
303                // These fields are written and read by thread itself without lock or barrier,
304                // and read by other threads without lock or barrier via standby() , outDevice()
305                // and inDevice().
306                // Because of the absence of a lock or barrier, any other thread that reads
307                // these fields must use the information in isolation, or be prepared to deal
308                // with possibility that it might be inconsistent with other information.
309                bool                    mStandby;   // Whether thread is currently in standby.
310                audio_devices_t         mOutDevice;   // output device
311                audio_devices_t         mInDevice;    // input device
312                audio_source_t          mAudioSource; // (see audio.h, audio_source_t)
313
314                const audio_io_handle_t mId;
315                Vector< sp<EffectChain> > mEffectChains;
316
317                static const int        kNameLength = 16;   // prctl(PR_SET_NAME) limit
318                char                    mName[kNameLength];
319                sp<IPowerManager>       mPowerManager;
320                sp<IBinder>             mWakeLockToken;
321                const sp<PMDeathRecipient> mDeathRecipient;
322                // list of suspended effects per session and per type. The first vector is
323                // keyed by session ID, the second by type UUID timeLow field
324                KeyedVector< int, KeyedVector< int, sp<SuspendedSessionDesc> > >
325                                        mSuspendedSessions;
326                static const size_t     kLogSize = 4 * 1024;
327                sp<NBLog::Writer>       mNBLogWriter;
328};
329
330// --- PlaybackThread ---
331class PlaybackThread : public ThreadBase {
332public:
333
334#include "PlaybackTracks.h"
335
336    enum mixer_state {
337        MIXER_IDLE,             // no active tracks
338        MIXER_TRACKS_ENABLED,   // at least one active track, but no track has any data ready
339        MIXER_TRACKS_READY,      // at least one active track, and at least one track has data
340        MIXER_DRAIN_TRACK,      // drain currently playing track
341        MIXER_DRAIN_ALL,        // fully drain the hardware
342        // standby mode does not have an enum value
343        // suspend by audio policy manager is orthogonal to mixer state
344    };
345
346    // retry count before removing active track in case of underrun on offloaded thread:
347    // we need to make sure that AudioTrack client has enough time to send large buffers
348//FIXME may be more appropriate if expressed in time units. Need to revise how underrun is handled
349    // for offloaded tracks
350    static const int8_t kMaxTrackRetriesOffload = 20;
351
352    PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
353                   audio_io_handle_t id, audio_devices_t device, type_t type);
354    virtual             ~PlaybackThread();
355
356                void        dump(int fd, const Vector<String16>& args);
357
358    // Thread virtuals
359    virtual     bool        threadLoop();
360
361    // RefBase
362    virtual     void        onFirstRef();
363
364protected:
365    // Code snippets that were lifted up out of threadLoop()
366    virtual     void        threadLoop_mix() = 0;
367    virtual     void        threadLoop_sleepTime() = 0;
368    virtual     ssize_t     threadLoop_write();
369    virtual     void        threadLoop_drain();
370    virtual     void        threadLoop_standby();
371    virtual     void        threadLoop_exit();
372    virtual     void        threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
373
374                // prepareTracks_l reads and writes mActiveTracks, and returns
375                // the pending set of tracks to remove via Vector 'tracksToRemove'.  The caller
376                // is responsible for clearing or destroying this Vector later on, when it
377                // is safe to do so. That will drop the final ref count and destroy the tracks.
378    virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove) = 0;
379                void        removeTracks_l(const Vector< sp<Track> >& tracksToRemove);
380
381                void        writeCallback();
382                void        setWriteBlocked(bool value);
383                void        drainCallback();
384                void        setDraining(bool value);
385
386    static      int         asyncCallback(stream_callback_event_t event, void *param, void *cookie);
387
388    virtual     bool        waitingAsyncCallback();
389    virtual     bool        waitingAsyncCallback_l();
390    virtual     bool        shouldStandby_l();
391
392
393    // ThreadBase virtuals
394    virtual     void        preExit();
395
396public:
397
398    virtual     status_t    initCheck() const { return (mOutput == NULL) ? NO_INIT : NO_ERROR; }
399
400                // return estimated latency in milliseconds, as reported by HAL
401                uint32_t    latency() const;
402                // same, but lock must already be held
403                uint32_t    latency_l() const;
404
405                void        setMasterVolume(float value);
406                void        setMasterMute(bool muted);
407
408                void        setStreamVolume(audio_stream_type_t stream, float value);
409                void        setStreamMute(audio_stream_type_t stream, bool muted);
410
411                float       streamVolume(audio_stream_type_t stream) const;
412
413                sp<Track>   createTrack_l(
414                                const sp<AudioFlinger::Client>& client,
415                                audio_stream_type_t streamType,
416                                uint32_t sampleRate,
417                                audio_format_t format,
418                                audio_channel_mask_t channelMask,
419                                size_t frameCount,
420                                const sp<IMemory>& sharedBuffer,
421                                int sessionId,
422                                IAudioFlinger::track_flags_t *flags,
423                                pid_t tid,
424                                status_t *status /*non-NULL*/);
425
426                AudioStreamOut* getOutput() const;
427                AudioStreamOut* clearOutput();
428                virtual audio_stream_t* stream() const;
429
430                // a very large number of suspend() will eventually wraparound, but unlikely
431                void        suspend() { (void) android_atomic_inc(&mSuspended); }
432                void        restore()
433                                {
434                                    // if restore() is done without suspend(), get back into
435                                    // range so that the next suspend() will operate correctly
436                                    if (android_atomic_dec(&mSuspended) <= 0) {
437                                        android_atomic_release_store(0, &mSuspended);
438                                    }
439                                }
440                bool        isSuspended() const
441                                { return android_atomic_acquire_load(&mSuspended) > 0; }
442
443    virtual     String8     getParameters(const String8& keys);
444    virtual     void        audioConfigChanged_l(int event, int param = 0);
445                status_t    getRenderPosition(size_t *halFrames, size_t *dspFrames);
446                int16_t     *mixBuffer() const { return mMixBuffer; };
447
448    virtual     void detachAuxEffect_l(int effectId);
449                status_t attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track> track,
450                        int EffectId);
451                status_t attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track> track,
452                        int EffectId);
453
454                virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
455                virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
456                virtual uint32_t hasAudioSession(int sessionId) const;
457                virtual uint32_t getStrategyForSession_l(int sessionId);
458
459
460                virtual status_t setSyncEvent(const sp<SyncEvent>& event);
461                virtual bool     isValidSyncEvent(const sp<SyncEvent>& event) const;
462
463                // called with AudioFlinger lock held
464                        void     invalidateTracks(audio_stream_type_t streamType);
465
466    virtual     size_t      frameCount() const { return mNormalFrameCount; }
467
468                // Return's the HAL's frame count i.e. fast mixer buffer size.
469                size_t      frameCountHAL() const { return mFrameCount; }
470
471protected:
472    // updated by readOutputParameters()
473    size_t                          mNormalFrameCount;  // normal mixer and effects
474
475    int16_t*                        mMixBuffer;         // frame size aligned mix buffer
476
477    // suspend count, > 0 means suspended.  While suspended, the thread continues to pull from
478    // tracks and mix, but doesn't write to HAL.  A2DP and SCO HAL implementations can't handle
479    // concurrent use of both of them, so Audio Policy Service suspends one of the threads to
480    // workaround that restriction.
481    // 'volatile' means accessed via atomic operations and no lock.
482    volatile int32_t                mSuspended;
483
484    // FIXME overflows every 6+ hours at 44.1 kHz stereo 16-bit samples
485    // mFramesWritten would be better, or 64-bit even better
486    size_t                          mBytesWritten;
487private:
488    // mMasterMute is in both PlaybackThread and in AudioFlinger.  When a
489    // PlaybackThread needs to find out if master-muted, it checks it's local
490    // copy rather than the one in AudioFlinger.  This optimization saves a lock.
491    bool                            mMasterMute;
492                void        setMasterMute_l(bool muted) { mMasterMute = muted; }
493protected:
494    SortedVector< wp<Track> >       mActiveTracks;  // FIXME check if this could be sp<>
495
496    // Allocate a track name for a given channel mask.
497    //   Returns name >= 0 if successful, -1 on failure.
498    virtual int             getTrackName_l(audio_channel_mask_t channelMask, int sessionId) = 0;
499    virtual void            deleteTrackName_l(int name) = 0;
500
501    // Time to sleep between cycles when:
502    virtual uint32_t        activeSleepTimeUs() const;      // mixer state MIXER_TRACKS_ENABLED
503    virtual uint32_t        idleSleepTimeUs() const = 0;    // mixer state MIXER_IDLE
504    virtual uint32_t        suspendSleepTimeUs() const = 0; // audio policy manager suspended us
505    // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write()
506    // No sleep in standby mode; waits on a condition
507
508    // Code snippets that are temporarily lifted up out of threadLoop() until the merge
509                void        checkSilentMode_l();
510
511    // Non-trivial for DUPLICATING only
512    virtual     void        saveOutputTracks() { }
513    virtual     void        clearOutputTracks() { }
514
515    // Cache various calculated values, at threadLoop() entry and after a parameter change
516    virtual     void        cacheParameters_l();
517
518    virtual     uint32_t    correctLatency_l(uint32_t latency) const;
519
520private:
521
522    friend class AudioFlinger;      // for numerous
523
524    PlaybackThread(const Client&);
525    PlaybackThread& operator = (const PlaybackThread&);
526
527    status_t    addTrack_l(const sp<Track>& track);
528    bool        destroyTrack_l(const sp<Track>& track);
529    void        removeTrack_l(const sp<Track>& track);
530    void        signal_l();
531
532    void        readOutputParameters();
533
534    virtual void dumpInternals(int fd, const Vector<String16>& args);
535    void        dumpTracks(int fd, const Vector<String16>& args);
536
537    SortedVector< sp<Track> >       mTracks;
538    // mStreamTypes[] uses 1 additional stream type internally for the OutputTrack used by
539    // DuplicatingThread
540    stream_type_t                   mStreamTypes[AUDIO_STREAM_CNT + 1];
541    AudioStreamOut                  *mOutput;
542
543    float                           mMasterVolume;
544    nsecs_t                         mLastWriteTime;
545    int                             mNumWrites;
546    int                             mNumDelayedWrites;
547    bool                            mInWrite;
548
549    // FIXME rename these former local variables of threadLoop to standard "m" names
550    nsecs_t                         standbyTime;
551    size_t                          mixBufferSize;
552
553    // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l()
554    uint32_t                        activeSleepTime;
555    uint32_t                        idleSleepTime;
556
557    uint32_t                        sleepTime;
558
559    // mixer status returned by prepareTracks_l()
560    mixer_state                     mMixerStatus; // current cycle
561                                                  // previous cycle when in prepareTracks_l()
562    mixer_state                     mMixerStatusIgnoringFastTracks;
563                                                  // FIXME or a separate ready state per track
564
565    // FIXME move these declarations into the specific sub-class that needs them
566    // MIXER only
567    uint32_t                        sleepTimeShift;
568
569    // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value
570    nsecs_t                         standbyDelay;
571
572    // MIXER only
573    nsecs_t                         maxPeriod;
574
575    // DUPLICATING only
576    uint32_t                        writeFrames;
577
578    size_t                          mBytesRemaining;
579    size_t                          mCurrentWriteLength;
580    bool                            mUseAsyncWrite;
581    bool                            mWriteBlocked;
582    bool                            mDraining;
583    bool                            mSignalPending;
584    sp<AsyncCallbackThread>         mCallbackThread;
585
586private:
587    // The HAL output sink is treated as non-blocking, but current implementation is blocking
588    sp<NBAIO_Sink>          mOutputSink;
589    // If a fast mixer is present, the blocking pipe sink, otherwise clear
590    sp<NBAIO_Sink>          mPipeSink;
591    // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink
592    sp<NBAIO_Sink>          mNormalSink;
593#ifdef TEE_SINK
594    // For dumpsys
595    sp<NBAIO_Sink>          mTeeSink;
596    sp<NBAIO_Source>        mTeeSource;
597#endif
598    uint32_t                mScreenState;   // cached copy of gScreenState
599    static const size_t     kFastMixerLogSize = 4 * 1024;
600    sp<NBLog::Writer>       mFastMixerNBLogWriter;
601public:
602    virtual     bool        hasFastMixer() const = 0;
603    virtual     FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const
604                                { FastTrackUnderruns dummy; return dummy; }
605
606protected:
607                // accessed by both binder threads and within threadLoop(), lock on mutex needed
608                unsigned    mFastTrackAvailMask;    // bit i set if fast track [i] is available
609    virtual     void        flushOutput_l();
610};
611
612class MixerThread : public PlaybackThread {
613public:
614    MixerThread(const sp<AudioFlinger>& audioFlinger,
615                AudioStreamOut* output,
616                audio_io_handle_t id,
617                audio_devices_t device,
618                type_t type = MIXER);
619    virtual             ~MixerThread();
620
621    // Thread virtuals
622
623    virtual     bool        checkForNewParameters_l();
624    virtual     void        dumpInternals(int fd, const Vector<String16>& args);
625
626protected:
627    virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
628    virtual     int         getTrackName_l(audio_channel_mask_t channelMask, int sessionId);
629    virtual     void        deleteTrackName_l(int name);
630    virtual     uint32_t    idleSleepTimeUs() const;
631    virtual     uint32_t    suspendSleepTimeUs() const;
632    virtual     void        cacheParameters_l();
633
634    // threadLoop snippets
635    virtual     ssize_t     threadLoop_write();
636    virtual     void        threadLoop_standby();
637    virtual     void        threadLoop_mix();
638    virtual     void        threadLoop_sleepTime();
639    virtual     void        threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
640    virtual     uint32_t    correctLatency_l(uint32_t latency) const;
641
642                AudioMixer* mAudioMixer;    // normal mixer
643private:
644                // one-time initialization, no locks required
645                FastMixer*  mFastMixer;         // non-NULL if there is also a fast mixer
646                sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread
647
648                // contents are not guaranteed to be consistent, no locks required
649                FastMixerDumpState mFastMixerDumpState;
650#ifdef STATE_QUEUE_DUMP
651                StateQueueObserverDump mStateQueueObserverDump;
652                StateQueueMutatorDump  mStateQueueMutatorDump;
653#endif
654                AudioWatchdogDump mAudioWatchdogDump;
655
656                // accessible only within the threadLoop(), no locks required
657                //          mFastMixer->sq()    // for mutating and pushing state
658                int32_t     mFastMixerFutex;    // for cold idle
659
660public:
661    virtual     bool        hasFastMixer() const { return mFastMixer != NULL; }
662    virtual     FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const {
663                              ALOG_ASSERT(fastIndex < FastMixerState::kMaxFastTracks);
664                              return mFastMixerDumpState.mTracks[fastIndex].mUnderruns;
665                            }
666};
667
668class DirectOutputThread : public PlaybackThread {
669public:
670
671    DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
672                       audio_io_handle_t id, audio_devices_t device);
673    virtual                 ~DirectOutputThread();
674
675    // Thread virtuals
676
677    virtual     bool        checkForNewParameters_l();
678
679protected:
680    virtual     int         getTrackName_l(audio_channel_mask_t channelMask, int sessionId);
681    virtual     void        deleteTrackName_l(int name);
682    virtual     uint32_t    activeSleepTimeUs() const;
683    virtual     uint32_t    idleSleepTimeUs() const;
684    virtual     uint32_t    suspendSleepTimeUs() const;
685    virtual     void        cacheParameters_l();
686
687    // threadLoop snippets
688    virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
689    virtual     void        threadLoop_mix();
690    virtual     void        threadLoop_sleepTime();
691
692    // volumes last sent to audio HAL with stream->set_volume()
693    float mLeftVolFloat;
694    float mRightVolFloat;
695
696    DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
697                        audio_io_handle_t id, uint32_t device, ThreadBase::type_t type);
698    void processVolume_l(Track *track, bool lastTrack);
699
700    // prepareTracks_l() tells threadLoop_mix() the name of the single active track
701    sp<Track>               mActiveTrack;
702public:
703    virtual     bool        hasFastMixer() const { return false; }
704};
705
706class OffloadThread : public DirectOutputThread {
707public:
708
709    OffloadThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
710                        audio_io_handle_t id, uint32_t device);
711    virtual                 ~OffloadThread();
712
713protected:
714    // threadLoop snippets
715    virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
716    virtual     void        threadLoop_exit();
717    virtual     void        flushOutput_l();
718
719    virtual     bool        waitingAsyncCallback();
720    virtual     bool        waitingAsyncCallback_l();
721    virtual     bool        shouldStandby_l();
722
723private:
724                void        flushHw_l();
725
726private:
727    bool        mHwPaused;
728    bool        mFlushPending;
729    size_t      mPausedWriteLength;     // length in bytes of write interrupted by pause
730    size_t      mPausedBytesRemaining;  // bytes still waiting in mixbuffer after resume
731    sp<Track>   mPreviousTrack;         // used to detect track switch
732};
733
734class AsyncCallbackThread : public Thread {
735public:
736
737    AsyncCallbackThread(const sp<OffloadThread>& offloadThread);
738
739    virtual             ~AsyncCallbackThread();
740
741    // Thread virtuals
742    virtual bool        threadLoop();
743
744    // RefBase
745    virtual void        onFirstRef();
746
747            void        exit();
748            void        setWriteBlocked(bool value);
749            void        setDraining(bool value);
750
751private:
752    wp<OffloadThread>   mOffloadThread;
753    bool                mWriteBlocked;
754    bool                mDraining;
755    Condition           mWaitWorkCV;
756    Mutex               mLock;
757};
758
759class DuplicatingThread : public MixerThread {
760public:
761    DuplicatingThread(const sp<AudioFlinger>& audioFlinger, MixerThread* mainThread,
762                      audio_io_handle_t id);
763    virtual                 ~DuplicatingThread();
764
765    // Thread virtuals
766                void        addOutputTrack(MixerThread* thread);
767                void        removeOutputTrack(MixerThread* thread);
768                uint32_t    waitTimeMs() const { return mWaitTimeMs; }
769protected:
770    virtual     uint32_t    activeSleepTimeUs() const;
771
772private:
773                bool        outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks);
774protected:
775    // threadLoop snippets
776    virtual     void        threadLoop_mix();
777    virtual     void        threadLoop_sleepTime();
778    virtual     ssize_t     threadLoop_write();
779    virtual     void        threadLoop_standby();
780    virtual     void        cacheParameters_l();
781
782private:
783    // called from threadLoop, addOutputTrack, removeOutputTrack
784    virtual     void        updateWaitTime_l();
785protected:
786    virtual     void        saveOutputTracks();
787    virtual     void        clearOutputTracks();
788private:
789
790                uint32_t    mWaitTimeMs;
791    SortedVector < sp<OutputTrack> >  outputTracks;
792    SortedVector < sp<OutputTrack> >  mOutputTracks;
793public:
794    virtual     bool        hasFastMixer() const { return false; }
795};
796
797
798// record thread
799class RecordThread : public ThreadBase, public AudioBufferProvider
800                        // derives from AudioBufferProvider interface for use by resampler
801{
802public:
803
804#include "RecordTracks.h"
805
806            RecordThread(const sp<AudioFlinger>& audioFlinger,
807                    AudioStreamIn *input,
808                    uint32_t sampleRate,
809                    audio_channel_mask_t channelMask,
810                    audio_io_handle_t id,
811                    audio_devices_t outDevice,
812                    audio_devices_t inDevice
813#ifdef TEE_SINK
814                    , const sp<NBAIO_Sink>& teeSink
815#endif
816                    );
817            virtual     ~RecordThread();
818
819    // no addTrack_l ?
820    void        destroyTrack_l(const sp<RecordTrack>& track);
821    void        removeTrack_l(const sp<RecordTrack>& track);
822
823    void        dumpInternals(int fd, const Vector<String16>& args);
824    void        dumpTracks(int fd, const Vector<String16>& args);
825
826    // Thread virtuals
827    virtual bool        threadLoop();
828
829    // RefBase
830    virtual void        onFirstRef();
831
832    virtual status_t    initCheck() const { return (mInput == NULL) ? NO_INIT : NO_ERROR; }
833
834            sp<AudioFlinger::RecordThread::RecordTrack>  createRecordTrack_l(
835                    const sp<AudioFlinger::Client>& client,
836                    uint32_t sampleRate,
837                    audio_format_t format,
838                    audio_channel_mask_t channelMask,
839                    size_t frameCount,
840                    int sessionId,
841                    IAudioFlinger::track_flags_t *flags,
842                    pid_t tid,
843                    status_t *status /*non-NULL*/);
844
845            status_t    start(RecordTrack* recordTrack,
846                              AudioSystem::sync_event_t event,
847                              int triggerSession);
848
849            // ask the thread to stop the specified track, and
850            // return true if the caller should then do it's part of the stopping process
851            bool        stop(RecordTrack* recordTrack);
852
853            void        dump(int fd, const Vector<String16>& args);
854            AudioStreamIn* clearInput();
855            virtual audio_stream_t* stream() const;
856
857    // AudioBufferProvider interface
858    virtual status_t    getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts);
859    virtual void        releaseBuffer(AudioBufferProvider::Buffer* buffer);
860
861    virtual bool        checkForNewParameters_l();
862    virtual String8     getParameters(const String8& keys);
863    virtual void        audioConfigChanged_l(int event, int param = 0);
864            void        readInputParameters();
865    virtual unsigned int  getInputFramesLost();
866
867    virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
868    virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
869    virtual uint32_t hasAudioSession(int sessionId) const;
870
871            // Return the set of unique session IDs across all tracks.
872            // The keys are the session IDs, and the associated values are meaningless.
873            // FIXME replace by Set [and implement Bag/Multiset for other uses].
874            KeyedVector<int, bool> sessionIds() const;
875
876    virtual status_t setSyncEvent(const sp<SyncEvent>& event);
877    virtual bool     isValidSyncEvent(const sp<SyncEvent>& event) const;
878
879    static void syncStartEventCallback(const wp<SyncEvent>& event);
880           void handleSyncStartEvent(const sp<SyncEvent>& event);
881
882    virtual size_t      frameCount() const { return mFrameCount; }
883            bool        hasFastRecorder() const { return false; }
884
885private:
886            void    clearSyncStartEvent();
887
888            // Enter standby if not already in standby, and set mStandby flag
889            void    standby();
890
891            // Call the HAL standby method unconditionally, and don't change mStandby flag
892            void    inputStandBy();
893
894            AudioStreamIn                       *mInput;
895            SortedVector < sp<RecordTrack> >    mTracks;
896            // mActiveTrack has dual roles:  it indicates the current active track, and
897            // is used together with mStartStopCond to indicate start()/stop() progress
898            sp<RecordTrack>                     mActiveTrack;
899            Condition                           mStartStopCond;
900
901            // updated by RecordThread::readInputParameters()
902            AudioResampler                      *mResampler;
903            // interleaved stereo pairs of fixed-point signed Q19.12
904            int32_t                             *mRsmpOutBuffer;
905            int16_t                             *mRsmpInBuffer; // [mFrameCount * mChannelCount]
906            size_t                              mRsmpInIndex;
907            const uint32_t                      mReqChannelCount;
908            const uint32_t                      mReqSampleRate;
909            ssize_t                             mBytesRead;
910            // sync event triggering actual audio capture. Frames read before this event will
911            // be dropped and therefore not read by the application.
912            sp<SyncEvent>                       mSyncStartEvent;
913            // number of captured frames to drop after the start sync event has been received.
914            // when < 0, maximum frames to drop before starting capture even if sync event is
915            // not received
916            ssize_t                             mFramestoDrop;
917
918            // For dumpsys
919            const sp<NBAIO_Sink>                mTeeSink;
920};
921