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