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