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