AudioFlinger.h revision dbabf8a7dfe3aa8bf0ed169220d2009d5891fef2
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                            void     invalidateTracks(audio_stream_type_t streamType);
1022
1023
1024    protected:
1025        int16_t*                        mMixBuffer;
1026        uint32_t                        mSuspended;     // suspend count, > 0 means suspended
1027        int                             mBytesWritten;
1028    private:
1029        // mMasterMute is in both PlaybackThread and in AudioFlinger.  When a
1030        // PlaybackThread needs to find out if master-muted, it checks it's local
1031        // copy rather than the one in AudioFlinger.  This optimization saves a lock.
1032        bool                            mMasterMute;
1033                    void        setMasterMute_l(bool muted) { mMasterMute = muted; }
1034    protected:
1035        SortedVector< wp<Track> >       mActiveTracks;  // FIXME check if this could be sp<>
1036
1037        // Allocate a track name for a given channel mask.
1038        //   Returns name >= 0 if successful, -1 on failure.
1039        virtual int             getTrackName_l(audio_channel_mask_t channelMask) = 0;
1040        virtual void            deleteTrackName_l(int name) = 0;
1041
1042        // Time to sleep between cycles when:
1043        virtual uint32_t        activeSleepTimeUs() const;      // mixer state MIXER_TRACKS_ENABLED
1044        virtual uint32_t        idleSleepTimeUs() const = 0;    // mixer state MIXER_IDLE
1045        virtual uint32_t        suspendSleepTimeUs() const = 0; // audio policy manager suspended us
1046        // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write()
1047        // No sleep in standby mode; waits on a condition
1048
1049        // Code snippets that are temporarily lifted up out of threadLoop() until the merge
1050                    void        checkSilentMode_l();
1051
1052        // Non-trivial for DUPLICATING only
1053        virtual     void        saveOutputTracks() { }
1054        virtual     void        clearOutputTracks() { }
1055
1056        // Cache various calculated values, at threadLoop() entry and after a parameter change
1057        virtual     void        cacheParameters_l();
1058
1059        virtual     uint32_t    correctLatency(uint32_t latency) const;
1060
1061    private:
1062
1063        friend class AudioFlinger;      // for numerous
1064
1065        PlaybackThread(const Client&);
1066        PlaybackThread& operator = (const PlaybackThread&);
1067
1068        status_t    addTrack_l(const sp<Track>& track);
1069        void        destroyTrack_l(const sp<Track>& track);
1070        void        removeTrack_l(const sp<Track>& track);
1071
1072        void        readOutputParameters();
1073
1074        virtual status_t    dumpInternals(int fd, const Vector<String16>& args);
1075        status_t    dumpTracks(int fd, const Vector<String16>& args);
1076
1077        SortedVector< sp<Track> >       mTracks;
1078        // mStreamTypes[] uses 1 additional stream type internally for the OutputTrack used by DuplicatingThread
1079        stream_type_t                   mStreamTypes[AUDIO_STREAM_CNT + 1];
1080        AudioStreamOut                  *mOutput;
1081        float                           mMasterVolume;
1082        nsecs_t                         mLastWriteTime;
1083        int                             mNumWrites;
1084        int                             mNumDelayedWrites;
1085        bool                            mInWrite;
1086
1087        // FIXME rename these former local variables of threadLoop to standard "m" names
1088        nsecs_t                         standbyTime;
1089        size_t                          mixBufferSize;
1090
1091        // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l()
1092        uint32_t                        activeSleepTime;
1093        uint32_t                        idleSleepTime;
1094
1095        uint32_t                        sleepTime;
1096
1097        // mixer status returned by prepareTracks_l()
1098        mixer_state                     mMixerStatus; // current cycle
1099                                                      // previous cycle when in prepareTracks_l()
1100        mixer_state                     mMixerStatusIgnoringFastTracks;
1101                                                      // FIXME or a separate ready state per track
1102
1103        // FIXME move these declarations into the specific sub-class that needs them
1104        // MIXER only
1105        bool                            longStandbyExit;
1106        uint32_t                        sleepTimeShift;
1107
1108        // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value
1109        nsecs_t                         standbyDelay;
1110
1111        // MIXER only
1112        nsecs_t                         maxPeriod;
1113
1114        // DUPLICATING only
1115        uint32_t                        writeFrames;
1116
1117    private:
1118        // The HAL output sink is treated as non-blocking, but current implementation is blocking
1119        sp<NBAIO_Sink>          mOutputSink;
1120        // If a fast mixer is present, the blocking pipe sink, otherwise clear
1121        sp<NBAIO_Sink>          mPipeSink;
1122        // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink
1123        sp<NBAIO_Sink>          mNormalSink;
1124        // For dumpsys
1125        sp<NBAIO_Sink>          mTeeSink;
1126        sp<NBAIO_Source>        mTeeSource;
1127        uint32_t                mScreenState;   // cached copy of gScreenState
1128    public:
1129        virtual     bool        hasFastMixer() const = 0;
1130        virtual     FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const
1131                                    { FastTrackUnderruns dummy; return dummy; }
1132
1133    protected:
1134                    // accessed by both binder threads and within threadLoop(), lock on mutex needed
1135                    unsigned    mFastTrackAvailMask;    // bit i set if fast track [i] is available
1136
1137    };
1138
1139    class MixerThread : public PlaybackThread {
1140    public:
1141        MixerThread (const sp<AudioFlinger>& audioFlinger,
1142                     AudioStreamOut* output,
1143                     audio_io_handle_t id,
1144                     uint32_t device,
1145                     type_t type = MIXER);
1146        virtual             ~MixerThread();
1147
1148        // Thread virtuals
1149
1150        virtual     bool        checkForNewParameters_l();
1151        virtual     status_t    dumpInternals(int fd, const Vector<String16>& args);
1152
1153    protected:
1154        virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
1155        virtual     int         getTrackName_l(audio_channel_mask_t channelMask);
1156        virtual     void        deleteTrackName_l(int name);
1157        virtual     uint32_t    idleSleepTimeUs() const;
1158        virtual     uint32_t    suspendSleepTimeUs() const;
1159        virtual     void        cacheParameters_l();
1160
1161        // threadLoop snippets
1162        virtual     void        threadLoop_write();
1163        virtual     void        threadLoop_standby();
1164        virtual     void        threadLoop_mix();
1165        virtual     void        threadLoop_sleepTime();
1166        virtual     void        threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
1167        virtual     uint32_t    correctLatency(uint32_t latency) const;
1168
1169                    AudioMixer* mAudioMixer;    // normal mixer
1170    private:
1171#ifdef SOAKER
1172                    Thread*     mSoaker;
1173#endif
1174                    // one-time initialization, no locks required
1175                    FastMixer*  mFastMixer;         // non-NULL if there is also a fast mixer
1176                    sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread
1177
1178                    // contents are not guaranteed to be consistent, no locks required
1179                    FastMixerDumpState mFastMixerDumpState;
1180#ifdef STATE_QUEUE_DUMP
1181                    StateQueueObserverDump mStateQueueObserverDump;
1182                    StateQueueMutatorDump  mStateQueueMutatorDump;
1183#endif
1184                    AudioWatchdogDump mAudioWatchdogDump;
1185
1186                    // accessible only within the threadLoop(), no locks required
1187                    //          mFastMixer->sq()    // for mutating and pushing state
1188                    int32_t     mFastMixerFutex;    // for cold idle
1189
1190    public:
1191        virtual     bool        hasFastMixer() const { return mFastMixer != NULL; }
1192        virtual     FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const {
1193                                  ALOG_ASSERT(fastIndex < FastMixerState::kMaxFastTracks);
1194                                  return mFastMixerDumpState.mTracks[fastIndex].mUnderruns;
1195                                }
1196    };
1197
1198    class DirectOutputThread : public PlaybackThread {
1199    public:
1200
1201        DirectOutputThread (const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
1202                            audio_io_handle_t id, uint32_t device);
1203        virtual                 ~DirectOutputThread();
1204
1205        // Thread virtuals
1206
1207        virtual     bool        checkForNewParameters_l();
1208
1209    protected:
1210        virtual     int         getTrackName_l(audio_channel_mask_t channelMask);
1211        virtual     void        deleteTrackName_l(int name);
1212        virtual     uint32_t    activeSleepTimeUs() const;
1213        virtual     uint32_t    idleSleepTimeUs() const;
1214        virtual     uint32_t    suspendSleepTimeUs() const;
1215        virtual     void        cacheParameters_l();
1216
1217        // threadLoop snippets
1218        virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
1219        virtual     void        threadLoop_mix();
1220        virtual     void        threadLoop_sleepTime();
1221
1222        // volumes last sent to audio HAL with stream->set_volume()
1223        float mLeftVolFloat;
1224        float mRightVolFloat;
1225
1226private:
1227        // prepareTracks_l() tells threadLoop_mix() the name of the single active track
1228        sp<Track>               mActiveTrack;
1229    public:
1230        virtual     bool        hasFastMixer() const { return false; }
1231    };
1232
1233    class DuplicatingThread : public MixerThread {
1234    public:
1235        DuplicatingThread (const sp<AudioFlinger>& audioFlinger, MixerThread* mainThread,
1236                           audio_io_handle_t id);
1237        virtual                 ~DuplicatingThread();
1238
1239        // Thread virtuals
1240                    void        addOutputTrack(MixerThread* thread);
1241                    void        removeOutputTrack(MixerThread* thread);
1242                    uint32_t    waitTimeMs() const { return mWaitTimeMs; }
1243    protected:
1244        virtual     uint32_t    activeSleepTimeUs() const;
1245
1246    private:
1247                    bool        outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks);
1248    protected:
1249        // threadLoop snippets
1250        virtual     void        threadLoop_mix();
1251        virtual     void        threadLoop_sleepTime();
1252        virtual     void        threadLoop_write();
1253        virtual     void        threadLoop_standby();
1254        virtual     void        cacheParameters_l();
1255
1256    private:
1257        // called from threadLoop, addOutputTrack, removeOutputTrack
1258        virtual     void        updateWaitTime_l();
1259    protected:
1260        virtual     void        saveOutputTracks();
1261        virtual     void        clearOutputTracks();
1262    private:
1263
1264                    uint32_t    mWaitTimeMs;
1265        SortedVector < sp<OutputTrack> >  outputTracks;
1266        SortedVector < sp<OutputTrack> >  mOutputTracks;
1267    public:
1268        virtual     bool        hasFastMixer() const { return false; }
1269    };
1270
1271              PlaybackThread *checkPlaybackThread_l(audio_io_handle_t output) const;
1272              MixerThread *checkMixerThread_l(audio_io_handle_t output) const;
1273              RecordThread *checkRecordThread_l(audio_io_handle_t input) const;
1274              // no range check, AudioFlinger::mLock held
1275              bool streamMute_l(audio_stream_type_t stream) const
1276                                { return mStreamTypes[stream].mute; }
1277              // no range check, doesn't check per-thread stream volume, AudioFlinger::mLock held
1278              float streamVolume_l(audio_stream_type_t stream) const
1279                                { return mStreamTypes[stream].volume; }
1280              void audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2);
1281
1282              // allocate an audio_io_handle_t, session ID, or effect ID
1283              uint32_t nextUniqueId();
1284
1285              status_t moveEffectChain_l(int sessionId,
1286                                     PlaybackThread *srcThread,
1287                                     PlaybackThread *dstThread,
1288                                     bool reRegister);
1289              // return thread associated with primary hardware device, or NULL
1290              PlaybackThread *primaryPlaybackThread_l() const;
1291              uint32_t primaryOutputDevice_l() const;
1292
1293              sp<PlaybackThread> getEffectThread_l(int sessionId, int EffectId);
1294
1295    // server side of the client's IAudioTrack
1296    class TrackHandle : public android::BnAudioTrack {
1297    public:
1298                            TrackHandle(const sp<PlaybackThread::Track>& track);
1299        virtual             ~TrackHandle();
1300        virtual sp<IMemory> getCblk() const;
1301        virtual status_t    start();
1302        virtual void        stop();
1303        virtual void        flush();
1304        virtual void        mute(bool);
1305        virtual void        pause();
1306        virtual status_t    attachAuxEffect(int effectId);
1307        virtual status_t    allocateTimedBuffer(size_t size,
1308                                                sp<IMemory>* buffer);
1309        virtual status_t    queueTimedBuffer(const sp<IMemory>& buffer,
1310                                             int64_t pts);
1311        virtual status_t    setMediaTimeTransform(const LinearTransform& xform,
1312                                                  int target);
1313        virtual status_t onTransact(
1314            uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags);
1315    private:
1316        const sp<PlaybackThread::Track> mTrack;
1317    };
1318
1319                void        removeClient_l(pid_t pid);
1320                void        removeNotificationClient(pid_t pid);
1321
1322
1323    // record thread
1324    class RecordThread : public ThreadBase, public AudioBufferProvider
1325    {
1326    public:
1327
1328        // record track
1329        class RecordTrack : public TrackBase {
1330        public:
1331                                RecordTrack(RecordThread *thread,
1332                                        const sp<Client>& client,
1333                                        uint32_t sampleRate,
1334                                        audio_format_t format,
1335                                        uint32_t channelMask,
1336                                        int frameCount,
1337                                        int sessionId);
1338            virtual             ~RecordTrack();
1339
1340            virtual status_t    start(AudioSystem::sync_event_t event = AudioSystem::SYNC_EVENT_NONE,
1341                                     int triggerSession = 0);
1342            virtual void        stop();
1343
1344                    bool        overflow() { bool tmp = mOverflow; mOverflow = false; return tmp; }
1345                    bool        setOverflow() { bool tmp = mOverflow; mOverflow = true; return tmp; }
1346
1347                    void        dump(char* buffer, size_t size);
1348
1349        private:
1350            friend class AudioFlinger;  // for mState
1351
1352                                RecordTrack(const RecordTrack&);
1353                                RecordTrack& operator = (const RecordTrack&);
1354
1355            // AudioBufferProvider interface
1356            virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts = kInvalidPTS);
1357            // releaseBuffer() not overridden
1358
1359            bool                mOverflow;
1360        };
1361
1362
1363                RecordThread(const sp<AudioFlinger>& audioFlinger,
1364                        AudioStreamIn *input,
1365                        uint32_t sampleRate,
1366                        uint32_t channels,
1367                        audio_io_handle_t id,
1368                        uint32_t device);
1369                virtual     ~RecordThread();
1370
1371        // Thread
1372        virtual bool        threadLoop();
1373        virtual status_t    readyToRun();
1374
1375        // RefBase
1376        virtual void        onFirstRef();
1377
1378        virtual status_t    initCheck() const { return (mInput == NULL) ? NO_INIT : NO_ERROR; }
1379                sp<AudioFlinger::RecordThread::RecordTrack>  createRecordTrack_l(
1380                        const sp<AudioFlinger::Client>& client,
1381                        uint32_t sampleRate,
1382                        audio_format_t format,
1383                        int channelMask,
1384                        int frameCount,
1385                        int sessionId,
1386                        status_t *status);
1387
1388                status_t    start(RecordTrack* recordTrack,
1389                                  AudioSystem::sync_event_t event,
1390                                  int triggerSession);
1391                void        stop(RecordTrack* recordTrack);
1392                status_t    dump(int fd, const Vector<String16>& args);
1393                AudioStreamIn* getInput() const;
1394                AudioStreamIn* clearInput();
1395                virtual audio_stream_t* stream() const;
1396
1397        // AudioBufferProvider interface
1398        virtual status_t    getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts);
1399        virtual void        releaseBuffer(AudioBufferProvider::Buffer* buffer);
1400
1401        virtual bool        checkForNewParameters_l();
1402        virtual String8     getParameters(const String8& keys);
1403        virtual void        audioConfigChanged_l(int event, int param = 0);
1404                void        readInputParameters();
1405        virtual unsigned int  getInputFramesLost();
1406
1407        virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
1408        virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
1409        virtual uint32_t hasAudioSession(int sessionId);
1410                RecordTrack* track();
1411
1412        virtual status_t setSyncEvent(const sp<SyncEvent>& event);
1413        virtual bool     isValidSyncEvent(const sp<SyncEvent>& event);
1414
1415        static void syncStartEventCallback(const wp<SyncEvent>& event);
1416               void handleSyncStartEvent(const sp<SyncEvent>& event);
1417
1418    private:
1419                void clearSyncStartEvent();
1420
1421                RecordThread();
1422                AudioStreamIn                       *mInput;
1423                RecordTrack*                        mTrack;
1424                sp<RecordTrack>                     mActiveTrack;
1425                Condition                           mStartStopCond;
1426                AudioResampler                      *mResampler;
1427                int32_t                             *mRsmpOutBuffer;
1428                int16_t                             *mRsmpInBuffer;
1429                size_t                              mRsmpInIndex;
1430                size_t                              mInputBytes;
1431                const int                           mReqChannelCount;
1432                const uint32_t                      mReqSampleRate;
1433                ssize_t                             mBytesRead;
1434                // sync event triggering actual audio capture. Frames read before this event will
1435                // be dropped and therefore not read by the application.
1436                sp<SyncEvent>                       mSyncStartEvent;
1437                // number of captured frames to drop after the start sync event has been received.
1438                // when < 0, maximum frames to drop before starting capture even if sync event is
1439                // not received
1440                ssize_t                             mFramestoDrop;
1441    };
1442
1443    // server side of the client's IAudioRecord
1444    class RecordHandle : public android::BnAudioRecord {
1445    public:
1446        RecordHandle(const sp<RecordThread::RecordTrack>& recordTrack);
1447        virtual             ~RecordHandle();
1448        virtual sp<IMemory> getCblk() const;
1449        virtual status_t    start(int event, int triggerSession);
1450        virtual void        stop();
1451        virtual status_t onTransact(
1452            uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags);
1453    private:
1454        const sp<RecordThread::RecordTrack> mRecordTrack;
1455    };
1456
1457    //--- Audio Effect Management
1458
1459    // EffectModule and EffectChain classes both have their own mutex to protect
1460    // state changes or resource modifications. Always respect the following order
1461    // if multiple mutexes must be acquired to avoid cross deadlock:
1462    // AudioFlinger -> ThreadBase -> EffectChain -> EffectModule
1463
1464    // The EffectModule class is a wrapper object controlling the effect engine implementation
1465    // in the effect library. It prevents concurrent calls to process() and command() functions
1466    // from different client threads. It keeps a list of EffectHandle objects corresponding
1467    // to all client applications using this effect and notifies applications of effect state,
1468    // control or parameter changes. It manages the activation state machine to send appropriate
1469    // reset, enable, disable commands to effect engine and provide volume
1470    // ramping when effects are activated/deactivated.
1471    // When controlling an auxiliary effect, the EffectModule also provides an input buffer used by
1472    // the attached track(s) to accumulate their auxiliary channel.
1473    class EffectModule: public RefBase {
1474    public:
1475        EffectModule(ThreadBase *thread,
1476                        const wp<AudioFlinger::EffectChain>& chain,
1477                        effect_descriptor_t *desc,
1478                        int id,
1479                        int sessionId);
1480        virtual ~EffectModule();
1481
1482        enum effect_state {
1483            IDLE,
1484            RESTART,
1485            STARTING,
1486            ACTIVE,
1487            STOPPING,
1488            STOPPED,
1489            DESTROYED
1490        };
1491
1492        int         id() const { return mId; }
1493        void process();
1494        void updateState();
1495        status_t command(uint32_t cmdCode,
1496                         uint32_t cmdSize,
1497                         void *pCmdData,
1498                         uint32_t *replySize,
1499                         void *pReplyData);
1500
1501        void reset_l();
1502        status_t configure();
1503        status_t init();
1504        effect_state state() const {
1505            return mState;
1506        }
1507        uint32_t status() {
1508            return mStatus;
1509        }
1510        int sessionId() const {
1511            return mSessionId;
1512        }
1513        status_t    setEnabled(bool enabled);
1514        bool isEnabled() const;
1515        bool isProcessEnabled() const;
1516
1517        void        setInBuffer(int16_t *buffer) { mConfig.inputCfg.buffer.s16 = buffer; }
1518        int16_t     *inBuffer() { return mConfig.inputCfg.buffer.s16; }
1519        void        setOutBuffer(int16_t *buffer) { mConfig.outputCfg.buffer.s16 = buffer; }
1520        int16_t     *outBuffer() { return mConfig.outputCfg.buffer.s16; }
1521        void        setChain(const wp<EffectChain>& chain) { mChain = chain; }
1522        void        setThread(const wp<ThreadBase>& thread) { mThread = thread; }
1523        const wp<ThreadBase>& thread() { return mThread; }
1524
1525        status_t addHandle(const sp<EffectHandle>& handle);
1526        void disconnect(const wp<EffectHandle>& handle, bool unpinIfLast);
1527        size_t removeHandle (const wp<EffectHandle>& handle);
1528
1529        effect_descriptor_t& desc() { return mDescriptor; }
1530        wp<EffectChain>&     chain() { return mChain; }
1531
1532        status_t         setDevice(uint32_t device);
1533        status_t         setVolume(uint32_t *left, uint32_t *right, bool controller);
1534        status_t         setMode(audio_mode_t mode);
1535        status_t         start();
1536        status_t         stop();
1537        void             setSuspended(bool suspended);
1538        bool             suspended() const;
1539
1540        sp<EffectHandle> controlHandle();
1541
1542        bool             isPinned() const { return mPinned; }
1543        void             unPin() { mPinned = false; }
1544
1545        status_t         dump(int fd, const Vector<String16>& args);
1546
1547    protected:
1548        friend class AudioFlinger;      // for mHandles
1549        bool                mPinned;
1550
1551        // Maximum time allocated to effect engines to complete the turn off sequence
1552        static const uint32_t MAX_DISABLE_TIME_MS = 10000;
1553
1554        EffectModule(const EffectModule&);
1555        EffectModule& operator = (const EffectModule&);
1556
1557        status_t start_l();
1558        status_t stop_l();
1559
1560mutable Mutex               mLock;      // mutex for process, commands and handles list protection
1561        wp<ThreadBase>      mThread;    // parent thread
1562        wp<EffectChain>     mChain;     // parent effect chain
1563        int                 mId;        // this instance unique ID
1564        int                 mSessionId; // audio session ID
1565        effect_descriptor_t mDescriptor;// effect descriptor received from effect engine
1566        effect_config_t     mConfig;    // input and output audio configuration
1567        effect_handle_t  mEffectInterface; // Effect module C API
1568        status_t            mStatus;    // initialization status
1569        effect_state        mState;     // current activation state
1570        Vector< wp<EffectHandle> > mHandles;    // list of client handles
1571                    // First handle in mHandles has highest priority and controls the effect module
1572        uint32_t mMaxDisableWaitCnt;    // maximum grace period before forcing an effect off after
1573                                        // sending disable command.
1574        uint32_t mDisableWaitCnt;       // current process() calls count during disable period.
1575        bool     mSuspended;            // effect is suspended: temporarily disabled by framework
1576    };
1577
1578    // The EffectHandle class implements the IEffect interface. It provides resources
1579    // to receive parameter updates, keeps track of effect control
1580    // ownership and state and has a pointer to the EffectModule object it is controlling.
1581    // There is one EffectHandle object for each application controlling (or using)
1582    // an effect module.
1583    // The EffectHandle is obtained by calling AudioFlinger::createEffect().
1584    class EffectHandle: public android::BnEffect {
1585    public:
1586
1587        EffectHandle(const sp<EffectModule>& effect,
1588                const sp<AudioFlinger::Client>& client,
1589                const sp<IEffectClient>& effectClient,
1590                int32_t priority);
1591        virtual ~EffectHandle();
1592
1593        // IEffect
1594        virtual status_t enable();
1595        virtual status_t disable();
1596        virtual status_t command(uint32_t cmdCode,
1597                                 uint32_t cmdSize,
1598                                 void *pCmdData,
1599                                 uint32_t *replySize,
1600                                 void *pReplyData);
1601        virtual void disconnect();
1602    private:
1603                void disconnect(bool unpinIfLast);
1604    public:
1605        virtual sp<IMemory> getCblk() const { return mCblkMemory; }
1606        virtual status_t onTransact(uint32_t code, const Parcel& data,
1607                Parcel* reply, uint32_t flags);
1608
1609
1610        // Give or take control of effect module
1611        // - hasControl: true if control is given, false if removed
1612        // - signal: true client app should be signaled of change, false otherwise
1613        // - enabled: state of the effect when control is passed
1614        void setControl(bool hasControl, bool signal, bool enabled);
1615        void commandExecuted(uint32_t cmdCode,
1616                             uint32_t cmdSize,
1617                             void *pCmdData,
1618                             uint32_t replySize,
1619                             void *pReplyData);
1620        void setEnabled(bool enabled);
1621        bool enabled() const { return mEnabled; }
1622
1623        // Getters
1624        int id() const { return mEffect->id(); }
1625        int priority() const { return mPriority; }
1626        bool hasControl() const { return mHasControl; }
1627        sp<EffectModule> effect() const { return mEffect; }
1628
1629        void dump(char* buffer, size_t size);
1630
1631    protected:
1632        friend class AudioFlinger;          // for mEffect, mHasControl, mEnabled
1633        EffectHandle(const EffectHandle&);
1634        EffectHandle& operator =(const EffectHandle&);
1635
1636        sp<EffectModule> mEffect;           // pointer to controlled EffectModule
1637        sp<IEffectClient> mEffectClient;    // callback interface for client notifications
1638        /*const*/ sp<Client> mClient;       // client for shared memory allocation, see disconnect()
1639        sp<IMemory>         mCblkMemory;    // shared memory for control block
1640        effect_param_cblk_t* mCblk;         // control block for deferred parameter setting via shared memory
1641        uint8_t*            mBuffer;        // pointer to parameter area in shared memory
1642        int mPriority;                      // client application priority to control the effect
1643        bool mHasControl;                   // true if this handle is controlling the effect
1644        bool mEnabled;                      // cached enable state: needed when the effect is
1645                                            // restored after being suspended
1646    };
1647
1648    // the EffectChain class represents a group of effects associated to one audio session.
1649    // There can be any number of EffectChain objects per output mixer thread (PlaybackThread).
1650    // The EffecChain with session ID 0 contains global effects applied to the output mix.
1651    // Effects in this chain can be insert or auxiliary. Effects in other chains (attached to tracks)
1652    // are insert only. The EffectChain maintains an ordered list of effect module, the order corresponding
1653    // in the effect process order. When attached to a track (session ID != 0), it also provide it's own
1654    // input buffer used by the track as accumulation buffer.
1655    class EffectChain: public RefBase {
1656    public:
1657        EffectChain(const wp<ThreadBase>& wThread, int sessionId);
1658        EffectChain(ThreadBase *thread, int sessionId);
1659        virtual ~EffectChain();
1660
1661        // special key used for an entry in mSuspendedEffects keyed vector
1662        // corresponding to a suspend all request.
1663        static const int        kKeyForSuspendAll = 0;
1664
1665        // minimum duration during which we force calling effect process when last track on
1666        // a session is stopped or removed to allow effect tail to be rendered
1667        static const int        kProcessTailDurationMs = 1000;
1668
1669        void process_l();
1670
1671        void lock() {
1672            mLock.lock();
1673        }
1674        void unlock() {
1675            mLock.unlock();
1676        }
1677
1678        status_t addEffect_l(const sp<EffectModule>& handle);
1679        size_t removeEffect_l(const sp<EffectModule>& handle);
1680
1681        int sessionId() const { return mSessionId; }
1682        void setSessionId(int sessionId) { mSessionId = sessionId; }
1683
1684        sp<EffectModule> getEffectFromDesc_l(effect_descriptor_t *descriptor);
1685        sp<EffectModule> getEffectFromId_l(int id);
1686        sp<EffectModule> getEffectFromType_l(const effect_uuid_t *type);
1687        bool setVolume_l(uint32_t *left, uint32_t *right);
1688        void setDevice_l(uint32_t device);
1689        void setMode_l(audio_mode_t mode);
1690
1691        void setInBuffer(int16_t *buffer, bool ownsBuffer = false) {
1692            mInBuffer = buffer;
1693            mOwnInBuffer = ownsBuffer;
1694        }
1695        int16_t *inBuffer() const {
1696            return mInBuffer;
1697        }
1698        void setOutBuffer(int16_t *buffer) {
1699            mOutBuffer = buffer;
1700        }
1701        int16_t *outBuffer() const {
1702            return mOutBuffer;
1703        }
1704
1705        void incTrackCnt() { android_atomic_inc(&mTrackCnt); }
1706        void decTrackCnt() { android_atomic_dec(&mTrackCnt); }
1707        int32_t trackCnt() const { return mTrackCnt;}
1708
1709        void incActiveTrackCnt() { android_atomic_inc(&mActiveTrackCnt);
1710                                   mTailBufferCount = mMaxTailBuffers; }
1711        void decActiveTrackCnt() { android_atomic_dec(&mActiveTrackCnt); }
1712        int32_t activeTrackCnt() const { return mActiveTrackCnt;}
1713
1714        uint32_t strategy() const { return mStrategy; }
1715        void setStrategy(uint32_t strategy)
1716                { mStrategy = strategy; }
1717
1718        // suspend effect of the given type
1719        void setEffectSuspended_l(const effect_uuid_t *type,
1720                                  bool suspend);
1721        // suspend all eligible effects
1722        void setEffectSuspendedAll_l(bool suspend);
1723        // check if effects should be suspend or restored when a given effect is enable or disabled
1724        void checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1725                                              bool enabled);
1726
1727        void clearInputBuffer();
1728
1729        status_t dump(int fd, const Vector<String16>& args);
1730
1731    protected:
1732        friend class AudioFlinger;  // for mThread, mEffects
1733        EffectChain(const EffectChain&);
1734        EffectChain& operator =(const EffectChain&);
1735
1736        class SuspendedEffectDesc : public RefBase {
1737        public:
1738            SuspendedEffectDesc() : mRefCount(0) {}
1739
1740            int mRefCount;
1741            effect_uuid_t mType;
1742            wp<EffectModule> mEffect;
1743        };
1744
1745        // get a list of effect modules to suspend when an effect of the type
1746        // passed is enabled.
1747        void                       getSuspendEligibleEffects(Vector< sp<EffectModule> > &effects);
1748
1749        // get an effect module if it is currently enable
1750        sp<EffectModule> getEffectIfEnabled(const effect_uuid_t *type);
1751        // true if the effect whose descriptor is passed can be suspended
1752        // OEMs can modify the rules implemented in this method to exclude specific effect
1753        // types or implementations from the suspend/restore mechanism.
1754        bool isEffectEligibleForSuspend(const effect_descriptor_t& desc);
1755
1756        void clearInputBuffer_l(sp<ThreadBase> thread);
1757
1758        wp<ThreadBase> mThread;     // parent mixer thread
1759        Mutex mLock;                // mutex protecting effect list
1760        Vector< sp<EffectModule> > mEffects; // list of effect modules
1761        int mSessionId;             // audio session ID
1762        int16_t *mInBuffer;         // chain input buffer
1763        int16_t *mOutBuffer;        // chain output buffer
1764        volatile int32_t mActiveTrackCnt;  // number of active tracks connected
1765        volatile int32_t mTrackCnt;        // number of tracks connected
1766        int32_t mTailBufferCount;   // current effect tail buffer count
1767        int32_t mMaxTailBuffers;    // maximum effect tail buffers
1768        bool mOwnInBuffer;          // true if the chain owns its input buffer
1769        int mVolumeCtrlIdx;         // index of insert effect having control over volume
1770        uint32_t mLeftVolume;       // previous volume on left channel
1771        uint32_t mRightVolume;      // previous volume on right channel
1772        uint32_t mNewLeftVolume;       // new volume on left channel
1773        uint32_t mNewRightVolume;      // new volume on right channel
1774        uint32_t mStrategy; // strategy for this effect chain
1775        // mSuspendedEffects lists all effects currently suspended in the chain.
1776        // Use effect type UUID timelow field as key. There is no real risk of identical
1777        // timeLow fields among effect type UUIDs.
1778        // Updated by updateSuspendedSessions_l() only.
1779        KeyedVector< int, sp<SuspendedEffectDesc> > mSuspendedEffects;
1780    };
1781
1782    // AudioStreamOut and AudioStreamIn are immutable, so their fields are const.
1783    // For emphasis, we could also make all pointers to them be "const *",
1784    // but that would clutter the code unnecessarily.
1785
1786    struct AudioStreamOut {
1787        audio_hw_device_t*  const hwDev;
1788        audio_stream_out_t* const stream;
1789
1790        AudioStreamOut(audio_hw_device_t *dev, audio_stream_out_t *out) :
1791            hwDev(dev), stream(out) {}
1792    };
1793
1794    struct AudioStreamIn {
1795        audio_hw_device_t* const hwDev;
1796        audio_stream_in_t* const stream;
1797
1798        AudioStreamIn(audio_hw_device_t *dev, audio_stream_in_t *in) :
1799            hwDev(dev), stream(in) {}
1800    };
1801
1802    // for mAudioSessionRefs only
1803    struct AudioSessionRef {
1804        AudioSessionRef(int sessionid, pid_t pid) :
1805            mSessionid(sessionid), mPid(pid), mCnt(1) {}
1806        const int   mSessionid;
1807        const pid_t mPid;
1808        int         mCnt;
1809    };
1810
1811    enum master_volume_support {
1812        // MVS_NONE:
1813        // Audio HAL has no support for master volume, either setting or
1814        // getting.  All master volume control must be implemented in SW by the
1815        // AudioFlinger mixing core.
1816        MVS_NONE,
1817
1818        // MVS_SETONLY:
1819        // Audio HAL has support for setting master volume, but not for getting
1820        // master volume (original HAL design did not include a getter).
1821        // AudioFlinger needs to keep track of the last set master volume in
1822        // addition to needing to set an initial, default, master volume at HAL
1823        // load time.
1824        MVS_SETONLY,
1825
1826        // MVS_FULL:
1827        // Audio HAL has support both for setting and getting master volume.
1828        // AudioFlinger should send all set and get master volume requests
1829        // directly to the HAL.
1830        MVS_FULL,
1831    };
1832
1833    class AudioHwDevice {
1834    public:
1835        AudioHwDevice(const char *moduleName, audio_hw_device_t *hwDevice) :
1836            mModuleName(strdup(moduleName)), mHwDevice(hwDevice){}
1837        ~AudioHwDevice() { free((void *)mModuleName); }
1838
1839        const char *moduleName() const { return mModuleName; }
1840        audio_hw_device_t *hwDevice() const { return mHwDevice; }
1841    private:
1842        const char * const mModuleName;
1843        audio_hw_device_t * const mHwDevice;
1844    };
1845
1846    mutable     Mutex                               mLock;
1847
1848                DefaultKeyedVector< pid_t, wp<Client> >     mClients;   // see ~Client()
1849
1850                mutable     Mutex                   mHardwareLock;
1851                // NOTE: If both mLock and mHardwareLock mutexes must be held,
1852                // always take mLock before mHardwareLock
1853
1854                // These two fields are immutable after onFirstRef(), so no lock needed to access
1855                audio_hw_device_t*                  mPrimaryHardwareDev; // mAudioHwDevs[0] or NULL
1856                DefaultKeyedVector<audio_module_handle_t, AudioHwDevice*>  mAudioHwDevs;
1857
1858    // for dump, indicates which hardware operation is currently in progress (but not stream ops)
1859    enum hardware_call_state {
1860        AUDIO_HW_IDLE = 0,              // no operation in progress
1861        AUDIO_HW_INIT,                  // init_check
1862        AUDIO_HW_OUTPUT_OPEN,           // open_output_stream
1863        AUDIO_HW_OUTPUT_CLOSE,          // unused
1864        AUDIO_HW_INPUT_OPEN,            // unused
1865        AUDIO_HW_INPUT_CLOSE,           // unused
1866        AUDIO_HW_STANDBY,               // unused
1867        AUDIO_HW_SET_MASTER_VOLUME,     // set_master_volume
1868        AUDIO_HW_GET_ROUTING,           // unused
1869        AUDIO_HW_SET_ROUTING,           // unused
1870        AUDIO_HW_GET_MODE,              // unused
1871        AUDIO_HW_SET_MODE,              // set_mode
1872        AUDIO_HW_GET_MIC_MUTE,          // get_mic_mute
1873        AUDIO_HW_SET_MIC_MUTE,          // set_mic_mute
1874        AUDIO_HW_SET_VOICE_VOLUME,      // set_voice_volume
1875        AUDIO_HW_SET_PARAMETER,         // set_parameters
1876        AUDIO_HW_GET_INPUT_BUFFER_SIZE, // get_input_buffer_size
1877        AUDIO_HW_GET_MASTER_VOLUME,     // get_master_volume
1878        AUDIO_HW_GET_PARAMETER,         // get_parameters
1879    };
1880
1881    mutable     hardware_call_state                 mHardwareStatus;    // for dump only
1882
1883
1884                DefaultKeyedVector< audio_io_handle_t, sp<PlaybackThread> >  mPlaybackThreads;
1885                stream_type_t                       mStreamTypes[AUDIO_STREAM_CNT];
1886
1887                // both are protected by mLock
1888                float                               mMasterVolume;
1889                float                               mMasterVolumeSW;
1890                master_volume_support               mMasterVolumeSupportLvl;
1891                bool                                mMasterMute;
1892
1893                DefaultKeyedVector< audio_io_handle_t, sp<RecordThread> >    mRecordThreads;
1894
1895                DefaultKeyedVector< pid_t, sp<NotificationClient> >    mNotificationClients;
1896                volatile int32_t                    mNextUniqueId;  // updated by android_atomic_inc
1897                audio_mode_t                        mMode;
1898                bool                                mBtNrecIsOff;
1899
1900                // protected by mLock
1901                Vector<AudioSessionRef*> mAudioSessionRefs;
1902
1903                float       masterVolume_l() const;
1904                float       masterVolumeSW_l() const  { return mMasterVolumeSW; }
1905                bool        masterMute_l() const    { return mMasterMute; }
1906                audio_module_handle_t loadHwModule_l(const char *name);
1907
1908                Vector < sp<SyncEvent> > mPendingSyncEvents; // sync events awaiting for a session
1909                                                             // to be created
1910
1911private:
1912    sp<Client>  registerPid_l(pid_t pid);    // always returns non-0
1913
1914};
1915
1916
1917// ----------------------------------------------------------------------------
1918
1919}; // namespace android
1920
1921#endif // ANDROID_AUDIO_FLINGER_H
1922