Threads.h revision 6acd1d432f526ae9a055ddaece28bf93b474a776
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        MMAP                // control thread for MMAP stream
34    };
35
36    static const char *threadTypeToString(type_t type);
37
38    ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
39                audio_devices_t outDevice, audio_devices_t inDevice, type_t type,
40                bool systemReady);
41    virtual             ~ThreadBase();
42
43    virtual status_t    readyToRun();
44
45    void dumpBase(int fd, const Vector<String16>& args);
46    void dumpEffectChains(int fd, const Vector<String16>& args);
47
48    void clearPowerManager();
49
50    // base for record and playback
51    enum {
52        CFG_EVENT_IO,
53        CFG_EVENT_PRIO,
54        CFG_EVENT_SET_PARAMETER,
55        CFG_EVENT_CREATE_AUDIO_PATCH,
56        CFG_EVENT_RELEASE_AUDIO_PATCH,
57    };
58
59    class ConfigEventData: public RefBase {
60    public:
61        virtual ~ConfigEventData() {}
62
63        virtual  void dump(char *buffer, size_t size) = 0;
64    protected:
65        ConfigEventData() {}
66    };
67
68    // Config event sequence by client if status needed (e.g binder thread calling setParameters()):
69    //  1. create SetParameterConfigEvent. This sets mWaitStatus in config event
70    //  2. Lock mLock
71    //  3. Call sendConfigEvent_l(): Append to mConfigEvents and mWaitWorkCV.signal
72    //  4. sendConfigEvent_l() reads status from event->mStatus;
73    //  5. sendConfigEvent_l() returns status
74    //  6. Unlock
75    //
76    // Parameter sequence by server: threadLoop calling processConfigEvents_l():
77    // 1. Lock mLock
78    // 2. If there is an entry in mConfigEvents proceed ...
79    // 3. Read first entry in mConfigEvents
80    // 4. Remove first entry from mConfigEvents
81    // 5. Process
82    // 6. Set event->mStatus
83    // 7. event->mCond.signal
84    // 8. Unlock
85
86    class ConfigEvent: public RefBase {
87    public:
88        virtual ~ConfigEvent() {}
89
90        void dump(char *buffer, size_t size) { mData->dump(buffer, size); }
91
92        const int mType; // event type e.g. CFG_EVENT_IO
93        Mutex mLock;     // mutex associated with mCond
94        Condition mCond; // condition for status return
95        status_t mStatus; // status communicated to sender
96        bool mWaitStatus; // true if sender is waiting for status
97        bool mRequiresSystemReady; // true if must wait for system ready to enter event queue
98        sp<ConfigEventData> mData;     // event specific parameter data
99
100    protected:
101        explicit ConfigEvent(int type, bool requiresSystemReady = false) :
102            mType(type), mStatus(NO_ERROR), mWaitStatus(false),
103            mRequiresSystemReady(requiresSystemReady), mData(NULL) {}
104    };
105
106    class IoConfigEventData : public ConfigEventData {
107    public:
108        IoConfigEventData(audio_io_config_event event, pid_t pid) :
109            mEvent(event), mPid(pid) {}
110
111        virtual  void dump(char *buffer, size_t size) {
112            snprintf(buffer, size, "IO event: event %d\n", mEvent);
113        }
114
115        const audio_io_config_event mEvent;
116        const pid_t                 mPid;
117    };
118
119    class IoConfigEvent : public ConfigEvent {
120    public:
121        IoConfigEvent(audio_io_config_event event, pid_t pid) :
122            ConfigEvent(CFG_EVENT_IO) {
123            mData = new IoConfigEventData(event, pid);
124        }
125        virtual ~IoConfigEvent() {}
126    };
127
128    class PrioConfigEventData : public ConfigEventData {
129    public:
130        PrioConfigEventData(pid_t pid, pid_t tid, int32_t prio) :
131            mPid(pid), mTid(tid), mPrio(prio) {}
132
133        virtual  void dump(char *buffer, size_t size) {
134            snprintf(buffer, size, "Prio event: pid %d, tid %d, prio %d\n", mPid, mTid, mPrio);
135        }
136
137        const pid_t mPid;
138        const pid_t mTid;
139        const int32_t mPrio;
140    };
141
142    class PrioConfigEvent : public ConfigEvent {
143    public:
144        PrioConfigEvent(pid_t pid, pid_t tid, int32_t prio) :
145            ConfigEvent(CFG_EVENT_PRIO, true) {
146            mData = new PrioConfigEventData(pid, tid, prio);
147        }
148        virtual ~PrioConfigEvent() {}
149    };
150
151    class SetParameterConfigEventData : public ConfigEventData {
152    public:
153        explicit SetParameterConfigEventData(String8 keyValuePairs) :
154            mKeyValuePairs(keyValuePairs) {}
155
156        virtual  void dump(char *buffer, size_t size) {
157            snprintf(buffer, size, "KeyValue: %s\n", mKeyValuePairs.string());
158        }
159
160        const String8 mKeyValuePairs;
161    };
162
163    class SetParameterConfigEvent : public ConfigEvent {
164    public:
165        explicit SetParameterConfigEvent(String8 keyValuePairs) :
166            ConfigEvent(CFG_EVENT_SET_PARAMETER) {
167            mData = new SetParameterConfigEventData(keyValuePairs);
168            mWaitStatus = true;
169        }
170        virtual ~SetParameterConfigEvent() {}
171    };
172
173    class CreateAudioPatchConfigEventData : public ConfigEventData {
174    public:
175        CreateAudioPatchConfigEventData(const struct audio_patch patch,
176                                        audio_patch_handle_t handle) :
177            mPatch(patch), mHandle(handle) {}
178
179        virtual  void dump(char *buffer, size_t size) {
180            snprintf(buffer, size, "Patch handle: %u\n", mHandle);
181        }
182
183        const struct audio_patch mPatch;
184        audio_patch_handle_t mHandle;
185    };
186
187    class CreateAudioPatchConfigEvent : public ConfigEvent {
188    public:
189        CreateAudioPatchConfigEvent(const struct audio_patch patch,
190                                    audio_patch_handle_t handle) :
191            ConfigEvent(CFG_EVENT_CREATE_AUDIO_PATCH) {
192            mData = new CreateAudioPatchConfigEventData(patch, handle);
193            mWaitStatus = true;
194        }
195        virtual ~CreateAudioPatchConfigEvent() {}
196    };
197
198    class ReleaseAudioPatchConfigEventData : public ConfigEventData {
199    public:
200        explicit ReleaseAudioPatchConfigEventData(const audio_patch_handle_t handle) :
201            mHandle(handle) {}
202
203        virtual  void dump(char *buffer, size_t size) {
204            snprintf(buffer, size, "Patch handle: %u\n", mHandle);
205        }
206
207        audio_patch_handle_t mHandle;
208    };
209
210    class ReleaseAudioPatchConfigEvent : public ConfigEvent {
211    public:
212        explicit ReleaseAudioPatchConfigEvent(const audio_patch_handle_t handle) :
213            ConfigEvent(CFG_EVENT_RELEASE_AUDIO_PATCH) {
214            mData = new ReleaseAudioPatchConfigEventData(handle);
215            mWaitStatus = true;
216        }
217        virtual ~ReleaseAudioPatchConfigEvent() {}
218    };
219
220    class PMDeathRecipient : public IBinder::DeathRecipient {
221    public:
222        explicit    PMDeathRecipient(const wp<ThreadBase>& thread) : mThread(thread) {}
223        virtual     ~PMDeathRecipient() {}
224
225        // IBinder::DeathRecipient
226        virtual     void        binderDied(const wp<IBinder>& who);
227
228    private:
229                    PMDeathRecipient(const PMDeathRecipient&);
230                    PMDeathRecipient& operator = (const PMDeathRecipient&);
231
232        wp<ThreadBase> mThread;
233    };
234
235    virtual     status_t    initCheck() const = 0;
236
237                // static externally-visible
238                type_t      type() const { return mType; }
239                bool isDuplicating() const { return (mType == DUPLICATING); }
240
241                audio_io_handle_t id() const { return mId;}
242
243                // dynamic externally-visible
244                uint32_t    sampleRate() const { return mSampleRate; }
245                audio_channel_mask_t channelMask() const { return mChannelMask; }
246                audio_format_t format() const { return mHALFormat; }
247                uint32_t channelCount() const { return mChannelCount; }
248                // Called by AudioFlinger::frameCount(audio_io_handle_t output) and effects,
249                // and returns the [normal mix] buffer's frame count.
250    virtual     size_t      frameCount() const = 0;
251
252                // Return's the HAL's frame count i.e. fast mixer buffer size.
253                size_t      frameCountHAL() const { return mFrameCount; }
254
255                size_t      frameSize() const { return mFrameSize; }
256
257    // Should be "virtual status_t requestExitAndWait()" and override same
258    // method in Thread, but Thread::requestExitAndWait() is not yet virtual.
259                void        exit();
260    virtual     bool        checkForNewParameter_l(const String8& keyValuePair,
261                                                    status_t& status) = 0;
262    virtual     status_t    setParameters(const String8& keyValuePairs);
263    virtual     String8     getParameters(const String8& keys) = 0;
264    virtual     void        ioConfigChanged(audio_io_config_event event, pid_t pid = 0) = 0;
265                // sendConfigEvent_l() must be called with ThreadBase::mLock held
266                // Can temporarily release the lock if waiting for a reply from
267                // processConfigEvents_l().
268                status_t    sendConfigEvent_l(sp<ConfigEvent>& event);
269                void        sendIoConfigEvent(audio_io_config_event event, pid_t pid = 0);
270                void        sendIoConfigEvent_l(audio_io_config_event event, pid_t pid = 0);
271                void        sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio);
272                void        sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio);
273                status_t    sendSetParameterConfigEvent_l(const String8& keyValuePair);
274                status_t    sendCreateAudioPatchConfigEvent(const struct audio_patch *patch,
275                                                            audio_patch_handle_t *handle);
276                status_t    sendReleaseAudioPatchConfigEvent(audio_patch_handle_t handle);
277                void        processConfigEvents_l();
278    virtual     void        cacheParameters_l() = 0;
279    virtual     status_t    createAudioPatch_l(const struct audio_patch *patch,
280                                               audio_patch_handle_t *handle) = 0;
281    virtual     status_t    releaseAudioPatch_l(const audio_patch_handle_t handle) = 0;
282    virtual     void        getAudioPortConfig(struct audio_port_config *config) = 0;
283
284
285                // see note at declaration of mStandby, mOutDevice and mInDevice
286                bool        standby() const { return mStandby; }
287                audio_devices_t outDevice() const { return mOutDevice; }
288                audio_devices_t inDevice() const { return mInDevice; }
289
290    virtual     sp<StreamHalInterface> stream() const = 0;
291
292                sp<EffectHandle> createEffect_l(
293                                    const sp<AudioFlinger::Client>& client,
294                                    const sp<IEffectClient>& effectClient,
295                                    int32_t priority,
296                                    audio_session_t sessionId,
297                                    effect_descriptor_t *desc,
298                                    int *enabled,
299                                    status_t *status /*non-NULL*/,
300                                    bool pinned);
301
302                // return values for hasAudioSession (bit field)
303                enum effect_state {
304                    EFFECT_SESSION = 0x1,   // the audio session corresponds to at least one
305                                            // effect
306                    TRACK_SESSION = 0x2,    // the audio session corresponds to at least one
307                                            // track
308                    FAST_SESSION = 0x4      // the audio session corresponds to at least one
309                                            // fast track
310                };
311
312                // get effect chain corresponding to session Id.
313                sp<EffectChain> getEffectChain(audio_session_t sessionId);
314                // same as getEffectChain() but must be called with ThreadBase mutex locked
315                sp<EffectChain> getEffectChain_l(audio_session_t sessionId) const;
316                // add an effect chain to the chain list (mEffectChains)
317    virtual     status_t addEffectChain_l(const sp<EffectChain>& chain) = 0;
318                // remove an effect chain from the chain list (mEffectChains)
319    virtual     size_t removeEffectChain_l(const sp<EffectChain>& chain) = 0;
320                // lock all effect chains Mutexes. Must be called before releasing the
321                // ThreadBase mutex before processing the mixer and effects. This guarantees the
322                // integrity of the chains during the process.
323                // Also sets the parameter 'effectChains' to current value of mEffectChains.
324                void lockEffectChains_l(Vector< sp<EffectChain> >& effectChains);
325                // unlock effect chains after process
326                void unlockEffectChains(const Vector< sp<EffectChain> >& effectChains);
327                // get a copy of mEffectChains vector
328                Vector< sp<EffectChain> > getEffectChains_l() const { return mEffectChains; };
329                // set audio mode to all effect chains
330                void setMode(audio_mode_t mode);
331                // get effect module with corresponding ID on specified audio session
332                sp<AudioFlinger::EffectModule> getEffect(audio_session_t sessionId, int effectId);
333                sp<AudioFlinger::EffectModule> getEffect_l(audio_session_t sessionId, int effectId);
334                // add and effect module. Also creates the effect chain is none exists for
335                // the effects audio session
336                status_t addEffect_l(const sp< EffectModule>& effect);
337                // remove and effect module. Also removes the effect chain is this was the last
338                // effect
339                void removeEffect_l(const sp< EffectModule>& effect, bool release = false);
340                // disconnect an effect handle from module and destroy module if last handle
341                void disconnectEffectHandle(EffectHandle *handle, bool unpinIfLast);
342                // detach all tracks connected to an auxiliary effect
343    virtual     void detachAuxEffect_l(int effectId __unused) {}
344                // returns a combination of:
345                // - EFFECT_SESSION if effects on this audio session exist in one chain
346                // - TRACK_SESSION if tracks on this audio session exist
347                // - FAST_SESSION if fast tracks on this audio session exist
348    virtual     uint32_t hasAudioSession_l(audio_session_t sessionId) const = 0;
349                uint32_t hasAudioSession(audio_session_t sessionId) const {
350                    Mutex::Autolock _l(mLock);
351                    return hasAudioSession_l(sessionId);
352                }
353
354                // the value returned by default implementation is not important as the
355                // strategy is only meaningful for PlaybackThread which implements this method
356                virtual uint32_t getStrategyForSession_l(audio_session_t sessionId __unused)
357                        { return 0; }
358
359                // suspend or restore effect according to the type of effect passed. a NULL
360                // type pointer means suspend all effects in the session
361                void setEffectSuspended(const effect_uuid_t *type,
362                                        bool suspend,
363                                        audio_session_t sessionId = AUDIO_SESSION_OUTPUT_MIX);
364                // check if some effects must be suspended/restored when an effect is enabled
365                // or disabled
366                void checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
367                                                 bool enabled,
368                                                 audio_session_t sessionId =
369                                                        AUDIO_SESSION_OUTPUT_MIX);
370                void checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
371                                                   bool enabled,
372                                                   audio_session_t sessionId =
373                                                        AUDIO_SESSION_OUTPUT_MIX);
374
375                virtual status_t    setSyncEvent(const sp<SyncEvent>& event) = 0;
376                virtual bool        isValidSyncEvent(const sp<SyncEvent>& event) const = 0;
377
378                // Return a reference to a per-thread heap which can be used to allocate IMemory
379                // objects that will be read-only to client processes, read/write to mediaserver,
380                // and shared by all client processes of the thread.
381                // The heap is per-thread rather than common across all threads, because
382                // clients can't be trusted not to modify the offset of the IMemory they receive.
383                // If a thread does not have such a heap, this method returns 0.
384                virtual sp<MemoryDealer>    readOnlyHeap() const { return 0; }
385
386                virtual sp<IMemory> pipeMemory() const { return 0; }
387
388                        void systemReady();
389
390                // checkEffectCompatibility_l() must be called with ThreadBase::mLock held
391                virtual status_t    checkEffectCompatibility_l(const effect_descriptor_t *desc,
392                                                               audio_session_t sessionId) = 0;
393
394                        void        broadcast_l();
395
396    mutable     Mutex                   mLock;
397
398protected:
399
400                // entry describing an effect being suspended in mSuspendedSessions keyed vector
401                class SuspendedSessionDesc : public RefBase {
402                public:
403                    SuspendedSessionDesc() : mRefCount(0) {}
404
405                    int mRefCount;          // number of active suspend requests
406                    effect_uuid_t mType;    // effect type UUID
407                };
408
409                void        acquireWakeLock();
410                virtual void acquireWakeLock_l();
411                void        releaseWakeLock();
412                void        releaseWakeLock_l();
413                void        updateWakeLockUids_l(const SortedVector<uid_t> &uids);
414                void        getPowerManager_l();
415                void setEffectSuspended_l(const effect_uuid_t *type,
416                                          bool suspend,
417                                          audio_session_t sessionId);
418                // updated mSuspendedSessions when an effect suspended or restored
419                void        updateSuspendedSessions_l(const effect_uuid_t *type,
420                                                      bool suspend,
421                                                      audio_session_t sessionId);
422                // check if some effects must be suspended when an effect chain is added
423                void checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain);
424
425                String16 getWakeLockTag();
426
427    virtual     void        preExit() { }
428    virtual     void        setMasterMono_l(bool mono __unused) { }
429    virtual     bool        requireMonoBlend() { return false; }
430
431    friend class AudioFlinger;      // for mEffectChains
432
433                const type_t            mType;
434
435                // Used by parameters, config events, addTrack_l, exit
436                Condition               mWaitWorkCV;
437
438                const sp<AudioFlinger>  mAudioFlinger;
439
440                // updated by PlaybackThread::readOutputParameters_l() or
441                // RecordThread::readInputParameters_l()
442                uint32_t                mSampleRate;
443                size_t                  mFrameCount;       // output HAL, direct output, record
444                audio_channel_mask_t    mChannelMask;
445                uint32_t                mChannelCount;
446                size_t                  mFrameSize;
447                // not HAL frame size, this is for output sink (to pipe to fast mixer)
448                audio_format_t          mFormat;           // Source format for Recording and
449                                                           // Sink format for Playback.
450                                                           // Sink format may be different than
451                                                           // HAL format if Fastmixer is used.
452                audio_format_t          mHALFormat;
453                size_t                  mBufferSize;       // HAL buffer size for read() or write()
454
455                Vector< sp<ConfigEvent> >     mConfigEvents;
456                Vector< sp<ConfigEvent> >     mPendingConfigEvents; // events awaiting system ready
457
458                // These fields are written and read by thread itself without lock or barrier,
459                // and read by other threads without lock or barrier via standby(), outDevice()
460                // and inDevice().
461                // Because of the absence of a lock or barrier, any other thread that reads
462                // these fields must use the information in isolation, or be prepared to deal
463                // with possibility that it might be inconsistent with other information.
464                bool                    mStandby;     // Whether thread is currently in standby.
465                audio_devices_t         mOutDevice;   // output device
466                audio_devices_t         mInDevice;    // input device
467                audio_devices_t         mPrevOutDevice;   // previous output device
468                audio_devices_t         mPrevInDevice;    // previous input device
469                struct audio_patch      mPatch;
470                audio_source_t          mAudioSource;
471
472                const audio_io_handle_t mId;
473                Vector< sp<EffectChain> > mEffectChains;
474
475                static const int        kThreadNameLength = 16; // prctl(PR_SET_NAME) limit
476                char                    mThreadName[kThreadNameLength]; // guaranteed NUL-terminated
477                sp<IPowerManager>       mPowerManager;
478                sp<IBinder>             mWakeLockToken;
479                const sp<PMDeathRecipient> mDeathRecipient;
480                // list of suspended effects per session and per type. The first (outer) vector is
481                // keyed by session ID, the second (inner) by type UUID timeLow field
482                KeyedVector< audio_session_t, KeyedVector< int, sp<SuspendedSessionDesc> > >
483                                        mSuspendedSessions;
484                static const size_t     kLogSize = 4 * 1024;
485                sp<NBLog::Writer>       mNBLogWriter;
486                bool                    mSystemReady;
487                ExtendedTimestamp       mTimestamp;
488                // A condition that must be evaluated by the thread loop has changed and
489                // we must not wait for async write callback in the thread loop before evaluating it
490                bool                    mSignalPending;
491
492                // ActiveTracks is a sorted vector of track type T representing the
493                // active tracks of threadLoop() to be considered by the locked prepare portion.
494                // ActiveTracks should be accessed with the ThreadBase lock held.
495                //
496                // During processing and I/O, the threadLoop does not hold the lock;
497                // hence it does not directly use ActiveTracks.  Care should be taken
498                // to hold local strong references or defer removal of tracks
499                // if the threadLoop may still be accessing those tracks due to mix, etc.
500                //
501                // This class updates power information appropriately.
502                //
503
504                template <typename T>
505                class ActiveTracks {
506                public:
507                    ActiveTracks()
508                        : mActiveTracksGeneration(0)
509                        , mLastActiveTracksGeneration(0)
510                    { }
511
512                    ~ActiveTracks() {
513                        ALOGW_IF(!mActiveTracks.isEmpty(),
514                                "ActiveTracks should be empty in destructor");
515                    }
516                    // returns the last track added (even though it may have been
517                    // subsequently removed from ActiveTracks).
518                    //
519                    // Used for DirectOutputThread to ensure a flush is called when transitioning
520                    // to a new track (even though it may be on the same session).
521                    // Used for OffloadThread to ensure that volume and mixer state is
522                    // taken from the latest track added.
523                    //
524                    // The latest track is saved with a weak pointer to prevent keeping an
525                    // otherwise useless track alive. Thus the function will return nullptr
526                    // if the latest track has subsequently been removed and destroyed.
527                    sp<T> getLatest() {
528                        return mLatestActiveTrack.promote();
529                    }
530
531                    // SortedVector methods
532                    ssize_t         add(const sp<T> &track);
533                    ssize_t         remove(const sp<T> &track);
534                    size_t          size() const {
535                        return mActiveTracks.size();
536                    }
537                    ssize_t         indexOf(const sp<T>& item) {
538                        return mActiveTracks.indexOf(item);
539                    }
540                    sp<T>           operator[](size_t index) const {
541                        return mActiveTracks[index];
542                    }
543                    typename SortedVector<sp<T>>::iterator begin() {
544                        return mActiveTracks.begin();
545                    }
546                    typename SortedVector<sp<T>>::iterator end() {
547                        return mActiveTracks.end();
548                    }
549
550                    // Due to Binder recursion optimization, clear() and updatePowerState()
551                    // cannot be called from a Binder thread because they may call back into
552                    // the original calling process (system server) for BatteryNotifier
553                    // (which requires a Java environment that may not be present).
554                    // Hence, call clear() and updatePowerState() only from the
555                    // ThreadBase thread.
556                    void            clear();
557                    // periodically called in the threadLoop() to update power state uids.
558                    void            updatePowerState(sp<ThreadBase> thread, bool force = false);
559
560                private:
561                    SortedVector<uid_t> getWakeLockUids() {
562                        SortedVector<uid_t> wakeLockUids;
563                        for (const sp<T> &track : mActiveTracks) {
564                            wakeLockUids.add(track->uid());
565                        }
566                        return wakeLockUids; // moved by underlying SharedBuffer
567                    }
568
569                    std::map<uid_t, std::pair<ssize_t /* previous */, ssize_t /* current */>>
570                                        mBatteryCounter;
571                    SortedVector<sp<T>> mActiveTracks;
572                    int                 mActiveTracksGeneration;
573                    int                 mLastActiveTracksGeneration;
574                    wp<T>               mLatestActiveTrack; // latest track added to ActiveTracks
575                };
576};
577
578class VolumeInterface {
579 public:
580
581    virtual ~VolumeInterface() {}
582
583    virtual void        setMasterVolume(float value) = 0;
584    virtual void        setMasterMute(bool muted) = 0;
585    virtual void        setStreamVolume(audio_stream_type_t stream, float value) = 0;
586    virtual void        setStreamMute(audio_stream_type_t stream, bool muted) = 0;
587    virtual float       streamVolume(audio_stream_type_t stream) const = 0;
588
589};
590
591// --- PlaybackThread ---
592class PlaybackThread : public ThreadBase, public StreamOutHalInterfaceCallback,
593    public VolumeInterface {
594public:
595
596#include "PlaybackTracks.h"
597
598    enum mixer_state {
599        MIXER_IDLE,             // no active tracks
600        MIXER_TRACKS_ENABLED,   // at least one active track, but no track has any data ready
601        MIXER_TRACKS_READY,      // at least one active track, and at least one track has data
602        MIXER_DRAIN_TRACK,      // drain currently playing track
603        MIXER_DRAIN_ALL,        // fully drain the hardware
604        // standby mode does not have an enum value
605        // suspend by audio policy manager is orthogonal to mixer state
606    };
607
608    // retry count before removing active track in case of underrun on offloaded thread:
609    // we need to make sure that AudioTrack client has enough time to send large buffers
610    //FIXME may be more appropriate if expressed in time units. Need to revise how underrun is
611    // handled for offloaded tracks
612    static const int8_t kMaxTrackRetriesOffload = 20;
613    static const int8_t kMaxTrackStartupRetriesOffload = 100;
614    static const int8_t kMaxTrackStopRetriesOffload = 2;
615    // 14 tracks max per client allows for 2 misbehaving application leaving 4 available tracks.
616    static const uint32_t kMaxTracksPerUid = 14;
617
618    PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
619                   audio_io_handle_t id, audio_devices_t device, type_t type, bool systemReady);
620    virtual             ~PlaybackThread();
621
622                void        dump(int fd, const Vector<String16>& args);
623
624    // Thread virtuals
625    virtual     bool        threadLoop();
626
627    // RefBase
628    virtual     void        onFirstRef();
629
630    virtual     status_t    checkEffectCompatibility_l(const effect_descriptor_t *desc,
631                                                       audio_session_t sessionId);
632
633protected:
634    // Code snippets that were lifted up out of threadLoop()
635    virtual     void        threadLoop_mix() = 0;
636    virtual     void        threadLoop_sleepTime() = 0;
637    virtual     ssize_t     threadLoop_write();
638    virtual     void        threadLoop_drain();
639    virtual     void        threadLoop_standby();
640    virtual     void        threadLoop_exit();
641    virtual     void        threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
642
643                // prepareTracks_l reads and writes mActiveTracks, and returns
644                // the pending set of tracks to remove via Vector 'tracksToRemove'.  The caller
645                // is responsible for clearing or destroying this Vector later on, when it
646                // is safe to do so. That will drop the final ref count and destroy the tracks.
647    virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove) = 0;
648                void        removeTracks_l(const Vector< sp<Track> >& tracksToRemove);
649
650    // StreamOutHalInterfaceCallback implementation
651    virtual     void        onWriteReady();
652    virtual     void        onDrainReady();
653    virtual     void        onError();
654
655                void        resetWriteBlocked(uint32_t sequence);
656                void        resetDraining(uint32_t sequence);
657
658    virtual     bool        waitingAsyncCallback();
659    virtual     bool        waitingAsyncCallback_l();
660    virtual     bool        shouldStandby_l();
661    virtual     void        onAddNewTrack_l();
662                void        onAsyncError(); // error reported by AsyncCallbackThread
663
664    // ThreadBase virtuals
665    virtual     void        preExit();
666
667    virtual     bool        keepWakeLock() const { return true; }
668    virtual     void        acquireWakeLock_l() {
669                                ThreadBase::acquireWakeLock_l();
670                                mActiveTracks.updatePowerState(this, true /* force */);
671                            }
672
673public:
674
675    virtual     status_t    initCheck() const { return (mOutput == NULL) ? NO_INIT : NO_ERROR; }
676
677                // return estimated latency in milliseconds, as reported by HAL
678                uint32_t    latency() const;
679                // same, but lock must already be held
680                uint32_t    latency_l() const;
681
682                // VolumeInterface
683    virtual     void        setMasterVolume(float value);
684    virtual     void        setMasterMute(bool muted);
685    virtual     void        setStreamVolume(audio_stream_type_t stream, float value);
686    virtual     void        setStreamMute(audio_stream_type_t stream, bool muted);
687    virtual     float       streamVolume(audio_stream_type_t stream) const;
688
689                sp<Track>   createTrack_l(
690                                const sp<AudioFlinger::Client>& client,
691                                audio_stream_type_t streamType,
692                                uint32_t sampleRate,
693                                audio_format_t format,
694                                audio_channel_mask_t channelMask,
695                                size_t *pFrameCount,
696                                const sp<IMemory>& sharedBuffer,
697                                audio_session_t sessionId,
698                                audio_output_flags_t *flags,
699                                pid_t tid,
700                                uid_t uid,
701                                status_t *status /*non-NULL*/,
702                                audio_port_handle_t portId);
703
704                AudioStreamOut* getOutput() const;
705                AudioStreamOut* clearOutput();
706                virtual sp<StreamHalInterface> stream() const;
707
708                // a very large number of suspend() will eventually wraparound, but unlikely
709                void        suspend() { (void) android_atomic_inc(&mSuspended); }
710                void        restore()
711                                {
712                                    // if restore() is done without suspend(), get back into
713                                    // range so that the next suspend() will operate correctly
714                                    if (android_atomic_dec(&mSuspended) <= 0) {
715                                        android_atomic_release_store(0, &mSuspended);
716                                    }
717                                }
718                bool        isSuspended() const
719                                { return android_atomic_acquire_load(&mSuspended) > 0; }
720
721    virtual     String8     getParameters(const String8& keys);
722    virtual     void        ioConfigChanged(audio_io_config_event event, pid_t pid = 0);
723                status_t    getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames);
724                // FIXME rename mixBuffer() to sinkBuffer() and remove int16_t* dependency.
725                // Consider also removing and passing an explicit mMainBuffer initialization
726                // parameter to AF::PlaybackThread::Track::Track().
727                int16_t     *mixBuffer() const {
728                    return reinterpret_cast<int16_t *>(mSinkBuffer); };
729
730    virtual     void detachAuxEffect_l(int effectId);
731                status_t attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track>& track,
732                        int EffectId);
733                status_t attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track>& track,
734                        int EffectId);
735
736                virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
737                virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
738                virtual uint32_t hasAudioSession_l(audio_session_t sessionId) const;
739                virtual uint32_t getStrategyForSession_l(audio_session_t sessionId);
740
741
742                virtual status_t setSyncEvent(const sp<SyncEvent>& event);
743                virtual bool     isValidSyncEvent(const sp<SyncEvent>& event) const;
744
745                // called with AudioFlinger lock held
746                        bool     invalidateTracks_l(audio_stream_type_t streamType);
747                virtual void     invalidateTracks(audio_stream_type_t streamType);
748
749    virtual     size_t      frameCount() const { return mNormalFrameCount; }
750
751                status_t    getTimestamp_l(AudioTimestamp& timestamp);
752
753                void        addPatchTrack(const sp<PatchTrack>& track);
754                void        deletePatchTrack(const sp<PatchTrack>& track);
755
756    virtual     void        getAudioPortConfig(struct audio_port_config *config);
757
758protected:
759    // updated by readOutputParameters_l()
760    size_t                          mNormalFrameCount;  // normal mixer and effects
761
762    bool                            mThreadThrottle;     // throttle the thread processing
763    uint32_t                        mThreadThrottleTimeMs; // throttle time for MIXER threads
764    uint32_t                        mThreadThrottleEndMs;  // notify once per throttling
765    uint32_t                        mHalfBufferMs;       // half the buffer size in milliseconds
766
767    void*                           mSinkBuffer;         // frame size aligned sink buffer
768
769    // TODO:
770    // Rearrange the buffer info into a struct/class with
771    // clear, copy, construction, destruction methods.
772    //
773    // mSinkBuffer also has associated with it:
774    //
775    // mSinkBufferSize: Sink Buffer Size
776    // mFormat: Sink Buffer Format
777
778    // Mixer Buffer (mMixerBuffer*)
779    //
780    // In the case of floating point or multichannel data, which is not in the
781    // sink format, it is required to accumulate in a higher precision or greater channel count
782    // buffer before downmixing or data conversion to the sink buffer.
783
784    // Set to "true" to enable the Mixer Buffer otherwise mixer output goes to sink buffer.
785    bool                            mMixerBufferEnabled;
786
787    // Storage, 32 byte aligned (may make this alignment a requirement later).
788    // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
789    void*                           mMixerBuffer;
790
791    // Size of mMixerBuffer in bytes: mNormalFrameCount * #channels * sampsize.
792    size_t                          mMixerBufferSize;
793
794    // The audio format of mMixerBuffer. Set to AUDIO_FORMAT_PCM_(FLOAT|16_BIT) only.
795    audio_format_t                  mMixerBufferFormat;
796
797    // An internal flag set to true by MixerThread::prepareTracks_l()
798    // when mMixerBuffer contains valid data after mixing.
799    bool                            mMixerBufferValid;
800
801    // Effects Buffer (mEffectsBuffer*)
802    //
803    // In the case of effects data, which is not in the sink format,
804    // it is required to accumulate in a different buffer before data conversion
805    // to the sink buffer.
806
807    // Set to "true" to enable the Effects Buffer otherwise effects output goes to sink buffer.
808    bool                            mEffectBufferEnabled;
809
810    // Storage, 32 byte aligned (may make this alignment a requirement later).
811    // Due to constraints on mNormalFrameCount, the buffer size is a multiple of 16 frames.
812    void*                           mEffectBuffer;
813
814    // Size of mEffectsBuffer in bytes: mNormalFrameCount * #channels * sampsize.
815    size_t                          mEffectBufferSize;
816
817    // The audio format of mEffectsBuffer. Set to AUDIO_FORMAT_PCM_16_BIT only.
818    audio_format_t                  mEffectBufferFormat;
819
820    // An internal flag set to true by MixerThread::prepareTracks_l()
821    // when mEffectsBuffer contains valid data after mixing.
822    //
823    // When this is set, all mixer data is routed into the effects buffer
824    // for any processing (including output processing).
825    bool                            mEffectBufferValid;
826
827    // suspend count, > 0 means suspended.  While suspended, the thread continues to pull from
828    // tracks and mix, but doesn't write to HAL.  A2DP and SCO HAL implementations can't handle
829    // concurrent use of both of them, so Audio Policy Service suspends one of the threads to
830    // workaround that restriction.
831    // 'volatile' means accessed via atomic operations and no lock.
832    volatile int32_t                mSuspended;
833
834    int64_t                         mBytesWritten;
835    int64_t                         mFramesWritten; // not reset on standby
836    int64_t                         mSuspendedFrames; // not reset on standby
837private:
838    // mMasterMute is in both PlaybackThread and in AudioFlinger.  When a
839    // PlaybackThread needs to find out if master-muted, it checks it's local
840    // copy rather than the one in AudioFlinger.  This optimization saves a lock.
841    bool                            mMasterMute;
842                void        setMasterMute_l(bool muted) { mMasterMute = muted; }
843protected:
844    ActiveTracks<Track>     mActiveTracks;
845
846    // Allocate a track name for a given channel mask.
847    //   Returns name >= 0 if successful, -1 on failure.
848    virtual int             getTrackName_l(audio_channel_mask_t channelMask, audio_format_t format,
849                                           audio_session_t sessionId, uid_t uid) = 0;
850    virtual void            deleteTrackName_l(int name) = 0;
851
852    // Time to sleep between cycles when:
853    virtual uint32_t        activeSleepTimeUs() const;      // mixer state MIXER_TRACKS_ENABLED
854    virtual uint32_t        idleSleepTimeUs() const = 0;    // mixer state MIXER_IDLE
855    virtual uint32_t        suspendSleepTimeUs() const = 0; // audio policy manager suspended us
856    // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write()
857    // No sleep in standby mode; waits on a condition
858
859    // Code snippets that are temporarily lifted up out of threadLoop() until the merge
860                void        checkSilentMode_l();
861
862    // Non-trivial for DUPLICATING only
863    virtual     void        saveOutputTracks() { }
864    virtual     void        clearOutputTracks() { }
865
866    // Cache various calculated values, at threadLoop() entry and after a parameter change
867    virtual     void        cacheParameters_l();
868
869    virtual     uint32_t    correctLatency_l(uint32_t latency) const;
870
871    virtual     status_t    createAudioPatch_l(const struct audio_patch *patch,
872                                   audio_patch_handle_t *handle);
873    virtual     status_t    releaseAudioPatch_l(const audio_patch_handle_t handle);
874
875                bool        usesHwAvSync() const { return (mType == DIRECT) && (mOutput != NULL)
876                                    && mHwSupportsPause
877                                    && (mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC); }
878
879                uint32_t    trackCountForUid_l(uid_t uid);
880
881private:
882
883    friend class AudioFlinger;      // for numerous
884
885    PlaybackThread& operator = (const PlaybackThread&);
886
887    status_t    addTrack_l(const sp<Track>& track);
888    bool        destroyTrack_l(const sp<Track>& track);
889    void        removeTrack_l(const sp<Track>& track);
890
891    void        readOutputParameters_l();
892
893    virtual void dumpInternals(int fd, const Vector<String16>& args);
894    void        dumpTracks(int fd, const Vector<String16>& args);
895
896    SortedVector< sp<Track> >       mTracks;
897    stream_type_t                   mStreamTypes[AUDIO_STREAM_CNT];
898    AudioStreamOut                  *mOutput;
899
900    float                           mMasterVolume;
901    nsecs_t                         mLastWriteTime;
902    int                             mNumWrites;
903    int                             mNumDelayedWrites;
904    bool                            mInWrite;
905
906    // FIXME rename these former local variables of threadLoop to standard "m" names
907    nsecs_t                         mStandbyTimeNs;
908    size_t                          mSinkBufferSize;
909
910    // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l()
911    uint32_t                        mActiveSleepTimeUs;
912    uint32_t                        mIdleSleepTimeUs;
913
914    uint32_t                        mSleepTimeUs;
915
916    // mixer status returned by prepareTracks_l()
917    mixer_state                     mMixerStatus; // current cycle
918                                                  // previous cycle when in prepareTracks_l()
919    mixer_state                     mMixerStatusIgnoringFastTracks;
920                                                  // FIXME or a separate ready state per track
921
922    // FIXME move these declarations into the specific sub-class that needs them
923    // MIXER only
924    uint32_t                        sleepTimeShift;
925
926    // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value
927    nsecs_t                         mStandbyDelayNs;
928
929    // MIXER only
930    nsecs_t                         maxPeriod;
931
932    // DUPLICATING only
933    uint32_t                        writeFrames;
934
935    size_t                          mBytesRemaining;
936    size_t                          mCurrentWriteLength;
937    bool                            mUseAsyncWrite;
938    // mWriteAckSequence contains current write sequence on bits 31-1. The write sequence is
939    // incremented each time a write(), a flush() or a standby() occurs.
940    // Bit 0 is set when a write blocks and indicates a callback is expected.
941    // Bit 0 is reset by the async callback thread calling resetWriteBlocked(). Out of sequence
942    // callbacks are ignored.
943    uint32_t                        mWriteAckSequence;
944    // mDrainSequence contains current drain sequence on bits 31-1. The drain sequence is
945    // incremented each time a drain is requested or a flush() or standby() occurs.
946    // Bit 0 is set when the drain() command is called at the HAL and indicates a callback is
947    // expected.
948    // Bit 0 is reset by the async callback thread calling resetDraining(). Out of sequence
949    // callbacks are ignored.
950    uint32_t                        mDrainSequence;
951    sp<AsyncCallbackThread>         mCallbackThread;
952
953private:
954    // The HAL output sink is treated as non-blocking, but current implementation is blocking
955    sp<NBAIO_Sink>          mOutputSink;
956    // If a fast mixer is present, the blocking pipe sink, otherwise clear
957    sp<NBAIO_Sink>          mPipeSink;
958    // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink
959    sp<NBAIO_Sink>          mNormalSink;
960#ifdef TEE_SINK
961    // For dumpsys
962    sp<NBAIO_Sink>          mTeeSink;
963    sp<NBAIO_Source>        mTeeSource;
964#endif
965    uint32_t                mScreenState;   // cached copy of gScreenState
966    static const size_t     kFastMixerLogSize = 4 * 1024;
967    sp<NBLog::Writer>       mFastMixerNBLogWriter;
968
969    // Do not call from a sched_fifo thread as it uses a system time call
970    // and obtains a local mutex.
971    class LocalLog {
972    public:
973        void log(const char *fmt, ...) {
974            va_list val;
975            va_start(val, fmt);
976
977            // format to buffer
978            char buffer[512];
979            int length = vsnprintf(buffer, sizeof(buffer), fmt, val);
980            if (length >= (signed)sizeof(buffer)) {
981                length = sizeof(buffer) - 1;
982            }
983
984            // strip out trailing newline
985            while (length > 0 && buffer[length - 1] == '\n') {
986                buffer[--length] = 0;
987            }
988
989            // store in circular array
990            AutoMutex _l(mLock);
991            mLog.emplace_back(
992                    std::make_pair(systemTime(SYSTEM_TIME_REALTIME), std::string(buffer)));
993            if (mLog.size() > kLogSize) {
994                mLog.pop_front();
995            }
996
997            va_end(val);
998        }
999
1000        void dump(int fd, const Vector<String16>& args, const char *prefix = "") {
1001            if (!AudioFlinger::dumpTryLock(mLock)) return; // a local lock, shouldn't happen
1002            if (mLog.size() > 0) {
1003                bool dumpAll = false;
1004                for (const auto &arg : args) {
1005                    if (arg == String16("--locallog")) {
1006                        dumpAll = true;
1007                    }
1008                }
1009
1010                dprintf(fd, "Local Log:\n");
1011                auto it = mLog.begin();
1012                if (!dumpAll) {
1013                    const size_t lines =
1014                            (size_t)property_get_int32("audio.locallog.lines", kLogPrint);
1015                    if (mLog.size() > lines) {
1016                        it += (mLog.size() - lines);
1017                    }
1018                }
1019                for (; it != mLog.end(); ++it) {
1020                    const int64_t ns = it->first;
1021                    const int ns_per_sec = 1000000000;
1022                    const time_t sec = ns / ns_per_sec;
1023                    struct tm tm;
1024                    localtime_r(&sec, &tm);
1025
1026                    dprintf(fd, "%s%02d-%02d %02d:%02d:%02d.%03d %s\n",
1027                            prefix,
1028                            tm.tm_mon + 1, // localtime_r uses months in 0 - 11 range
1029                            tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec,
1030                            (int)(ns % ns_per_sec / 1000000),
1031                            it->second.c_str());
1032                }
1033            }
1034            mLock.unlock();
1035        }
1036
1037    private:
1038        Mutex mLock;
1039        static const size_t kLogSize = 256; // full history
1040        static const size_t kLogPrint = 32; // default print history
1041        std::deque<std::pair<int64_t, std::string>> mLog;
1042    } mLocalLog;
1043
1044public:
1045    virtual     bool        hasFastMixer() const = 0;
1046    virtual     FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex __unused) const
1047                                { FastTrackUnderruns dummy; return dummy; }
1048
1049protected:
1050                // accessed by both binder threads and within threadLoop(), lock on mutex needed
1051                unsigned    mFastTrackAvailMask;    // bit i set if fast track [i] is available
1052                bool        mHwSupportsPause;
1053                bool        mHwPaused;
1054                bool        mFlushPending;
1055};
1056
1057class MixerThread : public PlaybackThread {
1058public:
1059    MixerThread(const sp<AudioFlinger>& audioFlinger,
1060                AudioStreamOut* output,
1061                audio_io_handle_t id,
1062                audio_devices_t device,
1063                bool systemReady,
1064                type_t type = MIXER);
1065    virtual             ~MixerThread();
1066
1067    // Thread virtuals
1068
1069    virtual     bool        checkForNewParameter_l(const String8& keyValuePair,
1070                                                   status_t& status);
1071    virtual     void        dumpInternals(int fd, const Vector<String16>& args);
1072
1073protected:
1074    virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
1075    virtual     int         getTrackName_l(audio_channel_mask_t channelMask, audio_format_t format,
1076                                           audio_session_t sessionId, uid_t uid);
1077    virtual     void        deleteTrackName_l(int name);
1078    virtual     uint32_t    idleSleepTimeUs() const;
1079    virtual     uint32_t    suspendSleepTimeUs() const;
1080    virtual     void        cacheParameters_l();
1081
1082    virtual void acquireWakeLock_l() {
1083        PlaybackThread::acquireWakeLock_l();
1084        if (hasFastMixer()) {
1085            mFastMixer->setBoottimeOffset(
1086                    mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME]);
1087        }
1088    }
1089
1090    // threadLoop snippets
1091    virtual     ssize_t     threadLoop_write();
1092    virtual     void        threadLoop_standby();
1093    virtual     void        threadLoop_mix();
1094    virtual     void        threadLoop_sleepTime();
1095    virtual     void        threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
1096    virtual     uint32_t    correctLatency_l(uint32_t latency) const;
1097
1098    virtual     status_t    createAudioPatch_l(const struct audio_patch *patch,
1099                                   audio_patch_handle_t *handle);
1100    virtual     status_t    releaseAudioPatch_l(const audio_patch_handle_t handle);
1101
1102                AudioMixer* mAudioMixer;    // normal mixer
1103private:
1104                // one-time initialization, no locks required
1105                sp<FastMixer>     mFastMixer;     // non-0 if there is also a fast mixer
1106                sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread
1107
1108                // contents are not guaranteed to be consistent, no locks required
1109                FastMixerDumpState mFastMixerDumpState;
1110#ifdef STATE_QUEUE_DUMP
1111                StateQueueObserverDump mStateQueueObserverDump;
1112                StateQueueMutatorDump  mStateQueueMutatorDump;
1113#endif
1114                AudioWatchdogDump mAudioWatchdogDump;
1115
1116                // accessible only within the threadLoop(), no locks required
1117                //          mFastMixer->sq()    // for mutating and pushing state
1118                int32_t     mFastMixerFutex;    // for cold idle
1119
1120                std::atomic_bool mMasterMono;
1121public:
1122    virtual     bool        hasFastMixer() const { return mFastMixer != 0; }
1123    virtual     FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const {
1124                              ALOG_ASSERT(fastIndex < FastMixerState::sMaxFastTracks);
1125                              return mFastMixerDumpState.mTracks[fastIndex].mUnderruns;
1126                            }
1127
1128protected:
1129    virtual     void       setMasterMono_l(bool mono) {
1130                               mMasterMono.store(mono);
1131                               if (mFastMixer != nullptr) { /* hasFastMixer() */
1132                                   mFastMixer->setMasterMono(mMasterMono);
1133                               }
1134                           }
1135                // the FastMixer performs mono blend if it exists.
1136                // Blending with limiter is not idempotent,
1137                // and blending without limiter is idempotent but inefficient to do twice.
1138    virtual     bool       requireMonoBlend() { return mMasterMono.load() && !hasFastMixer(); }
1139};
1140
1141class DirectOutputThread : public PlaybackThread {
1142public:
1143
1144    DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
1145                       audio_io_handle_t id, audio_devices_t device, bool systemReady);
1146    virtual                 ~DirectOutputThread();
1147
1148    // Thread virtuals
1149
1150    virtual     bool        checkForNewParameter_l(const String8& keyValuePair,
1151                                                   status_t& status);
1152    virtual     void        flushHw_l();
1153
1154protected:
1155    virtual     int         getTrackName_l(audio_channel_mask_t channelMask, audio_format_t format,
1156                                           audio_session_t sessionId, uid_t uid);
1157    virtual     void        deleteTrackName_l(int name);
1158    virtual     uint32_t    activeSleepTimeUs() const;
1159    virtual     uint32_t    idleSleepTimeUs() const;
1160    virtual     uint32_t    suspendSleepTimeUs() const;
1161    virtual     void        cacheParameters_l();
1162
1163    // threadLoop snippets
1164    virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
1165    virtual     void        threadLoop_mix();
1166    virtual     void        threadLoop_sleepTime();
1167    virtual     void        threadLoop_exit();
1168    virtual     bool        shouldStandby_l();
1169
1170    virtual     void        onAddNewTrack_l();
1171
1172    // volumes last sent to audio HAL with stream->set_volume()
1173    float mLeftVolFloat;
1174    float mRightVolFloat;
1175
1176    DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
1177                        audio_io_handle_t id, uint32_t device, ThreadBase::type_t type,
1178                        bool systemReady);
1179    void processVolume_l(Track *track, bool lastTrack);
1180
1181    // prepareTracks_l() tells threadLoop_mix() the name of the single active track
1182    sp<Track>               mActiveTrack;
1183
1184    wp<Track>               mPreviousTrack;         // used to detect track switch
1185
1186public:
1187    virtual     bool        hasFastMixer() const { return false; }
1188};
1189
1190class OffloadThread : public DirectOutputThread {
1191public:
1192
1193    OffloadThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
1194                        audio_io_handle_t id, uint32_t device, bool systemReady);
1195    virtual                 ~OffloadThread() {};
1196    virtual     void        flushHw_l();
1197
1198protected:
1199    // threadLoop snippets
1200    virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
1201    virtual     void        threadLoop_exit();
1202
1203    virtual     bool        waitingAsyncCallback();
1204    virtual     bool        waitingAsyncCallback_l();
1205    virtual     void        invalidateTracks(audio_stream_type_t streamType);
1206
1207    virtual     bool        keepWakeLock() const { return (mKeepWakeLock || (mDrainSequence & 1)); }
1208
1209private:
1210    size_t      mPausedWriteLength;     // length in bytes of write interrupted by pause
1211    size_t      mPausedBytesRemaining;  // bytes still waiting in mixbuffer after resume
1212    bool        mKeepWakeLock;          // keep wake lock while waiting for write callback
1213    uint64_t    mOffloadUnderrunPosition; // Current frame position for offloaded playback
1214                                          // used and valid only during underrun.  ~0 if
1215                                          // no underrun has occurred during playback and
1216                                          // is not reset on standby.
1217};
1218
1219class AsyncCallbackThread : public Thread {
1220public:
1221
1222    explicit AsyncCallbackThread(const wp<PlaybackThread>& playbackThread);
1223
1224    virtual             ~AsyncCallbackThread();
1225
1226    // Thread virtuals
1227    virtual bool        threadLoop();
1228
1229    // RefBase
1230    virtual void        onFirstRef();
1231
1232            void        exit();
1233            void        setWriteBlocked(uint32_t sequence);
1234            void        resetWriteBlocked();
1235            void        setDraining(uint32_t sequence);
1236            void        resetDraining();
1237            void        setAsyncError();
1238
1239private:
1240    const wp<PlaybackThread>   mPlaybackThread;
1241    // mWriteAckSequence corresponds to the last write sequence passed by the offload thread via
1242    // setWriteBlocked(). The sequence is shifted one bit to the left and the lsb is used
1243    // to indicate that the callback has been received via resetWriteBlocked()
1244    uint32_t                   mWriteAckSequence;
1245    // mDrainSequence corresponds to the last drain sequence passed by the offload thread via
1246    // setDraining(). The sequence is shifted one bit to the left and the lsb is used
1247    // to indicate that the callback has been received via resetDraining()
1248    uint32_t                   mDrainSequence;
1249    Condition                  mWaitWorkCV;
1250    Mutex                      mLock;
1251    bool                       mAsyncError;
1252};
1253
1254class DuplicatingThread : public MixerThread {
1255public:
1256    DuplicatingThread(const sp<AudioFlinger>& audioFlinger, MixerThread* mainThread,
1257                      audio_io_handle_t id, bool systemReady);
1258    virtual                 ~DuplicatingThread();
1259
1260    // Thread virtuals
1261                void        addOutputTrack(MixerThread* thread);
1262                void        removeOutputTrack(MixerThread* thread);
1263                uint32_t    waitTimeMs() const { return mWaitTimeMs; }
1264protected:
1265    virtual     uint32_t    activeSleepTimeUs() const;
1266
1267private:
1268                bool        outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks);
1269protected:
1270    // threadLoop snippets
1271    virtual     void        threadLoop_mix();
1272    virtual     void        threadLoop_sleepTime();
1273    virtual     ssize_t     threadLoop_write();
1274    virtual     void        threadLoop_standby();
1275    virtual     void        cacheParameters_l();
1276
1277private:
1278    // called from threadLoop, addOutputTrack, removeOutputTrack
1279    virtual     void        updateWaitTime_l();
1280protected:
1281    virtual     void        saveOutputTracks();
1282    virtual     void        clearOutputTracks();
1283private:
1284
1285                uint32_t    mWaitTimeMs;
1286    SortedVector < sp<OutputTrack> >  outputTracks;
1287    SortedVector < sp<OutputTrack> >  mOutputTracks;
1288public:
1289    virtual     bool        hasFastMixer() const { return false; }
1290};
1291
1292// record thread
1293class RecordThread : public ThreadBase
1294{
1295public:
1296
1297    class RecordTrack;
1298
1299    /* The ResamplerBufferProvider is used to retrieve recorded input data from the
1300     * RecordThread.  It maintains local state on the relative position of the read
1301     * position of the RecordTrack compared with the RecordThread.
1302     */
1303    class ResamplerBufferProvider : public AudioBufferProvider
1304    {
1305    public:
1306        explicit ResamplerBufferProvider(RecordTrack* recordTrack) :
1307            mRecordTrack(recordTrack),
1308            mRsmpInUnrel(0), mRsmpInFront(0) { }
1309        virtual ~ResamplerBufferProvider() { }
1310
1311        // called to set the ResamplerBufferProvider to head of the RecordThread data buffer,
1312        // skipping any previous data read from the hal.
1313        virtual void reset();
1314
1315        /* Synchronizes RecordTrack position with the RecordThread.
1316         * Calculates available frames and handle overruns if the RecordThread
1317         * has advanced faster than the ResamplerBufferProvider has retrieved data.
1318         * TODO: why not do this for every getNextBuffer?
1319         *
1320         * Parameters
1321         * framesAvailable:  pointer to optional output size_t to store record track
1322         *                   frames available.
1323         *      hasOverrun:  pointer to optional boolean, returns true if track has overrun.
1324         */
1325
1326        virtual void sync(size_t *framesAvailable = NULL, bool *hasOverrun = NULL);
1327
1328        // AudioBufferProvider interface
1329        virtual status_t    getNextBuffer(AudioBufferProvider::Buffer* buffer);
1330        virtual void        releaseBuffer(AudioBufferProvider::Buffer* buffer);
1331    private:
1332        RecordTrack * const mRecordTrack;
1333        size_t              mRsmpInUnrel;   // unreleased frames remaining from
1334                                            // most recent getNextBuffer
1335                                            // for debug only
1336        int32_t             mRsmpInFront;   // next available frame
1337                                            // rolling counter that is never cleared
1338    };
1339
1340    /* The RecordBufferConverter is used for format, channel, and sample rate
1341     * conversion for a RecordTrack.
1342     *
1343     * TODO: Self contained, so move to a separate file later.
1344     *
1345     * RecordBufferConverter uses the convert() method rather than exposing a
1346     * buffer provider interface; this is to save a memory copy.
1347     */
1348    class RecordBufferConverter
1349    {
1350    public:
1351        RecordBufferConverter(
1352                audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
1353                uint32_t srcSampleRate,
1354                audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
1355                uint32_t dstSampleRate);
1356
1357        ~RecordBufferConverter();
1358
1359        /* Converts input data from an AudioBufferProvider by format, channelMask,
1360         * and sampleRate to a destination buffer.
1361         *
1362         * Parameters
1363         *      dst:  buffer to place the converted data.
1364         * provider:  buffer provider to obtain source data.
1365         *   frames:  number of frames to convert
1366         *
1367         * Returns the number of frames converted.
1368         */
1369        size_t convert(void *dst, AudioBufferProvider *provider, size_t frames);
1370
1371        // returns NO_ERROR if constructor was successful
1372        status_t initCheck() const {
1373            // mSrcChannelMask set on successful updateParameters
1374            return mSrcChannelMask != AUDIO_CHANNEL_INVALID ? NO_ERROR : NO_INIT;
1375        }
1376
1377        // allows dynamic reconfigure of all parameters
1378        status_t updateParameters(
1379                audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
1380                uint32_t srcSampleRate,
1381                audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
1382                uint32_t dstSampleRate);
1383
1384        // called to reset resampler buffers on record track discontinuity
1385        void reset() {
1386            if (mResampler != NULL) {
1387                mResampler->reset();
1388            }
1389        }
1390
1391    private:
1392        // format conversion when not using resampler
1393        void convertNoResampler(void *dst, const void *src, size_t frames);
1394
1395        // format conversion when using resampler; modifies src in-place
1396        void convertResampler(void *dst, /*not-a-const*/ void *src, size_t frames);
1397
1398        // user provided information
1399        audio_channel_mask_t mSrcChannelMask;
1400        audio_format_t       mSrcFormat;
1401        uint32_t             mSrcSampleRate;
1402        audio_channel_mask_t mDstChannelMask;
1403        audio_format_t       mDstFormat;
1404        uint32_t             mDstSampleRate;
1405
1406        // derived information
1407        uint32_t             mSrcChannelCount;
1408        uint32_t             mDstChannelCount;
1409        size_t               mDstFrameSize;
1410
1411        // format conversion buffer
1412        void                *mBuf;
1413        size_t               mBufFrames;
1414        size_t               mBufFrameSize;
1415
1416        // resampler info
1417        AudioResampler      *mResampler;
1418
1419        bool                 mIsLegacyDownmix;  // legacy stereo to mono conversion needed
1420        bool                 mIsLegacyUpmix;    // legacy mono to stereo conversion needed
1421        bool                 mRequiresFloat;    // data processing requires float (e.g. resampler)
1422        PassthruBufferProvider *mInputConverterProvider;    // converts input to float
1423        int8_t               mIdxAry[sizeof(uint32_t) * 8]; // used for channel mask conversion
1424    };
1425
1426#include "RecordTracks.h"
1427
1428            RecordThread(const sp<AudioFlinger>& audioFlinger,
1429                    AudioStreamIn *input,
1430                    audio_io_handle_t id,
1431                    audio_devices_t outDevice,
1432                    audio_devices_t inDevice,
1433                    bool systemReady
1434#ifdef TEE_SINK
1435                    , const sp<NBAIO_Sink>& teeSink
1436#endif
1437                    );
1438            virtual     ~RecordThread();
1439
1440    // no addTrack_l ?
1441    void        destroyTrack_l(const sp<RecordTrack>& track);
1442    void        removeTrack_l(const sp<RecordTrack>& track);
1443
1444    void        dumpInternals(int fd, const Vector<String16>& args);
1445    void        dumpTracks(int fd, const Vector<String16>& args);
1446
1447    // Thread virtuals
1448    virtual bool        threadLoop();
1449
1450    // RefBase
1451    virtual void        onFirstRef();
1452
1453    virtual status_t    initCheck() const { return (mInput == NULL) ? NO_INIT : NO_ERROR; }
1454
1455    virtual sp<MemoryDealer>    readOnlyHeap() const { return mReadOnlyHeap; }
1456
1457    virtual sp<IMemory> pipeMemory() const { return mPipeMemory; }
1458
1459            sp<AudioFlinger::RecordThread::RecordTrack>  createRecordTrack_l(
1460                    const sp<AudioFlinger::Client>& client,
1461                    uint32_t sampleRate,
1462                    audio_format_t format,
1463                    audio_channel_mask_t channelMask,
1464                    size_t *pFrameCount,
1465                    audio_session_t sessionId,
1466                    size_t *notificationFrames,
1467                    uid_t uid,
1468                    audio_input_flags_t *flags,
1469                    pid_t tid,
1470                    status_t *status /*non-NULL*/,
1471                    audio_port_handle_t portId);
1472
1473            status_t    start(RecordTrack* recordTrack,
1474                              AudioSystem::sync_event_t event,
1475                              audio_session_t triggerSession);
1476
1477            // ask the thread to stop the specified track, and
1478            // return true if the caller should then do it's part of the stopping process
1479            bool        stop(RecordTrack* recordTrack);
1480
1481            void        dump(int fd, const Vector<String16>& args);
1482            AudioStreamIn* clearInput();
1483            virtual sp<StreamHalInterface> stream() const;
1484
1485
1486    virtual bool        checkForNewParameter_l(const String8& keyValuePair,
1487                                               status_t& status);
1488    virtual void        cacheParameters_l() {}
1489    virtual String8     getParameters(const String8& keys);
1490    virtual void        ioConfigChanged(audio_io_config_event event, pid_t pid = 0);
1491    virtual status_t    createAudioPatch_l(const struct audio_patch *patch,
1492                                           audio_patch_handle_t *handle);
1493    virtual status_t    releaseAudioPatch_l(const audio_patch_handle_t handle);
1494
1495            void        addPatchRecord(const sp<PatchRecord>& record);
1496            void        deletePatchRecord(const sp<PatchRecord>& record);
1497
1498            void        readInputParameters_l();
1499    virtual uint32_t    getInputFramesLost();
1500
1501    virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
1502    virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
1503    virtual uint32_t hasAudioSession_l(audio_session_t sessionId) const;
1504
1505            // Return the set of unique session IDs across all tracks.
1506            // The keys are the session IDs, and the associated values are meaningless.
1507            // FIXME replace by Set [and implement Bag/Multiset for other uses].
1508            KeyedVector<audio_session_t, bool> sessionIds() const;
1509
1510    virtual status_t setSyncEvent(const sp<SyncEvent>& event);
1511    virtual bool     isValidSyncEvent(const sp<SyncEvent>& event) const;
1512
1513    static void syncStartEventCallback(const wp<SyncEvent>& event);
1514
1515    virtual size_t      frameCount() const { return mFrameCount; }
1516            bool        hasFastCapture() const { return mFastCapture != 0; }
1517    virtual void        getAudioPortConfig(struct audio_port_config *config);
1518
1519    virtual status_t    checkEffectCompatibility_l(const effect_descriptor_t *desc,
1520                                                   audio_session_t sessionId);
1521
1522    virtual void        acquireWakeLock_l() {
1523                            ThreadBase::acquireWakeLock_l();
1524                            mActiveTracks.updatePowerState(this, true /* force */);
1525                        }
1526
1527private:
1528            // Enter standby if not already in standby, and set mStandby flag
1529            void    standbyIfNotAlreadyInStandby();
1530
1531            // Call the HAL standby method unconditionally, and don't change mStandby flag
1532            void    inputStandBy();
1533
1534            AudioStreamIn                       *mInput;
1535            SortedVector < sp<RecordTrack> >    mTracks;
1536            // mActiveTracks has dual roles:  it indicates the current active track(s), and
1537            // is used together with mStartStopCond to indicate start()/stop() progress
1538            ActiveTracks<RecordTrack>           mActiveTracks;
1539
1540            Condition                           mStartStopCond;
1541
1542            // resampler converts input at HAL Hz to output at AudioRecord client Hz
1543            void                               *mRsmpInBuffer;  // size = mRsmpInFramesOA
1544            size_t                              mRsmpInFrames;  // size of resampler input in frames
1545            size_t                              mRsmpInFramesP2;// size rounded up to a power-of-2
1546            size_t                              mRsmpInFramesOA;// mRsmpInFramesP2 + over-allocation
1547
1548            // rolling index that is never cleared
1549            int32_t                             mRsmpInRear;    // last filled frame + 1
1550
1551            // For dumpsys
1552            const sp<NBAIO_Sink>                mTeeSink;
1553
1554            const sp<MemoryDealer>              mReadOnlyHeap;
1555
1556            // one-time initialization, no locks required
1557            sp<FastCapture>                     mFastCapture;   // non-0 if there is also
1558                                                                // a fast capture
1559
1560            // FIXME audio watchdog thread
1561
1562            // contents are not guaranteed to be consistent, no locks required
1563            FastCaptureDumpState                mFastCaptureDumpState;
1564#ifdef STATE_QUEUE_DUMP
1565            // FIXME StateQueue observer and mutator dump fields
1566#endif
1567            // FIXME audio watchdog dump
1568
1569            // accessible only within the threadLoop(), no locks required
1570            //          mFastCapture->sq()      // for mutating and pushing state
1571            int32_t     mFastCaptureFutex;      // for cold idle
1572
1573            // The HAL input source is treated as non-blocking,
1574            // but current implementation is blocking
1575            sp<NBAIO_Source>                    mInputSource;
1576            // The source for the normal capture thread to read from: mInputSource or mPipeSource
1577            sp<NBAIO_Source>                    mNormalSource;
1578            // If a fast capture is present, the non-blocking pipe sink written to by fast capture,
1579            // otherwise clear
1580            sp<NBAIO_Sink>                      mPipeSink;
1581            // If a fast capture is present, the non-blocking pipe source read by normal thread,
1582            // otherwise clear
1583            sp<NBAIO_Source>                    mPipeSource;
1584            // Depth of pipe from fast capture to normal thread and fast clients, always power of 2
1585            size_t                              mPipeFramesP2;
1586            // If a fast capture is present, the Pipe as IMemory, otherwise clear
1587            sp<IMemory>                         mPipeMemory;
1588
1589            static const size_t                 kFastCaptureLogSize = 4 * 1024;
1590            sp<NBLog::Writer>                   mFastCaptureNBLogWriter;
1591
1592            bool                                mFastTrackAvail;    // true if fast track available
1593};
1594
1595class MmapThread : public ThreadBase
1596{
1597 public:
1598
1599#include "MmapTracks.h"
1600
1601    MmapThread(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1602                      AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
1603                      audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady);
1604    virtual     ~MmapThread();
1605
1606    virtual     void        configure(const audio_attributes_t *attr,
1607                                      audio_stream_type_t streamType,
1608                                      audio_session_t sessionId,
1609                                      const sp<MmapStreamCallback>& callback,
1610                                      audio_port_handle_t portId);
1611
1612                void        disconnect();
1613
1614    // MmapStreamInterface
1615    status_t createMmapBuffer(int32_t minSizeFrames,
1616                                      struct audio_mmap_buffer_info *info);
1617    status_t getMmapPosition(struct audio_mmap_position *position);
1618    status_t start(const MmapStreamInterface::Client& client, audio_port_handle_t *handle);
1619    status_t stop(audio_port_handle_t handle);
1620
1621    // RefBase
1622    virtual     void        onFirstRef();
1623
1624    // Thread virtuals
1625    virtual     bool        threadLoop();
1626
1627    virtual     void        threadLoop_exit();
1628    virtual     void        threadLoop_standby();
1629
1630    virtual     status_t    initCheck() const { return (mHalStream == 0) ? NO_INIT : NO_ERROR; }
1631    virtual     size_t      frameCount() const { return mFrameCount; }
1632    virtual     bool        checkForNewParameter_l(const String8& keyValuePair,
1633                                                    status_t& status);
1634    virtual     String8     getParameters(const String8& keys);
1635    virtual     void        ioConfigChanged(audio_io_config_event event, pid_t pid = 0);
1636                void        readHalParameters_l();
1637    virtual     void        cacheParameters_l() {}
1638    virtual     status_t    createAudioPatch_l(const struct audio_patch *patch,
1639                                               audio_patch_handle_t *handle);
1640    virtual     status_t    releaseAudioPatch_l(const audio_patch_handle_t handle);
1641    virtual     void        getAudioPortConfig(struct audio_port_config *config);
1642
1643    virtual     sp<StreamHalInterface> stream() const { return mHalStream; }
1644    virtual     status_t    addEffectChain_l(const sp<EffectChain>& chain);
1645    virtual     size_t      removeEffectChain_l(const sp<EffectChain>& chain);
1646    virtual     status_t    checkEffectCompatibility_l(const effect_descriptor_t *desc,
1647                                                               audio_session_t sessionId);
1648
1649    virtual     uint32_t    hasAudioSession_l(audio_session_t sessionId) const;
1650    virtual     status_t    setSyncEvent(const sp<SyncEvent>& event);
1651    virtual     bool        isValidSyncEvent(const sp<SyncEvent>& event) const;
1652
1653    virtual     void        checkSilentMode_l() {}
1654    virtual     void        processVolume_l() {}
1655                void        checkInvalidTracks_l();
1656
1657    virtual     audio_stream_type_t streamType() { return AUDIO_STREAM_DEFAULT; }
1658
1659    virtual     void        invalidateTracks(audio_stream_type_t streamType __unused) {}
1660
1661                void        dump(int fd, const Vector<String16>& args);
1662    virtual     void        dumpInternals(int fd, const Vector<String16>& args);
1663                void        dumpTracks(int fd, const Vector<String16>& args);
1664
1665    virtual     bool        isOutput() const = 0;
1666
1667 protected:
1668
1669                audio_attributes_t      mAttr;
1670                audio_session_t         mSessionId;
1671                audio_port_handle_t     mPortId;
1672
1673                sp<MmapStreamCallback>  mCallback;
1674                sp<StreamHalInterface>  mHalStream;
1675                sp<DeviceHalInterface>  mHalDevice;
1676                AudioHwDevice* const    mAudioHwDev;
1677                ActiveTracks<MmapTrack> mActiveTracks;
1678};
1679
1680class MmapPlaybackThread : public MmapThread, public VolumeInterface
1681{
1682
1683public:
1684    MmapPlaybackThread(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1685                      AudioHwDevice *hwDev, AudioStreamOut *output,
1686                      audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady);
1687    virtual     ~MmapPlaybackThread() {}
1688
1689    virtual     void        configure(const audio_attributes_t *attr,
1690                                      audio_stream_type_t streamType,
1691                                      audio_session_t sessionId,
1692                                      const sp<MmapStreamCallback>& callback,
1693                                      audio_port_handle_t portId);
1694
1695                AudioStreamOut* clearOutput();
1696
1697                // VolumeInterface
1698    virtual     void        setMasterVolume(float value);
1699    virtual     void        setMasterMute(bool muted);
1700    virtual     void        setStreamVolume(audio_stream_type_t stream, float value);
1701    virtual     void        setStreamMute(audio_stream_type_t stream, bool muted);
1702    virtual     float       streamVolume(audio_stream_type_t stream) const;
1703
1704                void        setMasterMute_l(bool muted) { mMasterMute = muted; }
1705
1706    virtual     void        invalidateTracks(audio_stream_type_t streamType);
1707
1708    virtual     audio_stream_type_t streamType() { return mStreamType; }
1709    virtual     void        checkSilentMode_l();
1710    virtual     void        processVolume_l();
1711
1712    virtual     void        dumpInternals(int fd, const Vector<String16>& args);
1713
1714    virtual     bool        isOutput() const { return true; }
1715
1716protected:
1717
1718                audio_stream_type_t         mStreamType;
1719                float                       mMasterVolume;
1720                float                       mStreamVolume;
1721                bool                        mMasterMute;
1722                bool                        mStreamMute;
1723                float                       mHalVolFloat;
1724                AudioStreamOut*             mOutput;
1725};
1726
1727class MmapCaptureThread : public MmapThread
1728{
1729
1730public:
1731    MmapCaptureThread(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1732                      AudioHwDevice *hwDev, AudioStreamIn *input,
1733                      audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady);
1734    virtual     ~MmapCaptureThread() {}
1735
1736                AudioStreamIn* clearInput();
1737
1738    virtual     bool           isOutput() const { return false; }
1739
1740protected:
1741
1742                AudioStreamIn*  mInput;
1743};
1744