AudioFlinger.h revision 717e128691f083a9469a1d0e363ac6ecd5c65d58
1/*
2**
3** Copyright 2007, 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 ANDROID_AUDIO_FLINGER_H
19#define ANDROID_AUDIO_FLINGER_H
20
21#include <stdint.h>
22#include <sys/types.h>
23#include <limits.h>
24
25#include <common_time/cc_helper.h>
26
27#include <media/IAudioFlinger.h>
28#include <media/IAudioFlingerClient.h>
29#include <media/IAudioTrack.h>
30#include <media/IAudioRecord.h>
31#include <media/AudioSystem.h>
32#include <media/AudioTrack.h>
33
34#include <utils/Atomic.h>
35#include <utils/Errors.h>
36#include <utils/threads.h>
37#include <utils/SortedVector.h>
38#include <utils/TypeHelpers.h>
39#include <utils/Vector.h>
40
41#include <binder/BinderService.h>
42#include <binder/MemoryDealer.h>
43
44#include <system/audio.h>
45#include <hardware/audio.h>
46#include <hardware/audio_policy.h>
47
48#include "AudioBufferProvider.h"
49#include "ExtendedAudioBufferProvider.h"
50#include "FastMixer.h"
51#include "NBAIO.h"
52#include "AudioWatchdog.h"
53
54#include <powermanager/IPowerManager.h>
55
56namespace android {
57
58class audio_track_cblk_t;
59class effect_param_cblk_t;
60class AudioMixer;
61class AudioBuffer;
62class AudioResampler;
63class FastMixer;
64
65// ----------------------------------------------------------------------------
66
67// AudioFlinger has a hard-coded upper limit of 2 channels for capture and playback.
68// There is support for > 2 channel tracks down-mixed to 2 channel output via a down-mix effect.
69// Adding full support for > 2 channel capture or playback would require more than simply changing
70// this #define.  There is an independent hard-coded upper limit in AudioMixer;
71// removing that AudioMixer limit would be necessary but insufficient to support > 2 channels.
72// The macro FCC_2 highlights some (but not all) places where there is are 2-channel assumptions.
73// Search also for "2", "left", "right", "[0]", "[1]", ">> 16", "<< 16", etc.
74#define FCC_2 2     // FCC_2 = Fixed Channel Count 2
75
76static const nsecs_t kDefaultStandbyTimeInNsecs = seconds(3);
77
78class AudioFlinger :
79    public BinderService<AudioFlinger>,
80    public BnAudioFlinger
81{
82    friend class BinderService<AudioFlinger>;   // for AudioFlinger()
83public:
84    static const char* getServiceName() { return "media.audio_flinger"; }
85
86    virtual     status_t    dump(int fd, const Vector<String16>& args);
87
88    // IAudioFlinger interface, in binder opcode order
89    virtual sp<IAudioTrack> createTrack(
90                                pid_t pid,
91                                audio_stream_type_t streamType,
92                                uint32_t sampleRate,
93                                audio_format_t format,
94                                uint32_t channelMask,
95                                int frameCount,
96                                IAudioFlinger::track_flags_t flags,
97                                const sp<IMemory>& sharedBuffer,
98                                audio_io_handle_t output,
99                                pid_t tid,
100                                int *sessionId,
101                                status_t *status);
102
103    virtual sp<IAudioRecord> openRecord(
104                                pid_t pid,
105                                audio_io_handle_t input,
106                                uint32_t sampleRate,
107                                audio_format_t format,
108                                uint32_t channelMask,
109                                int frameCount,
110                                IAudioFlinger::track_flags_t flags,
111                                int *sessionId,
112                                status_t *status);
113
114    virtual     uint32_t    sampleRate(audio_io_handle_t output) const;
115    virtual     int         channelCount(audio_io_handle_t output) const;
116    virtual     audio_format_t format(audio_io_handle_t output) const;
117    virtual     size_t      frameCount(audio_io_handle_t output) const;
118    virtual     uint32_t    latency(audio_io_handle_t output) const;
119
120    virtual     status_t    setMasterVolume(float value);
121    virtual     status_t    setMasterMute(bool muted);
122
123    virtual     float       masterVolume() const;
124    virtual     float       masterVolumeSW() const;
125    virtual     bool        masterMute() const;
126
127    virtual     status_t    setStreamVolume(audio_stream_type_t stream, float value,
128                                            audio_io_handle_t output);
129    virtual     status_t    setStreamMute(audio_stream_type_t stream, bool muted);
130
131    virtual     float       streamVolume(audio_stream_type_t stream,
132                                         audio_io_handle_t output) const;
133    virtual     bool        streamMute(audio_stream_type_t stream) const;
134
135    virtual     status_t    setMode(audio_mode_t mode);
136
137    virtual     status_t    setMicMute(bool state);
138    virtual     bool        getMicMute() const;
139
140    virtual     status_t    setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs);
141    virtual     String8     getParameters(audio_io_handle_t ioHandle, const String8& keys) const;
142
143    virtual     void        registerClient(const sp<IAudioFlingerClient>& client);
144
145    virtual     size_t      getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const;
146
147    virtual audio_io_handle_t openOutput(audio_module_handle_t module,
148                                         audio_devices_t *pDevices,
149                                         uint32_t *pSamplingRate,
150                                         audio_format_t *pFormat,
151                                         audio_channel_mask_t *pChannelMask,
152                                         uint32_t *pLatencyMs,
153                                         audio_output_flags_t flags);
154
155    virtual audio_io_handle_t openDuplicateOutput(audio_io_handle_t output1,
156                                                  audio_io_handle_t output2);
157
158    virtual status_t closeOutput(audio_io_handle_t output);
159
160    virtual status_t suspendOutput(audio_io_handle_t output);
161
162    virtual status_t restoreOutput(audio_io_handle_t output);
163
164    virtual audio_io_handle_t openInput(audio_module_handle_t module,
165                                        audio_devices_t *pDevices,
166                                        uint32_t *pSamplingRate,
167                                        audio_format_t *pFormat,
168                                        audio_channel_mask_t *pChannelMask);
169
170    virtual status_t closeInput(audio_io_handle_t input);
171
172    virtual status_t setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output);
173
174    virtual status_t setVoiceVolume(float volume);
175
176    virtual status_t getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
177                                       audio_io_handle_t output) const;
178
179    virtual     unsigned int  getInputFramesLost(audio_io_handle_t ioHandle) const;
180
181    virtual int newAudioSessionId();
182
183    virtual void acquireAudioSessionId(int audioSession);
184
185    virtual void releaseAudioSessionId(int audioSession);
186
187    virtual status_t queryNumberEffects(uint32_t *numEffects) const;
188
189    virtual status_t queryEffect(uint32_t index, effect_descriptor_t *descriptor) const;
190
191    virtual status_t getEffectDescriptor(const effect_uuid_t *pUuid,
192                                         effect_descriptor_t *descriptor) const;
193
194    virtual sp<IEffect> createEffect(pid_t pid,
195                        effect_descriptor_t *pDesc,
196                        const sp<IEffectClient>& effectClient,
197                        int32_t priority,
198                        audio_io_handle_t io,
199                        int sessionId,
200                        status_t *status,
201                        int *id,
202                        int *enabled);
203
204    virtual status_t moveEffects(int sessionId, audio_io_handle_t srcOutput,
205                        audio_io_handle_t dstOutput);
206
207    virtual audio_module_handle_t loadHwModule(const char *name);
208
209    virtual     status_t    onTransact(
210                                uint32_t code,
211                                const Parcel& data,
212                                Parcel* reply,
213                                uint32_t flags);
214
215    // end of IAudioFlinger interface
216
217    class SyncEvent;
218
219    typedef void (*sync_event_callback_t)(const wp<SyncEvent>& event) ;
220
221    class SyncEvent : public RefBase {
222    public:
223        SyncEvent(AudioSystem::sync_event_t type,
224                  int triggerSession,
225                  int listenerSession,
226                  sync_event_callback_t callBack,
227                  void *cookie)
228        : mType(type), mTriggerSession(triggerSession), mListenerSession(listenerSession),
229          mCallback(callBack), mCookie(cookie)
230        {}
231
232        virtual ~SyncEvent() {}
233
234        void trigger() { Mutex::Autolock _l(mLock); if (mCallback) mCallback(this); }
235        bool isCancelled() { Mutex::Autolock _l(mLock); return (mCallback == NULL); }
236        void cancel() {Mutex::Autolock _l(mLock); mCallback = NULL; }
237        AudioSystem::sync_event_t type() const { return mType; }
238        int triggerSession() const { return mTriggerSession; }
239        int listenerSession() const { return mListenerSession; }
240        void *cookie() const { return mCookie; }
241
242    private:
243          const AudioSystem::sync_event_t mType;
244          const int mTriggerSession;
245          const int mListenerSession;
246          sync_event_callback_t mCallback;
247          void * const mCookie;
248          Mutex mLock;
249    };
250
251    sp<SyncEvent> createSyncEvent(AudioSystem::sync_event_t type,
252                                        int triggerSession,
253                                        int listenerSession,
254                                        sync_event_callback_t callBack,
255                                        void *cookie);
256
257private:
258               audio_mode_t getMode() const { return mMode; }
259
260                bool        btNrecIsOff() const { return mBtNrecIsOff; }
261
262                            AudioFlinger();
263    virtual                 ~AudioFlinger();
264
265    // call in any IAudioFlinger method that accesses mPrimaryHardwareDev
266    status_t                initCheck() const { return mPrimaryHardwareDev == NULL ? NO_INIT : NO_ERROR; }
267
268    // RefBase
269    virtual     void        onFirstRef();
270
271    audio_hw_device_t*      findSuitableHwDev_l(audio_module_handle_t module, uint32_t devices);
272    void                    purgeStaleEffects_l();
273
274    // standby delay for MIXER and DUPLICATING playback threads is read from property
275    // ro.audio.flinger_standbytime_ms or defaults to kDefaultStandbyTimeInNsecs
276    static nsecs_t          mStandbyTimeInNsecs;
277
278    // Internal dump utilites.
279    status_t dumpPermissionDenial(int fd, const Vector<String16>& args);
280    status_t dumpClients(int fd, const Vector<String16>& args);
281    status_t dumpInternals(int fd, const Vector<String16>& args);
282
283    // --- Client ---
284    class Client : public RefBase {
285    public:
286                            Client(const sp<AudioFlinger>& audioFlinger, pid_t pid);
287        virtual             ~Client();
288        sp<MemoryDealer>    heap() const;
289        pid_t               pid() const { return mPid; }
290        sp<AudioFlinger>    audioFlinger() const { return mAudioFlinger; }
291
292        bool reserveTimedTrack();
293        void releaseTimedTrack();
294
295    private:
296                            Client(const Client&);
297                            Client& operator = (const Client&);
298        const sp<AudioFlinger> mAudioFlinger;
299        const sp<MemoryDealer> mMemoryDealer;
300        const pid_t         mPid;
301
302        Mutex               mTimedTrackLock;
303        int                 mTimedTrackCount;
304    };
305
306    // --- Notification Client ---
307    class NotificationClient : public IBinder::DeathRecipient {
308    public:
309                            NotificationClient(const sp<AudioFlinger>& audioFlinger,
310                                                const sp<IAudioFlingerClient>& client,
311                                                pid_t pid);
312        virtual             ~NotificationClient();
313
314                sp<IAudioFlingerClient> audioFlingerClient() const { return mAudioFlingerClient; }
315
316                // IBinder::DeathRecipient
317                virtual     void        binderDied(const wp<IBinder>& who);
318
319    private:
320                            NotificationClient(const NotificationClient&);
321                            NotificationClient& operator = (const NotificationClient&);
322
323        const sp<AudioFlinger>  mAudioFlinger;
324        const pid_t             mPid;
325        const sp<IAudioFlingerClient> mAudioFlingerClient;
326    };
327
328    class TrackHandle;
329    class RecordHandle;
330    class RecordThread;
331    class PlaybackThread;
332    class MixerThread;
333    class DirectOutputThread;
334    class DuplicatingThread;
335    class Track;
336    class RecordTrack;
337    class EffectModule;
338    class EffectHandle;
339    class EffectChain;
340    struct AudioStreamOut;
341    struct AudioStreamIn;
342
343    class ThreadBase : public Thread {
344    public:
345
346        enum type_t {
347            MIXER,              // Thread class is MixerThread
348            DIRECT,             // Thread class is DirectOutputThread
349            DUPLICATING,        // Thread class is DuplicatingThread
350            RECORD              // Thread class is RecordThread
351        };
352
353        ThreadBase (const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id, uint32_t device, type_t type);
354        virtual             ~ThreadBase();
355
356        status_t dumpBase(int fd, const Vector<String16>& args);
357        status_t dumpEffectChains(int fd, const Vector<String16>& args);
358
359        void clearPowerManager();
360
361        // base for record and playback
362        class TrackBase : public ExtendedAudioBufferProvider, public RefBase {
363
364        public:
365            enum track_state {
366                IDLE,
367                TERMINATED,
368                FLUSHED,
369                STOPPED,
370                // next 2 states are currently used for fast tracks only
371                STOPPING_1,     // waiting for first underrun
372                STOPPING_2,     // waiting for presentation complete
373                RESUMING,
374                ACTIVE,
375                PAUSING,
376                PAUSED
377            };
378
379                                TrackBase(ThreadBase *thread,
380                                        const sp<Client>& client,
381                                        uint32_t sampleRate,
382                                        audio_format_t format,
383                                        uint32_t channelMask,
384                                        int frameCount,
385                                        const sp<IMemory>& sharedBuffer,
386                                        int sessionId);
387            virtual             ~TrackBase();
388
389            virtual status_t    start(AudioSystem::sync_event_t event = AudioSystem::SYNC_EVENT_NONE,
390                                     int triggerSession = 0) = 0;
391            virtual void        stop() = 0;
392                    sp<IMemory> getCblk() const { return mCblkMemory; }
393                    audio_track_cblk_t* cblk() const { return mCblk; }
394                    int         sessionId() const { return mSessionId; }
395            virtual status_t    setSyncEvent(const sp<SyncEvent>& event);
396
397        protected:
398                                TrackBase(const TrackBase&);
399                                TrackBase& operator = (const TrackBase&);
400
401            // AudioBufferProvider interface
402            virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts) = 0;
403            virtual void releaseBuffer(AudioBufferProvider::Buffer* buffer);
404
405            // ExtendedAudioBufferProvider interface is only needed for Track,
406            // but putting it in TrackBase avoids the complexity of virtual inheritance
407            virtual size_t  framesReady() const { return SIZE_MAX; }
408
409            audio_format_t format() const {
410                return mFormat;
411            }
412
413            int channelCount() const { return mChannelCount; }
414
415            uint32_t channelMask() const { return mChannelMask; }
416
417            int sampleRate() const; // FIXME inline after cblk sr moved
418
419            void* getBuffer(uint32_t offset, uint32_t frames) const;
420
421            bool isStopped() const {
422                return (mState == STOPPED || mState == FLUSHED);
423            }
424
425            // for fast tracks only
426            bool isStopping() const {
427                return mState == STOPPING_1 || mState == STOPPING_2;
428            }
429            bool isStopping_1() const {
430                return mState == STOPPING_1;
431            }
432            bool isStopping_2() const {
433                return mState == STOPPING_2;
434            }
435
436            bool isTerminated() const {
437                return mState == TERMINATED;
438            }
439
440            bool step();
441            void reset();
442
443            const wp<ThreadBase> mThread;
444            /*const*/ sp<Client> mClient;   // see explanation at ~TrackBase() why not const
445            sp<IMemory>         mCblkMemory;
446            audio_track_cblk_t* mCblk;
447            void*               mBuffer;
448            void*               mBufferEnd;
449            uint32_t            mFrameCount;
450            // we don't really need a lock for these
451            track_state         mState;
452            const uint32_t      mSampleRate;    // initial sample rate only; for tracks which
453                                // support dynamic rates, the current value is in control block
454            const audio_format_t mFormat;
455            bool                mStepServerFailed;
456            const int           mSessionId;
457            uint8_t             mChannelCount;
458            uint32_t            mChannelMask;
459            Vector < sp<SyncEvent> >mSyncEvents;
460        };
461
462        class ConfigEvent {
463        public:
464            ConfigEvent() : mEvent(0), mParam(0) {}
465
466            int mEvent;
467            int mParam;
468        };
469
470        class PMDeathRecipient : public IBinder::DeathRecipient {
471        public:
472                        PMDeathRecipient(const wp<ThreadBase>& thread) : mThread(thread) {}
473            virtual     ~PMDeathRecipient() {}
474
475            // IBinder::DeathRecipient
476            virtual     void        binderDied(const wp<IBinder>& who);
477
478        private:
479                        PMDeathRecipient(const PMDeathRecipient&);
480                        PMDeathRecipient& operator = (const PMDeathRecipient&);
481
482            wp<ThreadBase> mThread;
483        };
484
485        virtual     status_t    initCheck() const = 0;
486                    type_t      type() const { return mType; }
487                    uint32_t    sampleRate() const { return mSampleRate; }
488                    int         channelCount() const { return mChannelCount; }
489                    audio_format_t format() const { return mFormat; }
490                    // Called by AudioFlinger::frameCount(audio_io_handle_t output) and effects,
491                    // and returns the normal mix buffer's frame count.  No API for HAL frame count.
492                    size_t      frameCount() const { return mNormalFrameCount; }
493                    void        wakeUp()    { mWaitWorkCV.broadcast(); }
494        // Should be "virtual status_t requestExitAndWait()" and override same
495        // method in Thread, but Thread::requestExitAndWait() is not yet virtual.
496                    void        exit();
497        virtual     bool        checkForNewParameters_l() = 0;
498        virtual     status_t    setParameters(const String8& keyValuePairs);
499        virtual     String8     getParameters(const String8& keys) = 0;
500        virtual     void        audioConfigChanged_l(int event, int param = 0) = 0;
501                    void        sendConfigEvent(int event, int param = 0);
502                    void        sendConfigEvent_l(int event, int param = 0);
503                    void        processConfigEvents();
504                    audio_io_handle_t id() const { return mId;}
505                    bool        standby() const { return mStandby; }
506                    uint32_t    device() const { return mDevice; }
507        virtual     audio_stream_t* stream() const = 0;
508
509                    sp<EffectHandle> createEffect_l(
510                                        const sp<AudioFlinger::Client>& client,
511                                        const sp<IEffectClient>& effectClient,
512                                        int32_t priority,
513                                        int sessionId,
514                                        effect_descriptor_t *desc,
515                                        int *enabled,
516                                        status_t *status);
517                    void disconnectEffect(const sp< EffectModule>& effect,
518                                          const wp<EffectHandle>& handle,
519                                          bool unpinIfLast);
520
521                    // return values for hasAudioSession (bit field)
522                    enum effect_state {
523                        EFFECT_SESSION = 0x1,   // the audio session corresponds to at least one
524                                                // effect
525                        TRACK_SESSION = 0x2     // the audio session corresponds to at least one
526                                                // track
527                    };
528
529                    // get effect chain corresponding to session Id.
530                    sp<EffectChain> getEffectChain(int sessionId);
531                    // same as getEffectChain() but must be called with ThreadBase mutex locked
532                    sp<EffectChain> getEffectChain_l(int sessionId);
533                    // add an effect chain to the chain list (mEffectChains)
534        virtual     status_t addEffectChain_l(const sp<EffectChain>& chain) = 0;
535                    // remove an effect chain from the chain list (mEffectChains)
536        virtual     size_t removeEffectChain_l(const sp<EffectChain>& chain) = 0;
537                    // lock all effect chains Mutexes. Must be called before releasing the
538                    // ThreadBase mutex before processing the mixer and effects. This guarantees the
539                    // integrity of the chains during the process.
540                    // Also sets the parameter 'effectChains' to current value of mEffectChains.
541                    void lockEffectChains_l(Vector< sp<EffectChain> >& effectChains);
542                    // unlock effect chains after process
543                    void unlockEffectChains(const Vector< sp<EffectChain> >& effectChains);
544                    // set audio mode to all effect chains
545                    void setMode(audio_mode_t mode);
546                    // get effect module with corresponding ID on specified audio session
547                    sp<AudioFlinger::EffectModule> getEffect(int sessionId, int effectId);
548                    sp<AudioFlinger::EffectModule> getEffect_l(int sessionId, int effectId);
549                    // add and effect module. Also creates the effect chain is none exists for
550                    // the effects audio session
551                    status_t addEffect_l(const sp< EffectModule>& effect);
552                    // remove and effect module. Also removes the effect chain is this was the last
553                    // effect
554                    void removeEffect_l(const sp< EffectModule>& effect);
555                    // detach all tracks connected to an auxiliary effect
556        virtual     void detachAuxEffect_l(int effectId) {}
557                    // returns either EFFECT_SESSION if effects on this audio session exist in one
558                    // chain, or TRACK_SESSION if tracks on this audio session exist, or both
559                    virtual uint32_t hasAudioSession(int sessionId) = 0;
560                    // the value returned by default implementation is not important as the
561                    // strategy is only meaningful for PlaybackThread which implements this method
562                    virtual uint32_t getStrategyForSession_l(int sessionId) { return 0; }
563
564                    // suspend or restore effect according to the type of effect passed. a NULL
565                    // type pointer means suspend all effects in the session
566                    void setEffectSuspended(const effect_uuid_t *type,
567                                            bool suspend,
568                                            int sessionId = AUDIO_SESSION_OUTPUT_MIX);
569                    // check if some effects must be suspended/restored when an effect is enabled
570                    // or disabled
571                    void checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
572                                                     bool enabled,
573                                                     int sessionId = AUDIO_SESSION_OUTPUT_MIX);
574                    void checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
575                                                       bool enabled,
576                                                       int sessionId = AUDIO_SESSION_OUTPUT_MIX);
577
578                    virtual status_t    setSyncEvent(const sp<SyncEvent>& event) = 0;
579                    virtual bool        isValidSyncEvent(const sp<SyncEvent>& event) = 0;
580
581
582        mutable     Mutex                   mLock;
583
584    protected:
585
586                    // entry describing an effect being suspended in mSuspendedSessions keyed vector
587                    class SuspendedSessionDesc : public RefBase {
588                    public:
589                        SuspendedSessionDesc() : mRefCount(0) {}
590
591                        int mRefCount;          // number of active suspend requests
592                        effect_uuid_t mType;    // effect type UUID
593                    };
594
595                    void        acquireWakeLock();
596                    void        acquireWakeLock_l();
597                    void        releaseWakeLock();
598                    void        releaseWakeLock_l();
599                    void setEffectSuspended_l(const effect_uuid_t *type,
600                                              bool suspend,
601                                              int sessionId = AUDIO_SESSION_OUTPUT_MIX);
602                    // updated mSuspendedSessions when an effect suspended or restored
603                    void        updateSuspendedSessions_l(const effect_uuid_t *type,
604                                                          bool suspend,
605                                                          int sessionId);
606                    // check if some effects must be suspended when an effect chain is added
607                    void checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain);
608
609        friend class AudioFlinger;      // for mEffectChains
610
611                    const type_t            mType;
612
613                    // Used by parameters, config events, addTrack_l, exit
614                    Condition               mWaitWorkCV;
615
616                    const sp<AudioFlinger>  mAudioFlinger;
617                    uint32_t                mSampleRate;
618                    size_t                  mFrameCount;       // output HAL, direct output, record
619                    size_t                  mNormalFrameCount; // normal mixer and effects
620                    uint32_t                mChannelMask;
621                    uint16_t                mChannelCount;
622                    size_t                  mFrameSize;
623                    audio_format_t          mFormat;
624
625                    // Parameter sequence by client: binder thread calling setParameters():
626                    //  1. Lock mLock
627                    //  2. Append to mNewParameters
628                    //  3. mWaitWorkCV.signal
629                    //  4. mParamCond.waitRelative with timeout
630                    //  5. read mParamStatus
631                    //  6. mWaitWorkCV.signal
632                    //  7. Unlock
633                    //
634                    // Parameter sequence by server: threadLoop calling checkForNewParameters_l():
635                    // 1. Lock mLock
636                    // 2. If there is an entry in mNewParameters proceed ...
637                    // 2. Read first entry in mNewParameters
638                    // 3. Process
639                    // 4. Remove first entry from mNewParameters
640                    // 5. Set mParamStatus
641                    // 6. mParamCond.signal
642                    // 7. mWaitWorkCV.wait with timeout (this is to avoid overwriting mParamStatus)
643                    // 8. Unlock
644                    Condition               mParamCond;
645                    Vector<String8>         mNewParameters;
646                    status_t                mParamStatus;
647
648                    Vector<ConfigEvent>     mConfigEvents;
649                    bool                    mStandby;
650                    const audio_io_handle_t mId;
651                    Vector< sp<EffectChain> > mEffectChains;
652                    uint32_t                mDevice;    // output device for PlaybackThread
653                                                        // input + output devices for RecordThread
654                    static const int        kNameLength = 16;   // prctl(PR_SET_NAME) limit
655                    char                    mName[kNameLength];
656                    sp<IPowerManager>       mPowerManager;
657                    sp<IBinder>             mWakeLockToken;
658                    const sp<PMDeathRecipient> mDeathRecipient;
659                    // list of suspended effects per session and per type. The first vector is
660                    // keyed by session ID, the second by type UUID timeLow field
661                    KeyedVector< int, KeyedVector< int, sp<SuspendedSessionDesc> > >  mSuspendedSessions;
662    };
663
664    struct  stream_type_t {
665        stream_type_t()
666            :   volume(1.0f),
667                mute(false)
668        {
669        }
670        float       volume;
671        bool        mute;
672    };
673
674    // --- PlaybackThread ---
675    class PlaybackThread : public ThreadBase {
676    public:
677
678        enum mixer_state {
679            MIXER_IDLE,             // no active tracks
680            MIXER_TRACKS_ENABLED,   // at least one active track, but no track has any data ready
681            MIXER_TRACKS_READY      // at least one active track, and at least one track has data
682            // standby mode does not have an enum value
683            // suspend by audio policy manager is orthogonal to mixer state
684        };
685
686        // playback track
687        class Track : public TrackBase, public VolumeProvider {
688        public:
689                                Track(  PlaybackThread *thread,
690                                        const sp<Client>& client,
691                                        audio_stream_type_t streamType,
692                                        uint32_t sampleRate,
693                                        audio_format_t format,
694                                        uint32_t channelMask,
695                                        int frameCount,
696                                        const sp<IMemory>& sharedBuffer,
697                                        int sessionId,
698                                        IAudioFlinger::track_flags_t flags);
699            virtual             ~Track();
700
701            static  void        appendDumpHeader(String8& result);
702                    void        dump(char* buffer, size_t size);
703            virtual status_t    start(AudioSystem::sync_event_t event = AudioSystem::SYNC_EVENT_NONE,
704                                     int triggerSession = 0);
705            virtual void        stop();
706                    void        pause();
707
708                    void        flush();
709                    void        destroy();
710                    void        mute(bool);
711                    int name() const {
712                        return mName;
713                    }
714
715                    audio_stream_type_t streamType() const {
716                        return mStreamType;
717                    }
718                    status_t    attachAuxEffect(int EffectId);
719                    void        setAuxBuffer(int EffectId, int32_t *buffer);
720                    int32_t     *auxBuffer() const { return mAuxBuffer; }
721                    void        setMainBuffer(int16_t *buffer) { mMainBuffer = buffer; }
722                    int16_t     *mainBuffer() const { return mMainBuffer; }
723                    int         auxEffectId() const { return mAuxEffectId; }
724
725        // implement FastMixerState::VolumeProvider interface
726            virtual uint32_t    getVolumeLR();
727            virtual status_t    setSyncEvent(const sp<SyncEvent>& event);
728
729        protected:
730            // for numerous
731            friend class PlaybackThread;
732            friend class MixerThread;
733            friend class DirectOutputThread;
734
735                                Track(const Track&);
736                                Track& operator = (const Track&);
737
738            // AudioBufferProvider interface
739            virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts = kInvalidPTS);
740            // releaseBuffer() not overridden
741
742            virtual size_t framesReady() const;
743
744            bool isMuted() const { return mMute; }
745            bool isPausing() const {
746                return mState == PAUSING;
747            }
748            bool isPaused() const {
749                return mState == PAUSED;
750            }
751            bool isResuming() const {
752                return mState == RESUMING;
753            }
754            bool isReady() const;
755            void setPaused() { mState = PAUSED; }
756            void reset();
757
758            bool isOutputTrack() const {
759                return (mStreamType == AUDIO_STREAM_CNT);
760            }
761
762            sp<IMemory> sharedBuffer() const { return mSharedBuffer; }
763
764            bool presentationComplete(size_t framesWritten, size_t audioHalFrames);
765
766        public:
767            void triggerEvents(AudioSystem::sync_event_t type);
768            virtual bool isTimedTrack() const { return false; }
769            bool isFastTrack() const { return (mFlags & IAudioFlinger::TRACK_FAST) != 0; }
770        protected:
771
772            // we don't really need a lock for these
773            volatile bool       mMute;
774            // FILLED state is used for suppressing volume ramp at begin of playing
775            enum {FS_INVALID, FS_FILLING, FS_FILLED, FS_ACTIVE};
776            mutable uint8_t     mFillingUpStatus;
777            int8_t              mRetryCount;
778            const sp<IMemory>   mSharedBuffer;
779            bool                mResetDone;
780            const audio_stream_type_t mStreamType;
781            int                 mName;      // track name on the normal mixer,
782                                            // allocated statically at track creation time,
783                                            // and is even allocated (though unused) for fast tracks
784                                            // FIXME don't allocate track name for fast tracks
785            int16_t             *mMainBuffer;
786            int32_t             *mAuxBuffer;
787            int                 mAuxEffectId;
788            bool                mHasVolumeController;
789            size_t              mPresentationCompleteFrames; // number of frames written to the audio HAL
790                                                       // when this track will be fully rendered
791        private:
792            IAudioFlinger::track_flags_t mFlags;
793
794            // The following fields are only for fast tracks, and should be in a subclass
795            int                 mFastIndex; // index within FastMixerState::mFastTracks[];
796                                            // either mFastIndex == -1 if not isFastTrack()
797                                            // or 0 < mFastIndex < FastMixerState::kMaxFast because
798                                            // index 0 is reserved for normal mixer's submix;
799                                            // index is allocated statically at track creation time
800                                            // but the slot is only used if track is active
801            FastTrackUnderruns  mObservedUnderruns; // Most recently observed value of
802                                            // mFastMixerDumpState.mTracks[mFastIndex].mUnderruns
803            uint32_t            mUnderrunCount; // Counter of total number of underruns, never reset
804            volatile float      mCachedVolume;  // combined master volume and stream type volume;
805                                                // 'volatile' means accessed without lock or
806                                                // barrier, but is read/written atomically
807        };  // end of Track
808
809        class TimedTrack : public Track {
810          public:
811            static sp<TimedTrack> create(PlaybackThread *thread,
812                                         const sp<Client>& client,
813                                         audio_stream_type_t streamType,
814                                         uint32_t sampleRate,
815                                         audio_format_t format,
816                                         uint32_t channelMask,
817                                         int frameCount,
818                                         const sp<IMemory>& sharedBuffer,
819                                         int sessionId);
820            ~TimedTrack();
821
822            class TimedBuffer {
823              public:
824                TimedBuffer();
825                TimedBuffer(const sp<IMemory>& buffer, int64_t pts);
826                const sp<IMemory>& buffer() const { return mBuffer; }
827                int64_t pts() const { return mPTS; }
828                uint32_t position() const { return mPosition; }
829                void setPosition(uint32_t pos) { mPosition = pos; }
830              private:
831                sp<IMemory> mBuffer;
832                int64_t     mPTS;
833                uint32_t    mPosition;
834            };
835
836            // Mixer facing methods.
837            virtual bool isTimedTrack() const { return true; }
838            virtual size_t framesReady() const;
839
840            // AudioBufferProvider interface
841            virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer,
842                                           int64_t pts);
843            virtual void releaseBuffer(AudioBufferProvider::Buffer* buffer);
844
845            // Client/App facing methods.
846            status_t    allocateTimedBuffer(size_t size,
847                                            sp<IMemory>* buffer);
848            status_t    queueTimedBuffer(const sp<IMemory>& buffer,
849                                         int64_t pts);
850            status_t    setMediaTimeTransform(const LinearTransform& xform,
851                                              TimedAudioTrack::TargetTimeline target);
852
853          private:
854            TimedTrack(PlaybackThread *thread,
855                       const sp<Client>& client,
856                       audio_stream_type_t streamType,
857                       uint32_t sampleRate,
858                       audio_format_t format,
859                       uint32_t channelMask,
860                       int frameCount,
861                       const sp<IMemory>& sharedBuffer,
862                       int sessionId);
863
864            void timedYieldSamples_l(AudioBufferProvider::Buffer* buffer);
865            void timedYieldSilence_l(uint32_t numFrames,
866                                     AudioBufferProvider::Buffer* buffer);
867            void trimTimedBufferQueue_l();
868            void trimTimedBufferQueueHead_l(const char* logTag);
869            void updateFramesPendingAfterTrim_l(const TimedBuffer& buf,
870                                                const char* logTag);
871
872            uint64_t            mLocalTimeFreq;
873            LinearTransform     mLocalTimeToSampleTransform;
874            LinearTransform     mMediaTimeToSampleTransform;
875            sp<MemoryDealer>    mTimedMemoryDealer;
876
877            Vector<TimedBuffer> mTimedBufferQueue;
878            bool                mQueueHeadInFlight;
879            bool                mTrimQueueHeadOnRelease;
880            uint32_t            mFramesPendingInQueue;
881
882            uint8_t*            mTimedSilenceBuffer;
883            uint32_t            mTimedSilenceBufferSize;
884            mutable Mutex       mTimedBufferQueueLock;
885            bool                mTimedAudioOutputOnTime;
886            CCHelper            mCCHelper;
887
888            Mutex               mMediaTimeTransformLock;
889            LinearTransform     mMediaTimeTransform;
890            bool                mMediaTimeTransformValid;
891            TimedAudioTrack::TargetTimeline mMediaTimeTransformTarget;
892        };
893
894
895        // playback track
896        class OutputTrack : public Track {
897        public:
898
899            class Buffer: public AudioBufferProvider::Buffer {
900            public:
901                int16_t *mBuffer;
902            };
903
904                                OutputTrack(PlaybackThread *thread,
905                                        DuplicatingThread *sourceThread,
906                                        uint32_t sampleRate,
907                                        audio_format_t format,
908                                        uint32_t channelMask,
909                                        int frameCount);
910            virtual             ~OutputTrack();
911
912            virtual status_t    start(AudioSystem::sync_event_t event = AudioSystem::SYNC_EVENT_NONE,
913                                     int triggerSession = 0);
914            virtual void        stop();
915                    bool        write(int16_t* data, uint32_t frames);
916                    bool        bufferQueueEmpty() const { return mBufferQueue.size() == 0; }
917                    bool        isActive() const { return mActive; }
918            const wp<ThreadBase>& thread() const { return mThread; }
919
920        private:
921
922            enum {
923                NO_MORE_BUFFERS = 0x80000001,   // same in AudioTrack.h, ok to be different value
924            };
925
926            status_t            obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs);
927            void                clearBufferQueue();
928
929            // Maximum number of pending buffers allocated by OutputTrack::write()
930            static const uint8_t kMaxOverFlowBuffers = 10;
931
932            Vector < Buffer* >          mBufferQueue;
933            AudioBufferProvider::Buffer mOutBuffer;
934            bool                        mActive;
935            DuplicatingThread* const mSourceThread; // for waitTimeMs() in write()
936        };  // end of OutputTrack
937
938        PlaybackThread (const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
939                        audio_io_handle_t id, uint32_t device, type_t type);
940        virtual             ~PlaybackThread();
941
942                    status_t    dump(int fd, const Vector<String16>& args);
943
944        // Thread virtuals
945        virtual     status_t    readyToRun();
946        virtual     bool        threadLoop();
947
948        // RefBase
949        virtual     void        onFirstRef();
950
951protected:
952        // Code snippets that were lifted up out of threadLoop()
953        virtual     void        threadLoop_mix() = 0;
954        virtual     void        threadLoop_sleepTime() = 0;
955        virtual     void        threadLoop_write();
956        virtual     void        threadLoop_standby();
957        virtual     void        threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
958
959                    // prepareTracks_l reads and writes mActiveTracks, and returns
960                    // the pending set of tracks to remove via Vector 'tracksToRemove'.  The caller
961                    // is responsible for clearing or destroying this Vector later on, when it
962                    // is safe to do so. That will drop the final ref count and destroy the tracks.
963        virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove) = 0;
964
965public:
966
967        virtual     status_t    initCheck() const { return (mOutput == NULL) ? NO_INIT : NO_ERROR; }
968
969                    // return estimated latency in milliseconds, as reported by HAL
970                    uint32_t    latency() const;
971                    // same, but lock must already be held
972                    uint32_t    latency_l() const;
973
974                    void        setMasterVolume(float value);
975                    void        setMasterMute(bool muted);
976
977                    void        setStreamVolume(audio_stream_type_t stream, float value);
978                    void        setStreamMute(audio_stream_type_t stream, bool muted);
979
980                    float       streamVolume(audio_stream_type_t stream) const;
981
982                    sp<Track>   createTrack_l(
983                                    const sp<AudioFlinger::Client>& client,
984                                    audio_stream_type_t streamType,
985                                    uint32_t sampleRate,
986                                    audio_format_t format,
987                                    uint32_t channelMask,
988                                    int frameCount,
989                                    const sp<IMemory>& sharedBuffer,
990                                    int sessionId,
991                                    IAudioFlinger::track_flags_t flags,
992                                    pid_t tid,
993                                    status_t *status);
994
995                    AudioStreamOut* getOutput() const;
996                    AudioStreamOut* clearOutput();
997                    virtual audio_stream_t* stream() const;
998
999                    void        suspend() { mSuspended++; }
1000                    void        restore() { if (mSuspended > 0) mSuspended--; }
1001                    bool        isSuspended() const { return (mSuspended > 0); }
1002        virtual     String8     getParameters(const String8& keys);
1003        virtual     void        audioConfigChanged_l(int event, int param = 0);
1004                    status_t    getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames);
1005                    int16_t     *mixBuffer() const { return mMixBuffer; };
1006
1007        virtual     void detachAuxEffect_l(int effectId);
1008                    status_t attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track> track,
1009                            int EffectId);
1010                    status_t attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track> track,
1011                            int EffectId);
1012
1013                    virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
1014                    virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
1015                    virtual uint32_t hasAudioSession(int sessionId);
1016                    virtual uint32_t getStrategyForSession_l(int sessionId);
1017
1018
1019                    virtual status_t setSyncEvent(const sp<SyncEvent>& event);
1020                    virtual bool     isValidSyncEvent(const sp<SyncEvent>& event);
1021
1022    protected:
1023        int16_t*                        mMixBuffer;
1024        uint32_t                        mSuspended;     // suspend count, > 0 means suspended
1025        int                             mBytesWritten;
1026    private:
1027        // mMasterMute is in both PlaybackThread and in AudioFlinger.  When a
1028        // PlaybackThread needs to find out if master-muted, it checks it's local
1029        // copy rather than the one in AudioFlinger.  This optimization saves a lock.
1030        bool                            mMasterMute;
1031                    void        setMasterMute_l(bool muted) { mMasterMute = muted; }
1032    protected:
1033        SortedVector< wp<Track> >       mActiveTracks;  // FIXME check if this could be sp<>
1034
1035        // Allocate a track name for a given channel mask.
1036        //   Returns name >= 0 if successful, -1 on failure.
1037        virtual int             getTrackName_l(audio_channel_mask_t channelMask) = 0;
1038        virtual void            deleteTrackName_l(int name) = 0;
1039
1040        // Time to sleep between cycles when:
1041        virtual uint32_t        activeSleepTimeUs() const;      // mixer state MIXER_TRACKS_ENABLED
1042        virtual uint32_t        idleSleepTimeUs() const = 0;    // mixer state MIXER_IDLE
1043        virtual uint32_t        suspendSleepTimeUs() const = 0; // audio policy manager suspended us
1044        // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write()
1045        // No sleep in standby mode; waits on a condition
1046
1047        // Code snippets that are temporarily lifted up out of threadLoop() until the merge
1048                    void        checkSilentMode_l();
1049
1050        // Non-trivial for DUPLICATING only
1051        virtual     void        saveOutputTracks() { }
1052        virtual     void        clearOutputTracks() { }
1053
1054        // Cache various calculated values, at threadLoop() entry and after a parameter change
1055        virtual     void        cacheParameters_l();
1056
1057        virtual     uint32_t    correctLatency(uint32_t latency) const;
1058
1059    private:
1060
1061        friend class AudioFlinger;      // for numerous
1062
1063        PlaybackThread(const Client&);
1064        PlaybackThread& operator = (const PlaybackThread&);
1065
1066        status_t    addTrack_l(const sp<Track>& track);
1067        void        destroyTrack_l(const sp<Track>& track);
1068        void        removeTrack_l(const sp<Track>& track);
1069
1070        void        readOutputParameters();
1071
1072        virtual status_t    dumpInternals(int fd, const Vector<String16>& args);
1073        status_t    dumpTracks(int fd, const Vector<String16>& args);
1074
1075        SortedVector< sp<Track> >       mTracks;
1076        // mStreamTypes[] uses 1 additional stream type internally for the OutputTrack used by DuplicatingThread
1077        stream_type_t                   mStreamTypes[AUDIO_STREAM_CNT + 1];
1078        AudioStreamOut                  *mOutput;
1079        float                           mMasterVolume;
1080        nsecs_t                         mLastWriteTime;
1081        int                             mNumWrites;
1082        int                             mNumDelayedWrites;
1083        bool                            mInWrite;
1084
1085        // FIXME rename these former local variables of threadLoop to standard "m" names
1086        nsecs_t                         standbyTime;
1087        size_t                          mixBufferSize;
1088
1089        // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l()
1090        uint32_t                        activeSleepTime;
1091        uint32_t                        idleSleepTime;
1092
1093        uint32_t                        sleepTime;
1094
1095        // mixer status returned by prepareTracks_l()
1096        mixer_state                     mMixerStatus; // current cycle
1097                                                      // previous cycle when in prepareTracks_l()
1098        mixer_state                     mMixerStatusIgnoringFastTracks;
1099                                                      // FIXME or a separate ready state per track
1100
1101        // FIXME move these declarations into the specific sub-class that needs them
1102        // MIXER only
1103        bool                            longStandbyExit;
1104        uint32_t                        sleepTimeShift;
1105
1106        // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value
1107        nsecs_t                         standbyDelay;
1108
1109        // MIXER only
1110        nsecs_t                         maxPeriod;
1111
1112        // DUPLICATING only
1113        uint32_t                        writeFrames;
1114
1115    private:
1116        // The HAL output sink is treated as non-blocking, but current implementation is blocking
1117        sp<NBAIO_Sink>          mOutputSink;
1118        // If a fast mixer is present, the blocking pipe sink, otherwise clear
1119        sp<NBAIO_Sink>          mPipeSink;
1120        // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink
1121        sp<NBAIO_Sink>          mNormalSink;
1122        // For dumpsys
1123        sp<NBAIO_Sink>          mTeeSink;
1124        sp<NBAIO_Source>        mTeeSource;
1125        uint32_t                mScreenState;   // cached copy of gScreenState
1126    public:
1127        virtual     bool        hasFastMixer() const = 0;
1128        virtual     FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const
1129                                    { FastTrackUnderruns dummy; return dummy; }
1130
1131    protected:
1132                    // accessed by both binder threads and within threadLoop(), lock on mutex needed
1133                    unsigned    mFastTrackAvailMask;    // bit i set if fast track [i] is available
1134
1135    };
1136
1137    class MixerThread : public PlaybackThread {
1138    public:
1139        MixerThread (const sp<AudioFlinger>& audioFlinger,
1140                     AudioStreamOut* output,
1141                     audio_io_handle_t id,
1142                     uint32_t device,
1143                     type_t type = MIXER);
1144        virtual             ~MixerThread();
1145
1146        // Thread virtuals
1147
1148                    void        invalidateTracks(audio_stream_type_t streamType);
1149        virtual     bool        checkForNewParameters_l();
1150        virtual     status_t    dumpInternals(int fd, const Vector<String16>& args);
1151
1152    protected:
1153        virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
1154        virtual     int         getTrackName_l(audio_channel_mask_t channelMask);
1155        virtual     void        deleteTrackName_l(int name);
1156        virtual     uint32_t    idleSleepTimeUs() const;
1157        virtual     uint32_t    suspendSleepTimeUs() const;
1158        virtual     void        cacheParameters_l();
1159
1160        // threadLoop snippets
1161        virtual     void        threadLoop_write();
1162        virtual     void        threadLoop_standby();
1163        virtual     void        threadLoop_mix();
1164        virtual     void        threadLoop_sleepTime();
1165        virtual     void        threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
1166        virtual     uint32_t    correctLatency(uint32_t latency) const;
1167
1168                    AudioMixer* mAudioMixer;    // normal mixer
1169    private:
1170#ifdef SOAKER
1171                    Thread*     mSoaker;
1172#endif
1173                    // one-time initialization, no locks required
1174                    FastMixer*  mFastMixer;         // non-NULL if there is also a fast mixer
1175                    sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread
1176
1177                    // contents are not guaranteed to be consistent, no locks required
1178                    FastMixerDumpState mFastMixerDumpState;
1179#ifdef STATE_QUEUE_DUMP
1180                    StateQueueObserverDump mStateQueueObserverDump;
1181                    StateQueueMutatorDump  mStateQueueMutatorDump;
1182#endif
1183                    AudioWatchdogDump mAudioWatchdogDump;
1184
1185                    // accessible only within the threadLoop(), no locks required
1186                    //          mFastMixer->sq()    // for mutating and pushing state
1187                    int32_t     mFastMixerFutex;    // for cold idle
1188
1189    public:
1190        virtual     bool        hasFastMixer() const { return mFastMixer != NULL; }
1191        virtual     FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const {
1192                                  ALOG_ASSERT(fastIndex < FastMixerState::kMaxFastTracks);
1193                                  return mFastMixerDumpState.mTracks[fastIndex].mUnderruns;
1194                                }
1195    };
1196
1197    class DirectOutputThread : public PlaybackThread {
1198    public:
1199
1200        DirectOutputThread (const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
1201                            audio_io_handle_t id, uint32_t device);
1202        virtual                 ~DirectOutputThread();
1203
1204        // Thread virtuals
1205
1206        virtual     bool        checkForNewParameters_l();
1207
1208    protected:
1209        virtual     int         getTrackName_l(audio_channel_mask_t channelMask);
1210        virtual     void        deleteTrackName_l(int name);
1211        virtual     uint32_t    activeSleepTimeUs() const;
1212        virtual     uint32_t    idleSleepTimeUs() const;
1213        virtual     uint32_t    suspendSleepTimeUs() const;
1214        virtual     void        cacheParameters_l();
1215
1216        // threadLoop snippets
1217        virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
1218        virtual     void        threadLoop_mix();
1219        virtual     void        threadLoop_sleepTime();
1220
1221        // volumes last sent to audio HAL with stream->set_volume()
1222        float mLeftVolFloat;
1223        float mRightVolFloat;
1224
1225private:
1226        // prepareTracks_l() tells threadLoop_mix() the name of the single active track
1227        sp<Track>               mActiveTrack;
1228    public:
1229        virtual     bool        hasFastMixer() const { return false; }
1230    };
1231
1232    class DuplicatingThread : public MixerThread {
1233    public:
1234        DuplicatingThread (const sp<AudioFlinger>& audioFlinger, MixerThread* mainThread,
1235                           audio_io_handle_t id);
1236        virtual                 ~DuplicatingThread();
1237
1238        // Thread virtuals
1239                    void        addOutputTrack(MixerThread* thread);
1240                    void        removeOutputTrack(MixerThread* thread);
1241                    uint32_t    waitTimeMs() const { return mWaitTimeMs; }
1242    protected:
1243        virtual     uint32_t    activeSleepTimeUs() const;
1244
1245    private:
1246                    bool        outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks);
1247    protected:
1248        // threadLoop snippets
1249        virtual     void        threadLoop_mix();
1250        virtual     void        threadLoop_sleepTime();
1251        virtual     void        threadLoop_write();
1252        virtual     void        threadLoop_standby();
1253        virtual     void        cacheParameters_l();
1254
1255    private:
1256        // called from threadLoop, addOutputTrack, removeOutputTrack
1257        virtual     void        updateWaitTime_l();
1258    protected:
1259        virtual     void        saveOutputTracks();
1260        virtual     void        clearOutputTracks();
1261    private:
1262
1263                    uint32_t    mWaitTimeMs;
1264        SortedVector < sp<OutputTrack> >  outputTracks;
1265        SortedVector < sp<OutputTrack> >  mOutputTracks;
1266    public:
1267        virtual     bool        hasFastMixer() const { return false; }
1268    };
1269
1270              PlaybackThread *checkPlaybackThread_l(audio_io_handle_t output) const;
1271              MixerThread *checkMixerThread_l(audio_io_handle_t output) const;
1272              RecordThread *checkRecordThread_l(audio_io_handle_t input) const;
1273              // no range check, AudioFlinger::mLock held
1274              bool streamMute_l(audio_stream_type_t stream) const
1275                                { return mStreamTypes[stream].mute; }
1276              // no range check, doesn't check per-thread stream volume, AudioFlinger::mLock held
1277              float streamVolume_l(audio_stream_type_t stream) const
1278                                { return mStreamTypes[stream].volume; }
1279              void audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2);
1280
1281              // allocate an audio_io_handle_t, session ID, or effect ID
1282              uint32_t nextUniqueId();
1283
1284              status_t moveEffectChain_l(int sessionId,
1285                                     PlaybackThread *srcThread,
1286                                     PlaybackThread *dstThread,
1287                                     bool reRegister);
1288              // return thread associated with primary hardware device, or NULL
1289              PlaybackThread *primaryPlaybackThread_l() const;
1290              uint32_t primaryOutputDevice_l() const;
1291
1292              sp<PlaybackThread> getEffectThread_l(int sessionId, int EffectId);
1293
1294    // server side of the client's IAudioTrack
1295    class TrackHandle : public android::BnAudioTrack {
1296    public:
1297                            TrackHandle(const sp<PlaybackThread::Track>& track);
1298        virtual             ~TrackHandle();
1299        virtual sp<IMemory> getCblk() const;
1300        virtual status_t    start();
1301        virtual void        stop();
1302        virtual void        flush();
1303        virtual void        mute(bool);
1304        virtual void        pause();
1305        virtual status_t    attachAuxEffect(int effectId);
1306        virtual status_t    allocateTimedBuffer(size_t size,
1307                                                sp<IMemory>* buffer);
1308        virtual status_t    queueTimedBuffer(const sp<IMemory>& buffer,
1309                                             int64_t pts);
1310        virtual status_t    setMediaTimeTransform(const LinearTransform& xform,
1311                                                  int target);
1312        virtual status_t onTransact(
1313            uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags);
1314    private:
1315        const sp<PlaybackThread::Track> mTrack;
1316    };
1317
1318                void        removeClient_l(pid_t pid);
1319                void        removeNotificationClient(pid_t pid);
1320
1321
1322    // record thread
1323    class RecordThread : public ThreadBase, public AudioBufferProvider
1324    {
1325    public:
1326
1327        // record track
1328        class RecordTrack : public TrackBase {
1329        public:
1330                                RecordTrack(RecordThread *thread,
1331                                        const sp<Client>& client,
1332                                        uint32_t sampleRate,
1333                                        audio_format_t format,
1334                                        uint32_t channelMask,
1335                                        int frameCount,
1336                                        int sessionId);
1337            virtual             ~RecordTrack();
1338
1339            virtual status_t    start(AudioSystem::sync_event_t event = AudioSystem::SYNC_EVENT_NONE,
1340                                     int triggerSession = 0);
1341            virtual void        stop();
1342
1343                    bool        overflow() { bool tmp = mOverflow; mOverflow = false; return tmp; }
1344                    bool        setOverflow() { bool tmp = mOverflow; mOverflow = true; return tmp; }
1345
1346                    void        dump(char* buffer, size_t size);
1347
1348        private:
1349            friend class AudioFlinger;  // for mState
1350
1351                                RecordTrack(const RecordTrack&);
1352                                RecordTrack& operator = (const RecordTrack&);
1353
1354            // AudioBufferProvider interface
1355            virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts = kInvalidPTS);
1356            // releaseBuffer() not overridden
1357
1358            bool                mOverflow;
1359        };
1360
1361
1362                RecordThread(const sp<AudioFlinger>& audioFlinger,
1363                        AudioStreamIn *input,
1364                        uint32_t sampleRate,
1365                        uint32_t channels,
1366                        audio_io_handle_t id,
1367                        uint32_t device);
1368                virtual     ~RecordThread();
1369
1370        // Thread
1371        virtual bool        threadLoop();
1372        virtual status_t    readyToRun();
1373
1374        // RefBase
1375        virtual void        onFirstRef();
1376
1377        virtual status_t    initCheck() const { return (mInput == NULL) ? NO_INIT : NO_ERROR; }
1378                sp<AudioFlinger::RecordThread::RecordTrack>  createRecordTrack_l(
1379                        const sp<AudioFlinger::Client>& client,
1380                        uint32_t sampleRate,
1381                        audio_format_t format,
1382                        int channelMask,
1383                        int frameCount,
1384                        int sessionId,
1385                        status_t *status);
1386
1387                status_t    start(RecordTrack* recordTrack,
1388                                  AudioSystem::sync_event_t event,
1389                                  int triggerSession);
1390                void        stop(RecordTrack* recordTrack);
1391                status_t    dump(int fd, const Vector<String16>& args);
1392                AudioStreamIn* getInput() const;
1393                AudioStreamIn* clearInput();
1394                virtual audio_stream_t* stream() const;
1395
1396        // AudioBufferProvider interface
1397        virtual status_t    getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts);
1398        virtual void        releaseBuffer(AudioBufferProvider::Buffer* buffer);
1399
1400        virtual bool        checkForNewParameters_l();
1401        virtual String8     getParameters(const String8& keys);
1402        virtual void        audioConfigChanged_l(int event, int param = 0);
1403                void        readInputParameters();
1404        virtual unsigned int  getInputFramesLost();
1405
1406        virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
1407        virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
1408        virtual uint32_t hasAudioSession(int sessionId);
1409                RecordTrack* track();
1410
1411        virtual status_t setSyncEvent(const sp<SyncEvent>& event);
1412        virtual bool     isValidSyncEvent(const sp<SyncEvent>& event);
1413
1414        static void syncStartEventCallback(const wp<SyncEvent>& event);
1415               void handleSyncStartEvent(const sp<SyncEvent>& event);
1416
1417    private:
1418                void clearSyncStartEvent();
1419
1420                RecordThread();
1421                AudioStreamIn                       *mInput;
1422                RecordTrack*                        mTrack;
1423                sp<RecordTrack>                     mActiveTrack;
1424                Condition                           mStartStopCond;
1425                AudioResampler                      *mResampler;
1426                int32_t                             *mRsmpOutBuffer;
1427                int16_t                             *mRsmpInBuffer;
1428                size_t                              mRsmpInIndex;
1429                size_t                              mInputBytes;
1430                const int                           mReqChannelCount;
1431                const uint32_t                      mReqSampleRate;
1432                ssize_t                             mBytesRead;
1433                // sync event triggering actual audio capture. Frames read before this event will
1434                // be dropped and therefore not read by the application.
1435                sp<SyncEvent>                       mSyncStartEvent;
1436                // number of captured frames to drop after the start sync event has been received.
1437                // when < 0, maximum frames to drop before starting capture even if sync event is
1438                // not received
1439                ssize_t                             mFramestoDrop;
1440    };
1441
1442    // server side of the client's IAudioRecord
1443    class RecordHandle : public android::BnAudioRecord {
1444    public:
1445        RecordHandle(const sp<RecordThread::RecordTrack>& recordTrack);
1446        virtual             ~RecordHandle();
1447        virtual sp<IMemory> getCblk() const;
1448        virtual status_t    start(int event, int triggerSession);
1449        virtual void        stop();
1450        virtual status_t onTransact(
1451            uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags);
1452    private:
1453        const sp<RecordThread::RecordTrack> mRecordTrack;
1454    };
1455
1456    //--- Audio Effect Management
1457
1458    // EffectModule and EffectChain classes both have their own mutex to protect
1459    // state changes or resource modifications. Always respect the following order
1460    // if multiple mutexes must be acquired to avoid cross deadlock:
1461    // AudioFlinger -> ThreadBase -> EffectChain -> EffectModule
1462
1463    // The EffectModule class is a wrapper object controlling the effect engine implementation
1464    // in the effect library. It prevents concurrent calls to process() and command() functions
1465    // from different client threads. It keeps a list of EffectHandle objects corresponding
1466    // to all client applications using this effect and notifies applications of effect state,
1467    // control or parameter changes. It manages the activation state machine to send appropriate
1468    // reset, enable, disable commands to effect engine and provide volume
1469    // ramping when effects are activated/deactivated.
1470    // When controlling an auxiliary effect, the EffectModule also provides an input buffer used by
1471    // the attached track(s) to accumulate their auxiliary channel.
1472    class EffectModule: public RefBase {
1473    public:
1474        EffectModule(ThreadBase *thread,
1475                        const wp<AudioFlinger::EffectChain>& chain,
1476                        effect_descriptor_t *desc,
1477                        int id,
1478                        int sessionId);
1479        virtual ~EffectModule();
1480
1481        enum effect_state {
1482            IDLE,
1483            RESTART,
1484            STARTING,
1485            ACTIVE,
1486            STOPPING,
1487            STOPPED,
1488            DESTROYED
1489        };
1490
1491        int         id() const { return mId; }
1492        void process();
1493        void updateState();
1494        status_t command(uint32_t cmdCode,
1495                         uint32_t cmdSize,
1496                         void *pCmdData,
1497                         uint32_t *replySize,
1498                         void *pReplyData);
1499
1500        void reset_l();
1501        status_t configure();
1502        status_t init();
1503        effect_state state() const {
1504            return mState;
1505        }
1506        uint32_t status() {
1507            return mStatus;
1508        }
1509        int sessionId() const {
1510            return mSessionId;
1511        }
1512        status_t    setEnabled(bool enabled);
1513        bool isEnabled() const;
1514        bool isProcessEnabled() const;
1515
1516        void        setInBuffer(int16_t *buffer) { mConfig.inputCfg.buffer.s16 = buffer; }
1517        int16_t     *inBuffer() { return mConfig.inputCfg.buffer.s16; }
1518        void        setOutBuffer(int16_t *buffer) { mConfig.outputCfg.buffer.s16 = buffer; }
1519        int16_t     *outBuffer() { return mConfig.outputCfg.buffer.s16; }
1520        void        setChain(const wp<EffectChain>& chain) { mChain = chain; }
1521        void        setThread(const wp<ThreadBase>& thread) { mThread = thread; }
1522        const wp<ThreadBase>& thread() { return mThread; }
1523
1524        status_t addHandle(const sp<EffectHandle>& handle);
1525        void disconnect(const wp<EffectHandle>& handle, bool unpinIfLast);
1526        size_t removeHandle (const wp<EffectHandle>& handle);
1527
1528        effect_descriptor_t& desc() { return mDescriptor; }
1529        wp<EffectChain>&     chain() { return mChain; }
1530
1531        status_t         setDevice(uint32_t device);
1532        status_t         setVolume(uint32_t *left, uint32_t *right, bool controller);
1533        status_t         setMode(audio_mode_t mode);
1534        status_t         start();
1535        status_t         stop();
1536        void             setSuspended(bool suspended);
1537        bool             suspended() const;
1538
1539        sp<EffectHandle> controlHandle();
1540
1541        bool             isPinned() const { return mPinned; }
1542        void             unPin() { mPinned = false; }
1543
1544        status_t         dump(int fd, const Vector<String16>& args);
1545
1546    protected:
1547        friend class AudioFlinger;      // for mHandles
1548        bool                mPinned;
1549
1550        // Maximum time allocated to effect engines to complete the turn off sequence
1551        static const uint32_t MAX_DISABLE_TIME_MS = 10000;
1552
1553        EffectModule(const EffectModule&);
1554        EffectModule& operator = (const EffectModule&);
1555
1556        status_t start_l();
1557        status_t stop_l();
1558
1559mutable Mutex               mLock;      // mutex for process, commands and handles list protection
1560        wp<ThreadBase>      mThread;    // parent thread
1561        wp<EffectChain>     mChain;     // parent effect chain
1562        int                 mId;        // this instance unique ID
1563        int                 mSessionId; // audio session ID
1564        effect_descriptor_t mDescriptor;// effect descriptor received from effect engine
1565        effect_config_t     mConfig;    // input and output audio configuration
1566        effect_handle_t  mEffectInterface; // Effect module C API
1567        status_t            mStatus;    // initialization status
1568        effect_state        mState;     // current activation state
1569        Vector< wp<EffectHandle> > mHandles;    // list of client handles
1570                    // First handle in mHandles has highest priority and controls the effect module
1571        uint32_t mMaxDisableWaitCnt;    // maximum grace period before forcing an effect off after
1572                                        // sending disable command.
1573        uint32_t mDisableWaitCnt;       // current process() calls count during disable period.
1574        bool     mSuspended;            // effect is suspended: temporarily disabled by framework
1575    };
1576
1577    // The EffectHandle class implements the IEffect interface. It provides resources
1578    // to receive parameter updates, keeps track of effect control
1579    // ownership and state and has a pointer to the EffectModule object it is controlling.
1580    // There is one EffectHandle object for each application controlling (or using)
1581    // an effect module.
1582    // The EffectHandle is obtained by calling AudioFlinger::createEffect().
1583    class EffectHandle: public android::BnEffect {
1584    public:
1585
1586        EffectHandle(const sp<EffectModule>& effect,
1587                const sp<AudioFlinger::Client>& client,
1588                const sp<IEffectClient>& effectClient,
1589                int32_t priority);
1590        virtual ~EffectHandle();
1591
1592        // IEffect
1593        virtual status_t enable();
1594        virtual status_t disable();
1595        virtual status_t command(uint32_t cmdCode,
1596                                 uint32_t cmdSize,
1597                                 void *pCmdData,
1598                                 uint32_t *replySize,
1599                                 void *pReplyData);
1600        virtual void disconnect();
1601    private:
1602                void disconnect(bool unpinIfLast);
1603    public:
1604        virtual sp<IMemory> getCblk() const { return mCblkMemory; }
1605        virtual status_t onTransact(uint32_t code, const Parcel& data,
1606                Parcel* reply, uint32_t flags);
1607
1608
1609        // Give or take control of effect module
1610        // - hasControl: true if control is given, false if removed
1611        // - signal: true client app should be signaled of change, false otherwise
1612        // - enabled: state of the effect when control is passed
1613        void setControl(bool hasControl, bool signal, bool enabled);
1614        void commandExecuted(uint32_t cmdCode,
1615                             uint32_t cmdSize,
1616                             void *pCmdData,
1617                             uint32_t replySize,
1618                             void *pReplyData);
1619        void setEnabled(bool enabled);
1620        bool enabled() const { return mEnabled; }
1621
1622        // Getters
1623        int id() const { return mEffect->id(); }
1624        int priority() const { return mPriority; }
1625        bool hasControl() const { return mHasControl; }
1626        sp<EffectModule> effect() const { return mEffect; }
1627
1628        void dump(char* buffer, size_t size);
1629
1630    protected:
1631        friend class AudioFlinger;          // for mEffect, mHasControl, mEnabled
1632        EffectHandle(const EffectHandle&);
1633        EffectHandle& operator =(const EffectHandle&);
1634
1635        sp<EffectModule> mEffect;           // pointer to controlled EffectModule
1636        sp<IEffectClient> mEffectClient;    // callback interface for client notifications
1637        /*const*/ sp<Client> mClient;       // client for shared memory allocation, see disconnect()
1638        sp<IMemory>         mCblkMemory;    // shared memory for control block
1639        effect_param_cblk_t* mCblk;         // control block for deferred parameter setting via shared memory
1640        uint8_t*            mBuffer;        // pointer to parameter area in shared memory
1641        int mPriority;                      // client application priority to control the effect
1642        bool mHasControl;                   // true if this handle is controlling the effect
1643        bool mEnabled;                      // cached enable state: needed when the effect is
1644                                            // restored after being suspended
1645    };
1646
1647    // the EffectChain class represents a group of effects associated to one audio session.
1648    // There can be any number of EffectChain objects per output mixer thread (PlaybackThread).
1649    // The EffecChain with session ID 0 contains global effects applied to the output mix.
1650    // Effects in this chain can be insert or auxiliary. Effects in other chains (attached to tracks)
1651    // are insert only. The EffectChain maintains an ordered list of effect module, the order corresponding
1652    // in the effect process order. When attached to a track (session ID != 0), it also provide it's own
1653    // input buffer used by the track as accumulation buffer.
1654    class EffectChain: public RefBase {
1655    public:
1656        EffectChain(const wp<ThreadBase>& wThread, int sessionId);
1657        EffectChain(ThreadBase *thread, int sessionId);
1658        virtual ~EffectChain();
1659
1660        // special key used for an entry in mSuspendedEffects keyed vector
1661        // corresponding to a suspend all request.
1662        static const int        kKeyForSuspendAll = 0;
1663
1664        // minimum duration during which we force calling effect process when last track on
1665        // a session is stopped or removed to allow effect tail to be rendered
1666        static const int        kProcessTailDurationMs = 1000;
1667
1668        void process_l();
1669
1670        void lock() {
1671            mLock.lock();
1672        }
1673        void unlock() {
1674            mLock.unlock();
1675        }
1676
1677        status_t addEffect_l(const sp<EffectModule>& handle);
1678        size_t removeEffect_l(const sp<EffectModule>& handle);
1679
1680        int sessionId() const { return mSessionId; }
1681        void setSessionId(int sessionId) { mSessionId = sessionId; }
1682
1683        sp<EffectModule> getEffectFromDesc_l(effect_descriptor_t *descriptor);
1684        sp<EffectModule> getEffectFromId_l(int id);
1685        sp<EffectModule> getEffectFromType_l(const effect_uuid_t *type);
1686        bool setVolume_l(uint32_t *left, uint32_t *right);
1687        void setDevice_l(uint32_t device);
1688        void setMode_l(audio_mode_t mode);
1689
1690        void setInBuffer(int16_t *buffer, bool ownsBuffer = false) {
1691            mInBuffer = buffer;
1692            mOwnInBuffer = ownsBuffer;
1693        }
1694        int16_t *inBuffer() const {
1695            return mInBuffer;
1696        }
1697        void setOutBuffer(int16_t *buffer) {
1698            mOutBuffer = buffer;
1699        }
1700        int16_t *outBuffer() const {
1701            return mOutBuffer;
1702        }
1703
1704        void incTrackCnt() { android_atomic_inc(&mTrackCnt); }
1705        void decTrackCnt() { android_atomic_dec(&mTrackCnt); }
1706        int32_t trackCnt() const { return mTrackCnt;}
1707
1708        void incActiveTrackCnt() { android_atomic_inc(&mActiveTrackCnt);
1709                                   mTailBufferCount = mMaxTailBuffers; }
1710        void decActiveTrackCnt() { android_atomic_dec(&mActiveTrackCnt); }
1711        int32_t activeTrackCnt() const { return mActiveTrackCnt;}
1712
1713        uint32_t strategy() const { return mStrategy; }
1714        void setStrategy(uint32_t strategy)
1715                { mStrategy = strategy; }
1716
1717        // suspend effect of the given type
1718        void setEffectSuspended_l(const effect_uuid_t *type,
1719                                  bool suspend);
1720        // suspend all eligible effects
1721        void setEffectSuspendedAll_l(bool suspend);
1722        // check if effects should be suspend or restored when a given effect is enable or disabled
1723        void checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1724                                              bool enabled);
1725
1726        void clearInputBuffer();
1727
1728        status_t dump(int fd, const Vector<String16>& args);
1729
1730    protected:
1731        friend class AudioFlinger;  // for mThread, mEffects
1732        EffectChain(const EffectChain&);
1733        EffectChain& operator =(const EffectChain&);
1734
1735        class SuspendedEffectDesc : public RefBase {
1736        public:
1737            SuspendedEffectDesc() : mRefCount(0) {}
1738
1739            int mRefCount;
1740            effect_uuid_t mType;
1741            wp<EffectModule> mEffect;
1742        };
1743
1744        // get a list of effect modules to suspend when an effect of the type
1745        // passed is enabled.
1746        void                       getSuspendEligibleEffects(Vector< sp<EffectModule> > &effects);
1747
1748        // get an effect module if it is currently enable
1749        sp<EffectModule> getEffectIfEnabled(const effect_uuid_t *type);
1750        // true if the effect whose descriptor is passed can be suspended
1751        // OEMs can modify the rules implemented in this method to exclude specific effect
1752        // types or implementations from the suspend/restore mechanism.
1753        bool isEffectEligibleForSuspend(const effect_descriptor_t& desc);
1754
1755        void clearInputBuffer_l(sp<ThreadBase> thread);
1756
1757        wp<ThreadBase> mThread;     // parent mixer thread
1758        Mutex mLock;                // mutex protecting effect list
1759        Vector< sp<EffectModule> > mEffects; // list of effect modules
1760        int mSessionId;             // audio session ID
1761        int16_t *mInBuffer;         // chain input buffer
1762        int16_t *mOutBuffer;        // chain output buffer
1763        volatile int32_t mActiveTrackCnt;  // number of active tracks connected
1764        volatile int32_t mTrackCnt;        // number of tracks connected
1765        int32_t mTailBufferCount;   // current effect tail buffer count
1766        int32_t mMaxTailBuffers;    // maximum effect tail buffers
1767        bool mOwnInBuffer;          // true if the chain owns its input buffer
1768        int mVolumeCtrlIdx;         // index of insert effect having control over volume
1769        uint32_t mLeftVolume;       // previous volume on left channel
1770        uint32_t mRightVolume;      // previous volume on right channel
1771        uint32_t mNewLeftVolume;       // new volume on left channel
1772        uint32_t mNewRightVolume;      // new volume on right channel
1773        uint32_t mStrategy; // strategy for this effect chain
1774        // mSuspendedEffects lists all effects currently suspended in the chain.
1775        // Use effect type UUID timelow field as key. There is no real risk of identical
1776        // timeLow fields among effect type UUIDs.
1777        // Updated by updateSuspendedSessions_l() only.
1778        KeyedVector< int, sp<SuspendedEffectDesc> > mSuspendedEffects;
1779    };
1780
1781    // AudioStreamOut and AudioStreamIn are immutable, so their fields are const.
1782    // For emphasis, we could also make all pointers to them be "const *",
1783    // but that would clutter the code unnecessarily.
1784
1785    struct AudioStreamOut {
1786        audio_hw_device_t*  const hwDev;
1787        audio_stream_out_t* const stream;
1788
1789        AudioStreamOut(audio_hw_device_t *dev, audio_stream_out_t *out) :
1790            hwDev(dev), stream(out) {}
1791    };
1792
1793    struct AudioStreamIn {
1794        audio_hw_device_t* const hwDev;
1795        audio_stream_in_t* const stream;
1796
1797        AudioStreamIn(audio_hw_device_t *dev, audio_stream_in_t *in) :
1798            hwDev(dev), stream(in) {}
1799    };
1800
1801    // for mAudioSessionRefs only
1802    struct AudioSessionRef {
1803        AudioSessionRef(int sessionid, pid_t pid) :
1804            mSessionid(sessionid), mPid(pid), mCnt(1) {}
1805        const int   mSessionid;
1806        const pid_t mPid;
1807        int         mCnt;
1808    };
1809
1810    enum master_volume_support {
1811        // MVS_NONE:
1812        // Audio HAL has no support for master volume, either setting or
1813        // getting.  All master volume control must be implemented in SW by the
1814        // AudioFlinger mixing core.
1815        MVS_NONE,
1816
1817        // MVS_SETONLY:
1818        // Audio HAL has support for setting master volume, but not for getting
1819        // master volume (original HAL design did not include a getter).
1820        // AudioFlinger needs to keep track of the last set master volume in
1821        // addition to needing to set an initial, default, master volume at HAL
1822        // load time.
1823        MVS_SETONLY,
1824
1825        // MVS_FULL:
1826        // Audio HAL has support both for setting and getting master volume.
1827        // AudioFlinger should send all set and get master volume requests
1828        // directly to the HAL.
1829        MVS_FULL,
1830    };
1831
1832    class AudioHwDevice {
1833    public:
1834        AudioHwDevice(const char *moduleName, audio_hw_device_t *hwDevice) :
1835            mModuleName(strdup(moduleName)), mHwDevice(hwDevice){}
1836        ~AudioHwDevice() { free((void *)mModuleName); }
1837
1838        const char *moduleName() const { return mModuleName; }
1839        audio_hw_device_t *hwDevice() const { return mHwDevice; }
1840    private:
1841        const char * const mModuleName;
1842        audio_hw_device_t * const mHwDevice;
1843    };
1844
1845    mutable     Mutex                               mLock;
1846
1847                DefaultKeyedVector< pid_t, wp<Client> >     mClients;   // see ~Client()
1848
1849                mutable     Mutex                   mHardwareLock;
1850                // NOTE: If both mLock and mHardwareLock mutexes must be held,
1851                // always take mLock before mHardwareLock
1852
1853                // These two fields are immutable after onFirstRef(), so no lock needed to access
1854                audio_hw_device_t*                  mPrimaryHardwareDev; // mAudioHwDevs[0] or NULL
1855                DefaultKeyedVector<audio_module_handle_t, AudioHwDevice*>  mAudioHwDevs;
1856
1857    // for dump, indicates which hardware operation is currently in progress (but not stream ops)
1858    enum hardware_call_state {
1859        AUDIO_HW_IDLE = 0,              // no operation in progress
1860        AUDIO_HW_INIT,                  // init_check
1861        AUDIO_HW_OUTPUT_OPEN,           // open_output_stream
1862        AUDIO_HW_OUTPUT_CLOSE,          // unused
1863        AUDIO_HW_INPUT_OPEN,            // unused
1864        AUDIO_HW_INPUT_CLOSE,           // unused
1865        AUDIO_HW_STANDBY,               // unused
1866        AUDIO_HW_SET_MASTER_VOLUME,     // set_master_volume
1867        AUDIO_HW_GET_ROUTING,           // unused
1868        AUDIO_HW_SET_ROUTING,           // unused
1869        AUDIO_HW_GET_MODE,              // unused
1870        AUDIO_HW_SET_MODE,              // set_mode
1871        AUDIO_HW_GET_MIC_MUTE,          // get_mic_mute
1872        AUDIO_HW_SET_MIC_MUTE,          // set_mic_mute
1873        AUDIO_HW_SET_VOICE_VOLUME,      // set_voice_volume
1874        AUDIO_HW_SET_PARAMETER,         // set_parameters
1875        AUDIO_HW_GET_INPUT_BUFFER_SIZE, // get_input_buffer_size
1876        AUDIO_HW_GET_MASTER_VOLUME,     // get_master_volume
1877        AUDIO_HW_GET_PARAMETER,         // get_parameters
1878    };
1879
1880    mutable     hardware_call_state                 mHardwareStatus;    // for dump only
1881
1882
1883                DefaultKeyedVector< audio_io_handle_t, sp<PlaybackThread> >  mPlaybackThreads;
1884                stream_type_t                       mStreamTypes[AUDIO_STREAM_CNT];
1885
1886                // both are protected by mLock
1887                float                               mMasterVolume;
1888                float                               mMasterVolumeSW;
1889                master_volume_support               mMasterVolumeSupportLvl;
1890                bool                                mMasterMute;
1891
1892                DefaultKeyedVector< audio_io_handle_t, sp<RecordThread> >    mRecordThreads;
1893
1894                DefaultKeyedVector< pid_t, sp<NotificationClient> >    mNotificationClients;
1895                volatile int32_t                    mNextUniqueId;  // updated by android_atomic_inc
1896                audio_mode_t                        mMode;
1897                bool                                mBtNrecIsOff;
1898
1899                // protected by mLock
1900                Vector<AudioSessionRef*> mAudioSessionRefs;
1901
1902                float       masterVolume_l() const;
1903                float       masterVolumeSW_l() const  { return mMasterVolumeSW; }
1904                bool        masterMute_l() const    { return mMasterMute; }
1905                audio_module_handle_t loadHwModule_l(const char *name);
1906
1907                Vector < sp<SyncEvent> > mPendingSyncEvents; // sync events awaiting for a session
1908                                                             // to be created
1909
1910private:
1911    sp<Client>  registerPid_l(pid_t pid);    // always returns non-0
1912
1913};
1914
1915
1916// ----------------------------------------------------------------------------
1917
1918}; // namespace android
1919
1920#endif // ANDROID_AUDIO_FLINGER_H
1921