Threads.h revision 463be250de73907965faa6a216c00312bf81e049
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        CFG_EVENT_SET_PARAMETER,
51        CFG_EVENT_CREATE_AUDIO_PATCH,
52        CFG_EVENT_RELEASE_AUDIO_PATCH,
53    };
54
55    class ConfigEventData: public RefBase {
56    public:
57        virtual ~ConfigEventData() {}
58
59        virtual  void dump(char *buffer, size_t size) = 0;
60    protected:
61        ConfigEventData() {}
62    };
63
64    // Config event sequence by client if status needed (e.g binder thread calling setParameters()):
65    //  1. create SetParameterConfigEvent. This sets mWaitStatus in config event
66    //  2. Lock mLock
67    //  3. Call sendConfigEvent_l(): Append to mConfigEvents and mWaitWorkCV.signal
68    //  4. sendConfigEvent_l() reads status from event->mStatus;
69    //  5. sendConfigEvent_l() returns status
70    //  6. Unlock
71    //
72    // Parameter sequence by server: threadLoop calling processConfigEvents_l():
73    // 1. Lock mLock
74    // 2. If there is an entry in mConfigEvents proceed ...
75    // 3. Read first entry in mConfigEvents
76    // 4. Remove first entry from mConfigEvents
77    // 5. Process
78    // 6. Set event->mStatus
79    // 7. event->mCond.signal
80    // 8. Unlock
81
82    class ConfigEvent: public RefBase {
83    public:
84        virtual ~ConfigEvent() {}
85
86        void dump(char *buffer, size_t size) { mData->dump(buffer, size); }
87
88        const int mType; // event type e.g. CFG_EVENT_IO
89        Mutex mLock;     // mutex associated with mCond
90        Condition mCond; // condition for status return
91        status_t mStatus; // status communicated to sender
92        bool mWaitStatus; // true if sender is waiting for status
93        sp<ConfigEventData> mData;     // event specific parameter data
94
95    protected:
96        ConfigEvent(int type) : mType(type), mStatus(NO_ERROR), mWaitStatus(false), mData(NULL) {}
97    };
98
99    class IoConfigEventData : public ConfigEventData {
100    public:
101        IoConfigEventData(int event, int param) :
102            mEvent(event), mParam(param) {}
103
104        virtual  void dump(char *buffer, size_t size) {
105            snprintf(buffer, size, "IO event: event %d, param %d\n", mEvent, mParam);
106        }
107
108        const int mEvent;
109        const int mParam;
110    };
111
112    class IoConfigEvent : public ConfigEvent {
113    public:
114        IoConfigEvent(int event, int param) :
115            ConfigEvent(CFG_EVENT_IO) {
116            mData = new IoConfigEventData(event, param);
117        }
118        virtual ~IoConfigEvent() {}
119    };
120
121    class PrioConfigEventData : public ConfigEventData {
122    public:
123        PrioConfigEventData(pid_t pid, pid_t tid, int32_t prio) :
124            mPid(pid), mTid(tid), mPrio(prio) {}
125
126        virtual  void dump(char *buffer, size_t size) {
127            snprintf(buffer, size, "Prio event: pid %d, tid %d, prio %d\n", mPid, mTid, mPrio);
128        }
129
130        const pid_t mPid;
131        const pid_t mTid;
132        const int32_t mPrio;
133    };
134
135    class PrioConfigEvent : public ConfigEvent {
136    public:
137        PrioConfigEvent(pid_t pid, pid_t tid, int32_t prio) :
138            ConfigEvent(CFG_EVENT_PRIO) {
139            mData = new PrioConfigEventData(pid, tid, prio);
140        }
141        virtual ~PrioConfigEvent() {}
142    };
143
144    class SetParameterConfigEventData : public ConfigEventData {
145    public:
146        SetParameterConfigEventData(String8 keyValuePairs) :
147            mKeyValuePairs(keyValuePairs) {}
148
149        virtual  void dump(char *buffer, size_t size) {
150            snprintf(buffer, size, "KeyValue: %s\n", mKeyValuePairs.string());
151        }
152
153        const String8 mKeyValuePairs;
154    };
155
156    class SetParameterConfigEvent : public ConfigEvent {
157    public:
158        SetParameterConfigEvent(String8 keyValuePairs) :
159            ConfigEvent(CFG_EVENT_SET_PARAMETER) {
160            mData = new SetParameterConfigEventData(keyValuePairs);
161            mWaitStatus = true;
162        }
163        virtual ~SetParameterConfigEvent() {}
164    };
165
166    class CreateAudioPatchConfigEventData : public ConfigEventData {
167    public:
168        CreateAudioPatchConfigEventData(const struct audio_patch patch,
169                                        audio_patch_handle_t handle) :
170            mPatch(patch), mHandle(handle) {}
171
172        virtual  void dump(char *buffer, size_t size) {
173            snprintf(buffer, size, "Patch handle: %u\n", mHandle);
174        }
175
176        const struct audio_patch mPatch;
177        audio_patch_handle_t mHandle;
178    };
179
180    class CreateAudioPatchConfigEvent : public ConfigEvent {
181    public:
182        CreateAudioPatchConfigEvent(const struct audio_patch patch,
183                                    audio_patch_handle_t handle) :
184            ConfigEvent(CFG_EVENT_CREATE_AUDIO_PATCH) {
185            mData = new CreateAudioPatchConfigEventData(patch, handle);
186            mWaitStatus = true;
187        }
188        virtual ~CreateAudioPatchConfigEvent() {}
189    };
190
191    class ReleaseAudioPatchConfigEventData : public ConfigEventData {
192    public:
193        ReleaseAudioPatchConfigEventData(const audio_patch_handle_t handle) :
194            mHandle(handle) {}
195
196        virtual  void dump(char *buffer, size_t size) {
197            snprintf(buffer, size, "Patch handle: %u\n", mHandle);
198        }
199
200        audio_patch_handle_t mHandle;
201    };
202
203    class ReleaseAudioPatchConfigEvent : public ConfigEvent {
204    public:
205        ReleaseAudioPatchConfigEvent(const audio_patch_handle_t handle) :
206            ConfigEvent(CFG_EVENT_RELEASE_AUDIO_PATCH) {
207            mData = new ReleaseAudioPatchConfigEventData(handle);
208            mWaitStatus = true;
209        }
210        virtual ~ReleaseAudioPatchConfigEvent() {}
211    };
212
213    class PMDeathRecipient : public IBinder::DeathRecipient {
214    public:
215                    PMDeathRecipient(const wp<ThreadBase>& thread) : mThread(thread) {}
216        virtual     ~PMDeathRecipient() {}
217
218        // IBinder::DeathRecipient
219        virtual     void        binderDied(const wp<IBinder>& who);
220
221    private:
222                    PMDeathRecipient(const PMDeathRecipient&);
223                    PMDeathRecipient& operator = (const PMDeathRecipient&);
224
225        wp<ThreadBase> mThread;
226    };
227
228    virtual     status_t    initCheck() const = 0;
229
230                // static externally-visible
231                type_t      type() const { return mType; }
232                audio_io_handle_t id() const { return mId;}
233
234                // dynamic externally-visible
235                uint32_t    sampleRate() const { return mSampleRate; }
236                audio_channel_mask_t channelMask() const { return mChannelMask; }
237                audio_format_t format() const { return mHALFormat; }
238                // Called by AudioFlinger::frameCount(audio_io_handle_t output) and effects,
239                // and returns the [normal mix] buffer's frame count.
240    virtual     size_t      frameCount() const = 0;
241                size_t      frameSize() const { return mFrameSize; }
242
243    // Should be "virtual status_t requestExitAndWait()" and override same
244    // method in Thread, but Thread::requestExitAndWait() is not yet virtual.
245                void        exit();
246    virtual     bool        checkForNewParameter_l(const String8& keyValuePair,
247                                                    status_t& status) = 0;
248    virtual     status_t    setParameters(const String8& keyValuePairs);
249    virtual     String8     getParameters(const String8& keys) = 0;
250    virtual     void        audioConfigChanged(int event, int param = 0) = 0;
251                // sendConfigEvent_l() must be called with ThreadBase::mLock held
252                // Can temporarily release the lock if waiting for a reply from
253                // processConfigEvents_l().
254                status_t    sendConfigEvent_l(sp<ConfigEvent>& event);
255                void        sendIoConfigEvent(int event, int param = 0);
256                void        sendIoConfigEvent_l(int event, int param = 0);
257                void        sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio);
258                status_t    sendSetParameterConfigEvent_l(const String8& keyValuePair);
259                status_t    sendCreateAudioPatchConfigEvent(const struct audio_patch *patch,
260                                                            audio_patch_handle_t *handle);
261                status_t    sendReleaseAudioPatchConfigEvent(audio_patch_handle_t handle);
262                void        processConfigEvents_l();
263    virtual     void        cacheParameters_l() = 0;
264    virtual     status_t    createAudioPatch_l(const struct audio_patch *patch,
265                                               audio_patch_handle_t *handle) = 0;
266    virtual     status_t    releaseAudioPatch_l(const audio_patch_handle_t handle) = 0;
267
268
269                // see note at declaration of mStandby, mOutDevice and mInDevice
270                bool        standby() const { return mStandby; }
271                audio_devices_t outDevice() const { return mOutDevice; }
272                audio_devices_t inDevice() const { return mInDevice; }
273
274    virtual     audio_stream_t* stream() const = 0;
275
276                sp<EffectHandle> createEffect_l(
277                                    const sp<AudioFlinger::Client>& client,
278                                    const sp<IEffectClient>& effectClient,
279                                    int32_t priority,
280                                    int sessionId,
281                                    effect_descriptor_t *desc,
282                                    int *enabled,
283                                    status_t *status /*non-NULL*/);
284                void disconnectEffect(const sp< EffectModule>& effect,
285                                      EffectHandle *handle,
286                                      bool unpinIfLast);
287
288                // return values for hasAudioSession (bit field)
289                enum effect_state {
290                    EFFECT_SESSION = 0x1,   // the audio session corresponds to at least one
291                                            // effect
292                    TRACK_SESSION = 0x2     // the audio session corresponds to at least one
293                                            // track
294                };
295
296                // get effect chain corresponding to session Id.
297                sp<EffectChain> getEffectChain(int sessionId);
298                // same as getEffectChain() but must be called with ThreadBase mutex locked
299                sp<EffectChain> getEffectChain_l(int sessionId) const;
300                // add an effect chain to the chain list (mEffectChains)
301    virtual     status_t addEffectChain_l(const sp<EffectChain>& chain) = 0;
302                // remove an effect chain from the chain list (mEffectChains)
303    virtual     size_t removeEffectChain_l(const sp<EffectChain>& chain) = 0;
304                // lock all effect chains Mutexes. Must be called before releasing the
305                // ThreadBase mutex before processing the mixer and effects. This guarantees the
306                // integrity of the chains during the process.
307                // Also sets the parameter 'effectChains' to current value of mEffectChains.
308                void lockEffectChains_l(Vector< sp<EffectChain> >& effectChains);
309                // unlock effect chains after process
310                void unlockEffectChains(const Vector< sp<EffectChain> >& effectChains);
311                // get a copy of mEffectChains vector
312                Vector< sp<EffectChain> > getEffectChains_l() const { return mEffectChains; };
313                // set audio mode to all effect chains
314                void setMode(audio_mode_t mode);
315                // get effect module with corresponding ID on specified audio session
316                sp<AudioFlinger::EffectModule> getEffect(int sessionId, int effectId);
317                sp<AudioFlinger::EffectModule> getEffect_l(int sessionId, int effectId);
318                // add and effect module. Also creates the effect chain is none exists for
319                // the effects audio session
320                status_t addEffect_l(const sp< EffectModule>& effect);
321                // remove and effect module. Also removes the effect chain is this was the last
322                // effect
323                void removeEffect_l(const sp< EffectModule>& effect);
324                // detach all tracks connected to an auxiliary effect
325    virtual     void detachAuxEffect_l(int effectId __unused) {}
326                // returns either EFFECT_SESSION if effects on this audio session exist in one
327                // chain, or TRACK_SESSION if tracks on this audio session exist, or both
328                virtual uint32_t hasAudioSession(int sessionId) const = 0;
329                // the value returned by default implementation is not important as the
330                // strategy is only meaningful for PlaybackThread which implements this method
331                virtual uint32_t getStrategyForSession_l(int sessionId __unused) { return 0; }
332
333                // suspend or restore effect according to the type of effect passed. a NULL
334                // type pointer means suspend all effects in the session
335                void setEffectSuspended(const effect_uuid_t *type,
336                                        bool suspend,
337                                        int sessionId = AUDIO_SESSION_OUTPUT_MIX);
338                // check if some effects must be suspended/restored when an effect is enabled
339                // or disabled
340                void checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
341                                                 bool enabled,
342                                                 int sessionId = AUDIO_SESSION_OUTPUT_MIX);
343                void checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
344                                                   bool enabled,
345                                                   int sessionId = AUDIO_SESSION_OUTPUT_MIX);
346
347                virtual status_t    setSyncEvent(const sp<SyncEvent>& event) = 0;
348                virtual bool        isValidSyncEvent(const sp<SyncEvent>& event) const = 0;
349
350                // Return a reference to a per-thread heap which can be used to allocate IMemory
351                // objects that will be read-only to client processes, read/write to mediaserver,
352                // and shared by all client processes of the thread.
353                // The heap is per-thread rather than common across all threads, because
354                // clients can't be trusted not to modify the offset of the IMemory they receive.
355                // If a thread does not have such a heap, this method returns 0.
356                virtual sp<MemoryDealer>    readOnlyHeap() const { return 0; }
357
358                virtual sp<IMemory> pipeMemory() const { return 0; }
359
360    mutable     Mutex                   mLock;
361
362protected:
363
364                // entry describing an effect being suspended in mSuspendedSessions keyed vector
365                class SuspendedSessionDesc : public RefBase {
366                public:
367                    SuspendedSessionDesc() : mRefCount(0) {}
368
369                    int mRefCount;          // number of active suspend requests
370                    effect_uuid_t mType;    // effect type UUID
371                };
372
373                void        acquireWakeLock(int uid = -1);
374                void        acquireWakeLock_l(int uid = -1);
375                void        releaseWakeLock();
376                void        releaseWakeLock_l();
377                void        updateWakeLockUids(const SortedVector<int> &uids);
378                void        updateWakeLockUids_l(const SortedVector<int> &uids);
379                void        getPowerManager_l();
380                void setEffectSuspended_l(const effect_uuid_t *type,
381                                          bool suspend,
382                                          int sessionId);
383                // updated mSuspendedSessions when an effect suspended or restored
384                void        updateSuspendedSessions_l(const effect_uuid_t *type,
385                                                      bool suspend,
386                                                      int sessionId);
387                // check if some effects must be suspended when an effect chain is added
388                void checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain);
389
390                String16 getWakeLockTag();
391
392    virtual     void        preExit() { }
393
394    friend class AudioFlinger;      // for mEffectChains
395
396                const type_t            mType;
397
398                // Used by parameters, config events, addTrack_l, exit
399                Condition               mWaitWorkCV;
400
401                const sp<AudioFlinger>  mAudioFlinger;
402
403                // updated by PlaybackThread::readOutputParameters_l() or
404                // RecordThread::readInputParameters_l()
405                uint32_t                mSampleRate;
406                size_t                  mFrameCount;       // output HAL, direct output, record
407                audio_channel_mask_t    mChannelMask;
408                uint32_t                mChannelCount;
409                size_t                  mFrameSize;
410                audio_format_t          mFormat;           // Source format for Recording and
411                                                           // Sink format for Playback.
412                                                           // Sink format may be different than
413                                                           // HAL format if Fastmixer is used.
414                audio_format_t          mHALFormat;
415                size_t                  mBufferSize;       // HAL buffer size for read() or write()
416
417                Vector< sp<ConfigEvent> >     mConfigEvents;
418
419                // These fields are written and read by thread itself without lock or barrier,
420                // and read by other threads without lock or barrier via standby(), outDevice()
421                // and inDevice().
422                // Because of the absence of a lock or barrier, any other thread that reads
423                // these fields must use the information in isolation, or be prepared to deal
424                // with possibility that it might be inconsistent with other information.
425                bool                    mStandby;     // Whether thread is currently in standby.
426                audio_devices_t         mOutDevice;   // output device
427                audio_devices_t         mInDevice;    // input device
428                audio_source_t          mAudioSource; // (see audio.h, audio_source_t)
429
430                const audio_io_handle_t mId;
431                Vector< sp<EffectChain> > mEffectChains;
432
433                static const int        kNameLength = 16;   // prctl(PR_SET_NAME) limit
434                char                    mName[kNameLength];
435                sp<IPowerManager>       mPowerManager;
436                sp<IBinder>             mWakeLockToken;
437                const sp<PMDeathRecipient> mDeathRecipient;
438                // list of suspended effects per session and per type. The first vector is
439                // keyed by session ID, the second by type UUID timeLow field
440                KeyedVector< int, KeyedVector< int, sp<SuspendedSessionDesc> > >
441                                        mSuspendedSessions;
442                static const size_t     kLogSize = 4 * 1024;
443                sp<NBLog::Writer>       mNBLogWriter;
444};
445
446// --- PlaybackThread ---
447class PlaybackThread : public ThreadBase {
448public:
449
450#include "PlaybackTracks.h"
451
452    enum mixer_state {
453        MIXER_IDLE,             // no active tracks
454        MIXER_TRACKS_ENABLED,   // at least one active track, but no track has any data ready
455        MIXER_TRACKS_READY,      // at least one active track, and at least one track has data
456        MIXER_DRAIN_TRACK,      // drain currently playing track
457        MIXER_DRAIN_ALL,        // fully drain the hardware
458        // standby mode does not have an enum value
459        // suspend by audio policy manager is orthogonal to mixer state
460    };
461
462    // retry count before removing active track in case of underrun on offloaded thread:
463    // we need to make sure that AudioTrack client has enough time to send large buffers
464//FIXME may be more appropriate if expressed in time units. Need to revise how underrun is handled
465    // for offloaded tracks
466    static const int8_t kMaxTrackRetriesOffload = 20;
467
468    PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
469                   audio_io_handle_t id, audio_devices_t device, type_t type);
470    virtual             ~PlaybackThread();
471
472                void        dump(int fd, const Vector<String16>& args);
473
474    // Thread virtuals
475    virtual     bool        threadLoop();
476
477    // RefBase
478    virtual     void        onFirstRef();
479
480protected:
481    // Code snippets that were lifted up out of threadLoop()
482    virtual     void        threadLoop_mix() = 0;
483    virtual     void        threadLoop_sleepTime() = 0;
484    virtual     ssize_t     threadLoop_write();
485    virtual     void        threadLoop_drain();
486    virtual     void        threadLoop_standby();
487    virtual     void        threadLoop_exit();
488    virtual     void        threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
489
490                // prepareTracks_l reads and writes mActiveTracks, and returns
491                // the pending set of tracks to remove via Vector 'tracksToRemove'.  The caller
492                // is responsible for clearing or destroying this Vector later on, when it
493                // is safe to do so. That will drop the final ref count and destroy the tracks.
494    virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove) = 0;
495                void        removeTracks_l(const Vector< sp<Track> >& tracksToRemove);
496
497                void        writeCallback();
498                void        resetWriteBlocked(uint32_t sequence);
499                void        drainCallback();
500                void        resetDraining(uint32_t sequence);
501
502    static      int         asyncCallback(stream_callback_event_t event, void *param, void *cookie);
503
504    virtual     bool        waitingAsyncCallback();
505    virtual     bool        waitingAsyncCallback_l();
506    virtual     bool        shouldStandby_l();
507    virtual     void        onAddNewTrack_l();
508
509    // ThreadBase virtuals
510    virtual     void        preExit();
511
512public:
513
514    virtual     status_t    initCheck() const { return (mOutput == NULL) ? NO_INIT : NO_ERROR; }
515
516                // return estimated latency in milliseconds, as reported by HAL
517                uint32_t    latency() const;
518                // same, but lock must already be held
519                uint32_t    latency_l() const;
520
521                void        setMasterVolume(float value);
522                void        setMasterMute(bool muted);
523
524                void        setStreamVolume(audio_stream_type_t stream, float value);
525                void        setStreamMute(audio_stream_type_t stream, bool muted);
526
527                float       streamVolume(audio_stream_type_t stream) const;
528
529                sp<Track>   createTrack_l(
530                                const sp<AudioFlinger::Client>& client,
531                                audio_stream_type_t streamType,
532                                uint32_t sampleRate,
533                                audio_format_t format,
534                                audio_channel_mask_t channelMask,
535                                size_t *pFrameCount,
536                                const sp<IMemory>& sharedBuffer,
537                                int sessionId,
538                                IAudioFlinger::track_flags_t *flags,
539                                pid_t tid,
540                                int uid,
541                                status_t *status /*non-NULL*/);
542
543                AudioStreamOut* getOutput() const;
544                AudioStreamOut* clearOutput();
545                virtual audio_stream_t* stream() const;
546
547                // a very large number of suspend() will eventually wraparound, but unlikely
548                void        suspend() { (void) android_atomic_inc(&mSuspended); }
549                void        restore()
550                                {
551                                    // if restore() is done without suspend(), get back into
552                                    // range so that the next suspend() will operate correctly
553                                    if (android_atomic_dec(&mSuspended) <= 0) {
554                                        android_atomic_release_store(0, &mSuspended);
555                                    }
556                                }
557                bool        isSuspended() const
558                                { return android_atomic_acquire_load(&mSuspended) > 0; }
559
560    virtual     String8     getParameters(const String8& keys);
561    virtual     void        audioConfigChanged(int event, int param = 0);
562                status_t    getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames);
563                // FIXME rename mixBuffer() to sinkBuffer() and remove int16_t* dependency.
564                // Consider also removing and passing an explicit mMainBuffer initialization
565                // parameter to AF::PlaybackThread::Track::Track().
566                int16_t     *mixBuffer() const {
567                    return reinterpret_cast<int16_t *>(mSinkBuffer); };
568
569    virtual     void detachAuxEffect_l(int effectId);
570                status_t attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track> track,
571                        int EffectId);
572                status_t attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track> track,
573                        int EffectId);
574
575                virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
576                virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
577                virtual uint32_t hasAudioSession(int sessionId) const;
578                virtual uint32_t getStrategyForSession_l(int sessionId);
579
580
581                virtual status_t setSyncEvent(const sp<SyncEvent>& event);
582                virtual bool     isValidSyncEvent(const sp<SyncEvent>& event) const;
583
584                // called with AudioFlinger lock held
585                        void     invalidateTracks(audio_stream_type_t streamType);
586
587    virtual     size_t      frameCount() const { return mNormalFrameCount; }
588
589                // Return's the HAL's frame count i.e. fast mixer buffer size.
590                size_t      frameCountHAL() const { return mFrameCount; }
591
592                status_t         getTimestamp_l(AudioTimestamp& timestamp);
593
594protected:
595    // updated by readOutputParameters_l()
596    size_t                          mNormalFrameCount;  // normal mixer and effects
597
598    void*                           mSinkBuffer;         // frame size aligned sink buffer
599
600    // TODO:
601    // Rearrange the buffer info into a struct/class with
602    // clear, copy, construction, destruction methods.
603    //
604    // mSinkBuffer also has associated with it:
605    //
606    // mSinkBufferSize: Sink Buffer Size
607    // mFormat: Sink Buffer Format
608
609    // Mixer Buffer (mMixerBuffer*)
610    //
611    // In the case of floating point or multichannel data, which is not in the
612    // sink format, it is required to accumulate in a higher precision or greater channel count
613    // buffer before downmixing or data conversion to the sink buffer.
614
615    // Set to "true" to enable the Mixer Buffer otherwise mixer output goes to sink buffer.
616    bool                            mMixerBufferEnabled;
617
618    // Storage, 32 byte aligned (may make this alignment a requirement later).
619    // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
620    void*                           mMixerBuffer;
621
622    // Size of mMixerBuffer in bytes: mNormalFrameCount * #channels * sampsize.
623    size_t                          mMixerBufferSize;
624
625    // The audio format of mMixerBuffer. Set to AUDIO_FORMAT_PCM_(FLOAT|16_BIT) only.
626    audio_format_t                  mMixerBufferFormat;
627
628    // An internal flag set to true by MixerThread::prepareTracks_l()
629    // when mMixerBuffer contains valid data after mixing.
630    bool                            mMixerBufferValid;
631
632    // Effects Buffer (mEffectsBuffer*)
633    //
634    // In the case of effects data, which is not in the sink format,
635    // it is required to accumulate in a different buffer before data conversion
636    // to the sink buffer.
637
638    // Set to "true" to enable the Effects Buffer otherwise effects output goes to sink buffer.
639    bool                            mEffectBufferEnabled;
640
641    // Storage, 32 byte aligned (may make this alignment a requirement later).
642    // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
643    void*                           mEffectBuffer;
644
645    // Size of mEffectsBuffer in bytes: mNormalFrameCount * #channels * sampsize.
646    size_t                          mEffectBufferSize;
647
648    // The audio format of mEffectsBuffer. Set to AUDIO_FORMAT_PCM_16_BIT only.
649    audio_format_t                  mEffectBufferFormat;
650
651    // An internal flag set to true by MixerThread::prepareTracks_l()
652    // when mEffectsBuffer contains valid data after mixing.
653    //
654    // When this is set, all mixer data is routed into the effects buffer
655    // for any processing (including output processing).
656    bool                            mEffectBufferValid;
657
658    // suspend count, > 0 means suspended.  While suspended, the thread continues to pull from
659    // tracks and mix, but doesn't write to HAL.  A2DP and SCO HAL implementations can't handle
660    // concurrent use of both of them, so Audio Policy Service suspends one of the threads to
661    // workaround that restriction.
662    // 'volatile' means accessed via atomic operations and no lock.
663    volatile int32_t                mSuspended;
664
665    // FIXME overflows every 6+ hours at 44.1 kHz stereo 16-bit samples
666    // mFramesWritten would be better, or 64-bit even better
667    size_t                          mBytesWritten;
668private:
669    // mMasterMute is in both PlaybackThread and in AudioFlinger.  When a
670    // PlaybackThread needs to find out if master-muted, it checks it's local
671    // copy rather than the one in AudioFlinger.  This optimization saves a lock.
672    bool                            mMasterMute;
673                void        setMasterMute_l(bool muted) { mMasterMute = muted; }
674protected:
675    SortedVector< wp<Track> >       mActiveTracks;  // FIXME check if this could be sp<>
676    SortedVector<int>               mWakeLockUids;
677    int                             mActiveTracksGeneration;
678    wp<Track>                       mLatestActiveTrack; // latest track added to mActiveTracks
679
680    // Allocate a track name for a given channel mask.
681    //   Returns name >= 0 if successful, -1 on failure.
682    virtual int             getTrackName_l(audio_channel_mask_t channelMask,
683                                           audio_format_t format, int sessionId) = 0;
684    virtual void            deleteTrackName_l(int name) = 0;
685
686    // Time to sleep between cycles when:
687    virtual uint32_t        activeSleepTimeUs() const;      // mixer state MIXER_TRACKS_ENABLED
688    virtual uint32_t        idleSleepTimeUs() const = 0;    // mixer state MIXER_IDLE
689    virtual uint32_t        suspendSleepTimeUs() const = 0; // audio policy manager suspended us
690    // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write()
691    // No sleep in standby mode; waits on a condition
692
693    // Code snippets that are temporarily lifted up out of threadLoop() until the merge
694                void        checkSilentMode_l();
695
696    // Non-trivial for DUPLICATING only
697    virtual     void        saveOutputTracks() { }
698    virtual     void        clearOutputTracks() { }
699
700    // Cache various calculated values, at threadLoop() entry and after a parameter change
701    virtual     void        cacheParameters_l();
702
703    virtual     uint32_t    correctLatency_l(uint32_t latency) const;
704
705    virtual     status_t    createAudioPatch_l(const struct audio_patch *patch,
706                                   audio_patch_handle_t *handle);
707    virtual     status_t    releaseAudioPatch_l(const audio_patch_handle_t handle);
708
709private:
710
711    friend class AudioFlinger;      // for numerous
712
713    PlaybackThread& operator = (const PlaybackThread&);
714
715    status_t    addTrack_l(const sp<Track>& track);
716    bool        destroyTrack_l(const sp<Track>& track);
717    void        removeTrack_l(const sp<Track>& track);
718    void        broadcast_l();
719
720    void        readOutputParameters_l();
721
722    virtual void dumpInternals(int fd, const Vector<String16>& args);
723    void        dumpTracks(int fd, const Vector<String16>& args);
724
725    SortedVector< sp<Track> >       mTracks;
726    // mStreamTypes[] uses 1 additional stream type internally for the OutputTrack used by
727    // DuplicatingThread
728    stream_type_t                   mStreamTypes[AUDIO_STREAM_CNT + 1];
729    AudioStreamOut                  *mOutput;
730
731    float                           mMasterVolume;
732    nsecs_t                         mLastWriteTime;
733    int                             mNumWrites;
734    int                             mNumDelayedWrites;
735    bool                            mInWrite;
736
737    // FIXME rename these former local variables of threadLoop to standard "m" names
738    nsecs_t                         standbyTime;
739    size_t                          mSinkBufferSize;
740
741    // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l()
742    uint32_t                        activeSleepTime;
743    uint32_t                        idleSleepTime;
744
745    uint32_t                        sleepTime;
746
747    // mixer status returned by prepareTracks_l()
748    mixer_state                     mMixerStatus; // current cycle
749                                                  // previous cycle when in prepareTracks_l()
750    mixer_state                     mMixerStatusIgnoringFastTracks;
751                                                  // FIXME or a separate ready state per track
752
753    // FIXME move these declarations into the specific sub-class that needs them
754    // MIXER only
755    uint32_t                        sleepTimeShift;
756
757    // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value
758    nsecs_t                         standbyDelay;
759
760    // MIXER only
761    nsecs_t                         maxPeriod;
762
763    // DUPLICATING only
764    uint32_t                        writeFrames;
765
766    size_t                          mBytesRemaining;
767    size_t                          mCurrentWriteLength;
768    bool                            mUseAsyncWrite;
769    // mWriteAckSequence contains current write sequence on bits 31-1. The write sequence is
770    // incremented each time a write(), a flush() or a standby() occurs.
771    // Bit 0 is set when a write blocks and indicates a callback is expected.
772    // Bit 0 is reset by the async callback thread calling resetWriteBlocked(). Out of sequence
773    // callbacks are ignored.
774    uint32_t                        mWriteAckSequence;
775    // mDrainSequence contains current drain sequence on bits 31-1. The drain sequence is
776    // incremented each time a drain is requested or a flush() or standby() occurs.
777    // Bit 0 is set when the drain() command is called at the HAL and indicates a callback is
778    // expected.
779    // Bit 0 is reset by the async callback thread calling resetDraining(). Out of sequence
780    // callbacks are ignored.
781    uint32_t                        mDrainSequence;
782    // A condition that must be evaluated by prepareTrack_l() has changed and we must not wait
783    // for async write callback in the thread loop before evaluating it
784    bool                            mSignalPending;
785    sp<AsyncCallbackThread>         mCallbackThread;
786
787private:
788    // The HAL output sink is treated as non-blocking, but current implementation is blocking
789    sp<NBAIO_Sink>          mOutputSink;
790    // If a fast mixer is present, the blocking pipe sink, otherwise clear
791    sp<NBAIO_Sink>          mPipeSink;
792    // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink
793    sp<NBAIO_Sink>          mNormalSink;
794#ifdef TEE_SINK
795    // For dumpsys
796    sp<NBAIO_Sink>          mTeeSink;
797    sp<NBAIO_Source>        mTeeSource;
798#endif
799    uint32_t                mScreenState;   // cached copy of gScreenState
800    static const size_t     kFastMixerLogSize = 4 * 1024;
801    sp<NBLog::Writer>       mFastMixerNBLogWriter;
802public:
803    virtual     bool        hasFastMixer() const = 0;
804    virtual     FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex __unused) const
805                                { FastTrackUnderruns dummy; return dummy; }
806
807protected:
808                // accessed by both binder threads and within threadLoop(), lock on mutex needed
809                unsigned    mFastTrackAvailMask;    // bit i set if fast track [i] is available
810
811private:
812    // timestamp latch:
813    //  D input is written by threadLoop_write while mutex is unlocked, and read while locked
814    //  Q output is written while locked, and read while locked
815    struct {
816        AudioTimestamp  mTimestamp;
817        uint32_t        mUnpresentedFrames;
818    } mLatchD, mLatchQ;
819    bool mLatchDValid;  // true means mLatchD is valid, and clock it into latch at next opportunity
820    bool mLatchQValid;  // true means mLatchQ is valid
821};
822
823class MixerThread : public PlaybackThread {
824public:
825    MixerThread(const sp<AudioFlinger>& audioFlinger,
826                AudioStreamOut* output,
827                audio_io_handle_t id,
828                audio_devices_t device,
829                type_t type = MIXER);
830    virtual             ~MixerThread();
831
832    // Thread virtuals
833
834    virtual     bool        checkForNewParameter_l(const String8& keyValuePair,
835                                                   status_t& status);
836    virtual     void        dumpInternals(int fd, const Vector<String16>& args);
837
838protected:
839    virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
840    virtual     int         getTrackName_l(audio_channel_mask_t channelMask,
841                                           audio_format_t format, int sessionId);
842    virtual     void        deleteTrackName_l(int name);
843    virtual     uint32_t    idleSleepTimeUs() const;
844    virtual     uint32_t    suspendSleepTimeUs() const;
845    virtual     void        cacheParameters_l();
846
847    // threadLoop snippets
848    virtual     ssize_t     threadLoop_write();
849    virtual     void        threadLoop_standby();
850    virtual     void        threadLoop_mix();
851    virtual     void        threadLoop_sleepTime();
852    virtual     void        threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
853    virtual     uint32_t    correctLatency_l(uint32_t latency) const;
854
855                AudioMixer* mAudioMixer;    // normal mixer
856private:
857                // one-time initialization, no locks required
858                sp<FastMixer>     mFastMixer;     // non-0 if there is also a fast mixer
859                sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread
860
861                // contents are not guaranteed to be consistent, no locks required
862                FastMixerDumpState mFastMixerDumpState;
863#ifdef STATE_QUEUE_DUMP
864                StateQueueObserverDump mStateQueueObserverDump;
865                StateQueueMutatorDump  mStateQueueMutatorDump;
866#endif
867                AudioWatchdogDump mAudioWatchdogDump;
868
869                // accessible only within the threadLoop(), no locks required
870                //          mFastMixer->sq()    // for mutating and pushing state
871                int32_t     mFastMixerFutex;    // for cold idle
872
873public:
874    virtual     bool        hasFastMixer() const { return mFastMixer != 0; }
875    virtual     FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const {
876                              ALOG_ASSERT(fastIndex < FastMixerState::kMaxFastTracks);
877                              return mFastMixerDumpState.mTracks[fastIndex].mUnderruns;
878                            }
879};
880
881class DirectOutputThread : public PlaybackThread {
882public:
883
884    DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
885                       audio_io_handle_t id, audio_devices_t device);
886    virtual                 ~DirectOutputThread();
887
888    // Thread virtuals
889
890    virtual     bool        checkForNewParameter_l(const String8& keyValuePair,
891                                                   status_t& status);
892
893protected:
894    virtual     int         getTrackName_l(audio_channel_mask_t channelMask,
895                                           audio_format_t format, int sessionId);
896    virtual     void        deleteTrackName_l(int name);
897    virtual     uint32_t    activeSleepTimeUs() const;
898    virtual     uint32_t    idleSleepTimeUs() const;
899    virtual     uint32_t    suspendSleepTimeUs() const;
900    virtual     void        cacheParameters_l();
901
902    // threadLoop snippets
903    virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
904    virtual     void        threadLoop_mix();
905    virtual     void        threadLoop_sleepTime();
906
907    // volumes last sent to audio HAL with stream->set_volume()
908    float mLeftVolFloat;
909    float mRightVolFloat;
910
911    DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
912                        audio_io_handle_t id, uint32_t device, ThreadBase::type_t type);
913    void processVolume_l(Track *track, bool lastTrack);
914
915    // prepareTracks_l() tells threadLoop_mix() the name of the single active track
916    sp<Track>               mActiveTrack;
917public:
918    virtual     bool        hasFastMixer() const { return false; }
919};
920
921class OffloadThread : public DirectOutputThread {
922public:
923
924    OffloadThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
925                        audio_io_handle_t id, uint32_t device);
926    virtual                 ~OffloadThread() {};
927
928protected:
929    // threadLoop snippets
930    virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
931    virtual     void        threadLoop_exit();
932
933    virtual     bool        waitingAsyncCallback();
934    virtual     bool        waitingAsyncCallback_l();
935    virtual     bool        shouldStandby_l();
936    virtual     void        onAddNewTrack_l();
937
938private:
939                void        flushHw_l();
940
941private:
942    bool        mHwPaused;
943    bool        mFlushPending;
944    size_t      mPausedWriteLength;     // length in bytes of write interrupted by pause
945    size_t      mPausedBytesRemaining;  // bytes still waiting in mixbuffer after resume
946    wp<Track>   mPreviousTrack;         // used to detect track switch
947};
948
949class AsyncCallbackThread : public Thread {
950public:
951
952    AsyncCallbackThread(const wp<PlaybackThread>& playbackThread);
953
954    virtual             ~AsyncCallbackThread();
955
956    // Thread virtuals
957    virtual bool        threadLoop();
958
959    // RefBase
960    virtual void        onFirstRef();
961
962            void        exit();
963            void        setWriteBlocked(uint32_t sequence);
964            void        resetWriteBlocked();
965            void        setDraining(uint32_t sequence);
966            void        resetDraining();
967
968private:
969    const wp<PlaybackThread>   mPlaybackThread;
970    // mWriteAckSequence corresponds to the last write sequence passed by the offload thread via
971    // setWriteBlocked(). The sequence is shifted one bit to the left and the lsb is used
972    // to indicate that the callback has been received via resetWriteBlocked()
973    uint32_t                   mWriteAckSequence;
974    // mDrainSequence corresponds to the last drain sequence passed by the offload thread via
975    // setDraining(). The sequence is shifted one bit to the left and the lsb is used
976    // to indicate that the callback has been received via resetDraining()
977    uint32_t                   mDrainSequence;
978    Condition                  mWaitWorkCV;
979    Mutex                      mLock;
980};
981
982class DuplicatingThread : public MixerThread {
983public:
984    DuplicatingThread(const sp<AudioFlinger>& audioFlinger, MixerThread* mainThread,
985                      audio_io_handle_t id);
986    virtual                 ~DuplicatingThread();
987
988    // Thread virtuals
989                void        addOutputTrack(MixerThread* thread);
990                void        removeOutputTrack(MixerThread* thread);
991                uint32_t    waitTimeMs() const { return mWaitTimeMs; }
992protected:
993    virtual     uint32_t    activeSleepTimeUs() const;
994
995private:
996                bool        outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks);
997protected:
998    // threadLoop snippets
999    virtual     void        threadLoop_mix();
1000    virtual     void        threadLoop_sleepTime();
1001    virtual     ssize_t     threadLoop_write();
1002    virtual     void        threadLoop_standby();
1003    virtual     void        cacheParameters_l();
1004
1005private:
1006    // called from threadLoop, addOutputTrack, removeOutputTrack
1007    virtual     void        updateWaitTime_l();
1008protected:
1009    virtual     void        saveOutputTracks();
1010    virtual     void        clearOutputTracks();
1011private:
1012
1013                uint32_t    mWaitTimeMs;
1014    SortedVector < sp<OutputTrack> >  outputTracks;
1015    SortedVector < sp<OutputTrack> >  mOutputTracks;
1016public:
1017    virtual     bool        hasFastMixer() const { return false; }
1018};
1019
1020
1021// record thread
1022class RecordThread : public ThreadBase
1023{
1024public:
1025
1026    class RecordTrack;
1027    class ResamplerBufferProvider : public AudioBufferProvider
1028                        // derives from AudioBufferProvider interface for use by resampler
1029    {
1030    public:
1031        ResamplerBufferProvider(RecordTrack* recordTrack) : mRecordTrack(recordTrack) { }
1032        virtual ~ResamplerBufferProvider() { }
1033        // AudioBufferProvider interface
1034        virtual status_t    getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts);
1035        virtual void        releaseBuffer(AudioBufferProvider::Buffer* buffer);
1036    private:
1037        RecordTrack * const mRecordTrack;
1038    };
1039
1040#include "RecordTracks.h"
1041
1042            RecordThread(const sp<AudioFlinger>& audioFlinger,
1043                    AudioStreamIn *input,
1044                    audio_io_handle_t id,
1045                    audio_devices_t outDevice,
1046                    audio_devices_t inDevice
1047#ifdef TEE_SINK
1048                    , const sp<NBAIO_Sink>& teeSink
1049#endif
1050                    );
1051            virtual     ~RecordThread();
1052
1053    // no addTrack_l ?
1054    void        destroyTrack_l(const sp<RecordTrack>& track);
1055    void        removeTrack_l(const sp<RecordTrack>& track);
1056
1057    void        dumpInternals(int fd, const Vector<String16>& args);
1058    void        dumpTracks(int fd, const Vector<String16>& args);
1059
1060    // Thread virtuals
1061    virtual bool        threadLoop();
1062
1063    // RefBase
1064    virtual void        onFirstRef();
1065
1066    virtual status_t    initCheck() const { return (mInput == NULL) ? NO_INIT : NO_ERROR; }
1067
1068    virtual sp<MemoryDealer>    readOnlyHeap() const { return mReadOnlyHeap; }
1069
1070    virtual sp<IMemory> pipeMemory() const { return mPipeMemory; }
1071
1072            sp<AudioFlinger::RecordThread::RecordTrack>  createRecordTrack_l(
1073                    const sp<AudioFlinger::Client>& client,
1074                    uint32_t sampleRate,
1075                    audio_format_t format,
1076                    audio_channel_mask_t channelMask,
1077                    size_t *pFrameCount,
1078                    int sessionId,
1079                    size_t *notificationFrames,
1080                    int uid,
1081                    IAudioFlinger::track_flags_t *flags,
1082                    pid_t tid,
1083                    status_t *status /*non-NULL*/);
1084
1085            status_t    start(RecordTrack* recordTrack,
1086                              AudioSystem::sync_event_t event,
1087                              int triggerSession);
1088
1089            // ask the thread to stop the specified track, and
1090            // return true if the caller should then do it's part of the stopping process
1091            bool        stop(RecordTrack* recordTrack);
1092
1093            void        dump(int fd, const Vector<String16>& args);
1094            AudioStreamIn* clearInput();
1095            virtual audio_stream_t* stream() const;
1096
1097
1098    virtual bool        checkForNewParameter_l(const String8& keyValuePair,
1099                                               status_t& status);
1100    virtual void        cacheParameters_l() {}
1101    virtual String8     getParameters(const String8& keys);
1102    virtual void        audioConfigChanged(int event, int param = 0);
1103    virtual status_t    createAudioPatch_l(const struct audio_patch *patch,
1104                                           audio_patch_handle_t *handle);
1105    virtual status_t    releaseAudioPatch_l(const audio_patch_handle_t handle);
1106            void        readInputParameters_l();
1107    virtual uint32_t    getInputFramesLost();
1108
1109    virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
1110    virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
1111    virtual uint32_t hasAudioSession(int sessionId) const;
1112
1113            // Return the set of unique session IDs across all tracks.
1114            // The keys are the session IDs, and the associated values are meaningless.
1115            // FIXME replace by Set [and implement Bag/Multiset for other uses].
1116            KeyedVector<int, bool> sessionIds() const;
1117
1118    virtual status_t setSyncEvent(const sp<SyncEvent>& event);
1119    virtual bool     isValidSyncEvent(const sp<SyncEvent>& event) const;
1120
1121    static void syncStartEventCallback(const wp<SyncEvent>& event);
1122
1123    virtual size_t      frameCount() const { return mFrameCount; }
1124            bool        hasFastCapture() const { return mFastCapture != 0; }
1125
1126private:
1127            // Enter standby if not already in standby, and set mStandby flag
1128            void    standbyIfNotAlreadyInStandby();
1129
1130            // Call the HAL standby method unconditionally, and don't change mStandby flag
1131            void    inputStandBy();
1132
1133            AudioStreamIn                       *mInput;
1134            SortedVector < sp<RecordTrack> >    mTracks;
1135            // mActiveTracks has dual roles:  it indicates the current active track(s), and
1136            // is used together with mStartStopCond to indicate start()/stop() progress
1137            SortedVector< sp<RecordTrack> >     mActiveTracks;
1138            // generation counter for mActiveTracks
1139            int                                 mActiveTracksGen;
1140            Condition                           mStartStopCond;
1141
1142            // resampler converts input at HAL Hz to output at AudioRecord client Hz
1143            int16_t                             *mRsmpInBuffer; // see new[] for details on the size
1144            size_t                              mRsmpInFrames;  // size of resampler input in frames
1145            size_t                              mRsmpInFramesP2;// size rounded up to a power-of-2
1146
1147            // rolling index that is never cleared
1148            int32_t                             mRsmpInRear;    // last filled frame + 1
1149
1150            // For dumpsys
1151            const sp<NBAIO_Sink>                mTeeSink;
1152
1153            const sp<MemoryDealer>              mReadOnlyHeap;
1154
1155            // one-time initialization, no locks required
1156            sp<FastCapture>                     mFastCapture;   // non-0 if there is also a fast capture
1157            // FIXME audio watchdog thread
1158
1159            // contents are not guaranteed to be consistent, no locks required
1160            FastCaptureDumpState                mFastCaptureDumpState;
1161#ifdef STATE_QUEUE_DUMP
1162            // FIXME StateQueue observer and mutator dump fields
1163#endif
1164            // FIXME audio watchdog dump
1165
1166            // accessible only within the threadLoop(), no locks required
1167            //          mFastCapture->sq()      // for mutating and pushing state
1168            int32_t     mFastCaptureFutex;      // for cold idle
1169
1170            // The HAL input source is treated as non-blocking,
1171            // but current implementation is blocking
1172            sp<NBAIO_Source>                    mInputSource;
1173            // The source for the normal capture thread to read from: mInputSource or mPipeSource
1174            sp<NBAIO_Source>                    mNormalSource;
1175            // If a fast capture is present, the non-blocking pipe sink written to by fast capture,
1176            // otherwise clear
1177            sp<NBAIO_Sink>                      mPipeSink;
1178            // If a fast capture is present, the non-blocking pipe source read by normal thread,
1179            // otherwise clear
1180            sp<NBAIO_Source>                    mPipeSource;
1181            // Depth of pipe from fast capture to normal thread and fast clients, always power of 2
1182            size_t                              mPipeFramesP2;
1183            // If a fast capture is present, the Pipe as IMemory, otherwise clear
1184            sp<IMemory>                         mPipeMemory;
1185
1186            static const size_t                 kFastCaptureLogSize = 4 * 1024;
1187            sp<NBLog::Writer>                   mFastCaptureNBLogWriter;
1188
1189            bool                                mFastTrackAvail;    // true if fast track available
1190};
1191