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