AudioFlinger.h revision 91de9b56282d126ffb36344266af5fee3cefcfdd
1/*
2**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9**     http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18#ifndef ANDROID_AUDIO_FLINGER_H
19#define ANDROID_AUDIO_FLINGER_H
20
21#include <stdint.h>
22#include <sys/types.h>
23#include <limits.h>
24
25#include <common_time/cc_helper.h>
26
27#include <media/IAudioFlinger.h>
28#include <media/IAudioFlingerClient.h>
29#include <media/IAudioTrack.h>
30#include <media/IAudioRecord.h>
31#include <media/AudioSystem.h>
32#include <media/AudioTrack.h>
33
34#include <utils/Atomic.h>
35#include <utils/Errors.h>
36#include <utils/threads.h>
37#include <utils/SortedVector.h>
38#include <utils/TypeHelpers.h>
39#include <utils/Vector.h>
40
41#include <binder/BinderService.h>
42#include <binder/MemoryDealer.h>
43
44#include <system/audio.h>
45#include <hardware/audio.h>
46#include <hardware/audio_policy.h>
47
48#include "AudioBufferProvider.h"
49#include "ExtendedAudioBufferProvider.h"
50#include "FastMixer.h"
51#include "NBAIO.h"
52#include "AudioWatchdog.h"
53
54#include <powermanager/IPowerManager.h>
55
56namespace android {
57
58class audio_track_cblk_t;
59class effect_param_cblk_t;
60class AudioMixer;
61class AudioBuffer;
62class AudioResampler;
63class FastMixer;
64
65// ----------------------------------------------------------------------------
66
67// AudioFlinger has a hard-coded upper limit of 2 channels for capture and playback.
68// There is support for > 2 channel tracks down-mixed to 2 channel output via a down-mix effect.
69// Adding full support for > 2 channel capture or playback would require more than simply changing
70// this #define.  There is an independent hard-coded upper limit in AudioMixer;
71// removing that AudioMixer limit would be necessary but insufficient to support > 2 channels.
72// The macro FCC_2 highlights some (but not all) places where there is are 2-channel assumptions.
73// Search also for "2", "left", "right", "[0]", "[1]", ">> 16", "<< 16", etc.
74#define FCC_2 2     // FCC_2 = Fixed Channel Count 2
75
76static const nsecs_t kDefaultStandbyTimeInNsecs = seconds(3);
77
78class AudioFlinger :
79    public BinderService<AudioFlinger>,
80    public BnAudioFlinger
81{
82    friend class BinderService<AudioFlinger>;   // for AudioFlinger()
83public:
84    static const char* getServiceName() { return "media.audio_flinger"; }
85
86    virtual     status_t    dump(int fd, const Vector<String16>& args);
87
88    // IAudioFlinger interface, in binder opcode order
89    virtual sp<IAudioTrack> createTrack(
90                                pid_t pid,
91                                audio_stream_type_t streamType,
92                                uint32_t sampleRate,
93                                audio_format_t format,
94                                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     float       masterVolumeSW() const;
126    virtual     bool        masterMute() const;
127    virtual     bool        masterMuteSW() const;
128
129    virtual     status_t    setStreamVolume(audio_stream_type_t stream, float value,
130                                            audio_io_handle_t output);
131    virtual     status_t    setStreamMute(audio_stream_type_t stream, bool muted);
132
133    virtual     float       streamVolume(audio_stream_type_t stream,
134                                         audio_io_handle_t output) const;
135    virtual     bool        streamMute(audio_stream_type_t stream) const;
136
137    virtual     status_t    setMode(audio_mode_t mode);
138
139    virtual     status_t    setMicMute(bool state);
140    virtual     bool        getMicMute() const;
141
142    virtual     status_t    setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs);
143    virtual     String8     getParameters(audio_io_handle_t ioHandle, const String8& keys) const;
144
145    virtual     void        registerClient(const sp<IAudioFlingerClient>& client);
146
147    virtual     size_t      getInputBufferSize(uint32_t sampleRate, audio_format_t format,
148                                               audio_channel_mask_t channelMask) const;
149
150    virtual audio_io_handle_t openOutput(audio_module_handle_t module,
151                                         audio_devices_t *pDevices,
152                                         uint32_t *pSamplingRate,
153                                         audio_format_t *pFormat,
154                                         audio_channel_mask_t *pChannelMask,
155                                         uint32_t *pLatencyMs,
156                                         audio_output_flags_t flags);
157
158    virtual audio_io_handle_t openDuplicateOutput(audio_io_handle_t output1,
159                                                  audio_io_handle_t output2);
160
161    virtual status_t closeOutput(audio_io_handle_t output);
162
163    virtual status_t suspendOutput(audio_io_handle_t output);
164
165    virtual status_t restoreOutput(audio_io_handle_t output);
166
167    virtual audio_io_handle_t openInput(audio_module_handle_t module,
168                                        audio_devices_t *pDevices,
169                                        uint32_t *pSamplingRate,
170                                        audio_format_t *pFormat,
171                                        audio_channel_mask_t *pChannelMask);
172
173    virtual status_t closeInput(audio_io_handle_t input);
174
175    virtual status_t setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output);
176
177    virtual status_t setVoiceVolume(float volume);
178
179    virtual status_t getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
180                                       audio_io_handle_t output) const;
181
182    virtual     unsigned int  getInputFramesLost(audio_io_handle_t ioHandle) const;
183
184    virtual int newAudioSessionId();
185
186    virtual void acquireAudioSessionId(int audioSession);
187
188    virtual void releaseAudioSessionId(int audioSession);
189
190    virtual status_t queryNumberEffects(uint32_t *numEffects) const;
191
192    virtual status_t queryEffect(uint32_t index, effect_descriptor_t *descriptor) const;
193
194    virtual status_t getEffectDescriptor(const effect_uuid_t *pUuid,
195                                         effect_descriptor_t *descriptor) const;
196
197    virtual sp<IEffect> createEffect(pid_t pid,
198                        effect_descriptor_t *pDesc,
199                        const sp<IEffectClient>& effectClient,
200                        int32_t priority,
201                        audio_io_handle_t io,
202                        int sessionId,
203                        status_t *status,
204                        int *id,
205                        int *enabled);
206
207    virtual status_t moveEffects(int sessionId, audio_io_handle_t srcOutput,
208                        audio_io_handle_t dstOutput);
209
210    virtual audio_module_handle_t loadHwModule(const char *name);
211
212    virtual     status_t    onTransact(
213                                uint32_t code,
214                                const Parcel& data,
215                                Parcel* reply,
216                                uint32_t flags);
217
218    // end of IAudioFlinger interface
219
220    class SyncEvent;
221
222    typedef void (*sync_event_callback_t)(const wp<SyncEvent>& event) ;
223
224    class SyncEvent : public RefBase {
225    public:
226        SyncEvent(AudioSystem::sync_event_t type,
227                  int triggerSession,
228                  int listenerSession,
229                  sync_event_callback_t callBack,
230                  void *cookie)
231        : mType(type), mTriggerSession(triggerSession), mListenerSession(listenerSession),
232          mCallback(callBack), mCookie(cookie)
233        {}
234
235        virtual ~SyncEvent() {}
236
237        void trigger() { Mutex::Autolock _l(mLock); if (mCallback) mCallback(this); }
238        bool isCancelled() { Mutex::Autolock _l(mLock); return (mCallback == NULL); }
239        void cancel() {Mutex::Autolock _l(mLock); mCallback = NULL; }
240        AudioSystem::sync_event_t type() const { return mType; }
241        int triggerSession() const { return mTriggerSession; }
242        int listenerSession() const { return mListenerSession; }
243        void *cookie() const { return mCookie; }
244
245    private:
246          const AudioSystem::sync_event_t mType;
247          const int mTriggerSession;
248          const int mListenerSession;
249          sync_event_callback_t mCallback;
250          void * const mCookie;
251          Mutex mLock;
252    };
253
254    sp<SyncEvent> createSyncEvent(AudioSystem::sync_event_t type,
255                                        int triggerSession,
256                                        int listenerSession,
257                                        sync_event_callback_t callBack,
258                                        void *cookie);
259
260private:
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    audio_hw_device_t*      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);
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) = 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) = 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);
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);
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                    // clear the buffer overflow flag
1386                    void        clearOverflow() { mOverflow = false; }
1387                    // set the buffer overflow flag and return previous value
1388                    bool        setOverflow() { bool tmp = mOverflow; mOverflow = true; return tmp; }
1389
1390                    void        dump(char* buffer, size_t size);
1391
1392        private:
1393            friend class AudioFlinger;  // for mState
1394
1395                                RecordTrack(const RecordTrack&);
1396                                RecordTrack& operator = (const RecordTrack&);
1397
1398            // AudioBufferProvider interface
1399            virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts = kInvalidPTS);
1400            // releaseBuffer() not overridden
1401
1402            bool                mOverflow;  // overflow on most recent attempt to fill client buffer
1403        };
1404
1405                RecordThread(const sp<AudioFlinger>& audioFlinger,
1406                        AudioStreamIn *input,
1407                        uint32_t sampleRate,
1408                        audio_channel_mask_t channelMask,
1409                        audio_io_handle_t id,
1410                        audio_devices_t device);
1411                virtual     ~RecordThread();
1412
1413        // Thread
1414        virtual bool        threadLoop();
1415        virtual status_t    readyToRun();
1416
1417        // RefBase
1418        virtual void        onFirstRef();
1419
1420        virtual status_t    initCheck() const { return (mInput == NULL) ? NO_INIT : NO_ERROR; }
1421                sp<AudioFlinger::RecordThread::RecordTrack>  createRecordTrack_l(
1422                        const sp<AudioFlinger::Client>& client,
1423                        uint32_t sampleRate,
1424                        audio_format_t format,
1425                        audio_channel_mask_t channelMask,
1426                        int frameCount,
1427                        int sessionId,
1428                        IAudioFlinger::track_flags_t flags,
1429                        pid_t tid,
1430                        status_t *status);
1431
1432                status_t    start(RecordTrack* recordTrack,
1433                                  AudioSystem::sync_event_t event,
1434                                  int triggerSession);
1435
1436                // ask the thread to stop the specified track, and
1437                // return true if the caller should then do it's part of the stopping process
1438                bool        stop_l(RecordTrack* recordTrack);
1439
1440                void        dump(int fd, const Vector<String16>& args);
1441                AudioStreamIn* clearInput();
1442                virtual audio_stream_t* stream() const;
1443
1444        // AudioBufferProvider interface
1445        virtual status_t    getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts);
1446        virtual void        releaseBuffer(AudioBufferProvider::Buffer* buffer);
1447
1448        virtual bool        checkForNewParameters_l();
1449        virtual String8     getParameters(const String8& keys);
1450        virtual void        audioConfigChanged_l(int event, int param = 0);
1451                void        readInputParameters();
1452        virtual unsigned int  getInputFramesLost();
1453
1454        virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
1455        virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
1456        virtual uint32_t hasAudioSession(int sessionId);
1457                RecordTrack* track();
1458
1459        virtual status_t setSyncEvent(const sp<SyncEvent>& event);
1460        virtual bool     isValidSyncEvent(const sp<SyncEvent>& event);
1461
1462        static void syncStartEventCallback(const wp<SyncEvent>& event);
1463               void handleSyncStartEvent(const sp<SyncEvent>& event);
1464
1465    private:
1466                void clearSyncStartEvent();
1467
1468                // Enter standby if not already in standby, and set mStandby flag
1469                void standby();
1470
1471                // Call the HAL standby method unconditionally, and don't change mStandby flag
1472                void inputStandBy();
1473
1474                AudioStreamIn                       *mInput;
1475                RecordTrack*                        mTrack;
1476                sp<RecordTrack>                     mActiveTrack;
1477                Condition                           mStartStopCond;
1478                AudioResampler                      *mResampler;
1479                int32_t                             *mRsmpOutBuffer;
1480                int16_t                             *mRsmpInBuffer;
1481                size_t                              mRsmpInIndex;
1482                size_t                              mInputBytes;
1483                const int                           mReqChannelCount;
1484                const uint32_t                      mReqSampleRate;
1485                ssize_t                             mBytesRead;
1486                // sync event triggering actual audio capture. Frames read before this event will
1487                // be dropped and therefore not read by the application.
1488                sp<SyncEvent>                       mSyncStartEvent;
1489                // number of captured frames to drop after the start sync event has been received.
1490                // when < 0, maximum frames to drop before starting capture even if sync event is
1491                // not received
1492                ssize_t                             mFramestoDrop;
1493    };
1494
1495    // server side of the client's IAudioRecord
1496    class RecordHandle : public android::BnAudioRecord {
1497    public:
1498        RecordHandle(const sp<RecordThread::RecordTrack>& recordTrack);
1499        virtual             ~RecordHandle();
1500        virtual sp<IMemory> getCblk() const;
1501        virtual status_t    start(int /*AudioSystem::sync_event_t*/ event, int triggerSession);
1502        virtual void        stop();
1503        virtual status_t onTransact(
1504            uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags);
1505    private:
1506        const sp<RecordThread::RecordTrack> mRecordTrack;
1507
1508        // for use from destructor
1509        void                stop_nonvirtual();
1510    };
1511
1512    //--- Audio Effect Management
1513
1514    // EffectModule and EffectChain classes both have their own mutex to protect
1515    // state changes or resource modifications. Always respect the following order
1516    // if multiple mutexes must be acquired to avoid cross deadlock:
1517    // AudioFlinger -> ThreadBase -> EffectChain -> EffectModule
1518
1519    // The EffectModule class is a wrapper object controlling the effect engine implementation
1520    // in the effect library. It prevents concurrent calls to process() and command() functions
1521    // from different client threads. It keeps a list of EffectHandle objects corresponding
1522    // to all client applications using this effect and notifies applications of effect state,
1523    // control or parameter changes. It manages the activation state machine to send appropriate
1524    // reset, enable, disable commands to effect engine and provide volume
1525    // ramping when effects are activated/deactivated.
1526    // When controlling an auxiliary effect, the EffectModule also provides an input buffer used by
1527    // the attached track(s) to accumulate their auxiliary channel.
1528    class EffectModule: public RefBase {
1529    public:
1530        EffectModule(ThreadBase *thread,
1531                        const wp<AudioFlinger::EffectChain>& chain,
1532                        effect_descriptor_t *desc,
1533                        int id,
1534                        int sessionId);
1535        virtual ~EffectModule();
1536
1537        enum effect_state {
1538            IDLE,
1539            RESTART,
1540            STARTING,
1541            ACTIVE,
1542            STOPPING,
1543            STOPPED,
1544            DESTROYED
1545        };
1546
1547        int         id() const { return mId; }
1548        void process();
1549        void updateState();
1550        status_t command(uint32_t cmdCode,
1551                         uint32_t cmdSize,
1552                         void *pCmdData,
1553                         uint32_t *replySize,
1554                         void *pReplyData);
1555
1556        void reset_l();
1557        status_t configure();
1558        status_t init();
1559        effect_state state() const {
1560            return mState;
1561        }
1562        uint32_t status() {
1563            return mStatus;
1564        }
1565        int sessionId() const {
1566            return mSessionId;
1567        }
1568        status_t    setEnabled(bool enabled);
1569        status_t    setEnabled_l(bool enabled);
1570        bool isEnabled() const;
1571        bool isProcessEnabled() const;
1572
1573        void        setInBuffer(int16_t *buffer) { mConfig.inputCfg.buffer.s16 = buffer; }
1574        int16_t     *inBuffer() { return mConfig.inputCfg.buffer.s16; }
1575        void        setOutBuffer(int16_t *buffer) { mConfig.outputCfg.buffer.s16 = buffer; }
1576        int16_t     *outBuffer() { return mConfig.outputCfg.buffer.s16; }
1577        void        setChain(const wp<EffectChain>& chain) { mChain = chain; }
1578        void        setThread(const wp<ThreadBase>& thread) { mThread = thread; }
1579        const wp<ThreadBase>& thread() { return mThread; }
1580
1581        status_t addHandle(EffectHandle *handle);
1582        size_t disconnect(EffectHandle *handle, bool unpinIfLast);
1583        size_t removeHandle(EffectHandle *handle);
1584
1585        const effect_descriptor_t& desc() const { return mDescriptor; }
1586        wp<EffectChain>&     chain() { return mChain; }
1587
1588        status_t         setDevice(audio_devices_t device);
1589        status_t         setVolume(uint32_t *left, uint32_t *right, bool controller);
1590        status_t         setMode(audio_mode_t mode);
1591        status_t         start();
1592        status_t         stop();
1593        void             setSuspended(bool suspended);
1594        bool             suspended() const;
1595
1596        EffectHandle*    controlHandle_l();
1597
1598        bool             isPinned() const { return mPinned; }
1599        void             unPin() { mPinned = false; }
1600        bool             purgeHandles();
1601        void             lock() { mLock.lock(); }
1602        void             unlock() { mLock.unlock(); }
1603
1604        void             dump(int fd, const Vector<String16>& args);
1605
1606    protected:
1607        friend class AudioFlinger;      // for mHandles
1608        bool                mPinned;
1609
1610        // Maximum time allocated to effect engines to complete the turn off sequence
1611        static const uint32_t MAX_DISABLE_TIME_MS = 10000;
1612
1613        EffectModule(const EffectModule&);
1614        EffectModule& operator = (const EffectModule&);
1615
1616        status_t start_l();
1617        status_t stop_l();
1618
1619mutable Mutex               mLock;      // mutex for process, commands and handles list protection
1620        wp<ThreadBase>      mThread;    // parent thread
1621        wp<EffectChain>     mChain;     // parent effect chain
1622        const int           mId;        // this instance unique ID
1623        const int           mSessionId; // audio session ID
1624        const effect_descriptor_t mDescriptor;// effect descriptor received from effect engine
1625        effect_config_t     mConfig;    // input and output audio configuration
1626        effect_handle_t  mEffectInterface; // Effect module C API
1627        status_t            mStatus;    // initialization status
1628        effect_state        mState;     // current activation state
1629        Vector<EffectHandle *> mHandles;    // list of client handles
1630                    // First handle in mHandles has highest priority and controls the effect module
1631        uint32_t mMaxDisableWaitCnt;    // maximum grace period before forcing an effect off after
1632                                        // sending disable command.
1633        uint32_t mDisableWaitCnt;       // current process() calls count during disable period.
1634        bool     mSuspended;            // effect is suspended: temporarily disabled by framework
1635    };
1636
1637    // The EffectHandle class implements the IEffect interface. It provides resources
1638    // to receive parameter updates, keeps track of effect control
1639    // ownership and state and has a pointer to the EffectModule object it is controlling.
1640    // There is one EffectHandle object for each application controlling (or using)
1641    // an effect module.
1642    // The EffectHandle is obtained by calling AudioFlinger::createEffect().
1643    class EffectHandle: public android::BnEffect {
1644    public:
1645
1646        EffectHandle(const sp<EffectModule>& effect,
1647                const sp<AudioFlinger::Client>& client,
1648                const sp<IEffectClient>& effectClient,
1649                int32_t priority);
1650        virtual ~EffectHandle();
1651
1652        // IEffect
1653        virtual status_t enable();
1654        virtual status_t disable();
1655        virtual status_t command(uint32_t cmdCode,
1656                                 uint32_t cmdSize,
1657                                 void *pCmdData,
1658                                 uint32_t *replySize,
1659                                 void *pReplyData);
1660        virtual void disconnect();
1661    private:
1662                void disconnect(bool unpinIfLast);
1663    public:
1664        virtual sp<IMemory> getCblk() const { return mCblkMemory; }
1665        virtual status_t onTransact(uint32_t code, const Parcel& data,
1666                Parcel* reply, uint32_t flags);
1667
1668
1669        // Give or take control of effect module
1670        // - hasControl: true if control is given, false if removed
1671        // - signal: true client app should be signaled of change, false otherwise
1672        // - enabled: state of the effect when control is passed
1673        void setControl(bool hasControl, bool signal, bool enabled);
1674        void commandExecuted(uint32_t cmdCode,
1675                             uint32_t cmdSize,
1676                             void *pCmdData,
1677                             uint32_t replySize,
1678                             void *pReplyData);
1679        void setEnabled(bool enabled);
1680        bool enabled() const { return mEnabled; }
1681
1682        // Getters
1683        int id() const { return mEffect->id(); }
1684        int priority() const { return mPriority; }
1685        bool hasControl() const { return mHasControl; }
1686        sp<EffectModule> effect() const { return mEffect; }
1687        // destroyed_l() must be called with the associated EffectModule mLock held
1688        bool destroyed_l() const { return mDestroyed; }
1689
1690        void dump(char* buffer, size_t size);
1691
1692    protected:
1693        friend class AudioFlinger;          // for mEffect, mHasControl, mEnabled
1694        EffectHandle(const EffectHandle&);
1695        EffectHandle& operator =(const EffectHandle&);
1696
1697        sp<EffectModule> mEffect;           // pointer to controlled EffectModule
1698        sp<IEffectClient> mEffectClient;    // callback interface for client notifications
1699        /*const*/ sp<Client> mClient;       // client for shared memory allocation, see disconnect()
1700        sp<IMemory>         mCblkMemory;    // shared memory for control block
1701        effect_param_cblk_t* mCblk;         // control block for deferred parameter setting via shared memory
1702        uint8_t*            mBuffer;        // pointer to parameter area in shared memory
1703        int mPriority;                      // client application priority to control the effect
1704        bool mHasControl;                   // true if this handle is controlling the effect
1705        bool mEnabled;                      // cached enable state: needed when the effect is
1706                                            // restored after being suspended
1707        bool mDestroyed;                    // Set to true by destructor. Access with EffectModule
1708                                            // mLock held
1709    };
1710
1711    // the EffectChain class represents a group of effects associated to one audio session.
1712    // There can be any number of EffectChain objects per output mixer thread (PlaybackThread).
1713    // The EffecChain with session ID 0 contains global effects applied to the output mix.
1714    // Effects in this chain can be insert or auxiliary. Effects in other chains (attached to tracks)
1715    // are insert only. The EffectChain maintains an ordered list of effect module, the order corresponding
1716    // in the effect process order. When attached to a track (session ID != 0), it also provide it's own
1717    // input buffer used by the track as accumulation buffer.
1718    class EffectChain: public RefBase {
1719    public:
1720        EffectChain(const wp<ThreadBase>& wThread, int sessionId);
1721        EffectChain(ThreadBase *thread, int sessionId);
1722        virtual ~EffectChain();
1723
1724        // special key used for an entry in mSuspendedEffects keyed vector
1725        // corresponding to a suspend all request.
1726        static const int        kKeyForSuspendAll = 0;
1727
1728        // minimum duration during which we force calling effect process when last track on
1729        // a session is stopped or removed to allow effect tail to be rendered
1730        static const int        kProcessTailDurationMs = 1000;
1731
1732        void process_l();
1733
1734        void lock() {
1735            mLock.lock();
1736        }
1737        void unlock() {
1738            mLock.unlock();
1739        }
1740
1741        status_t addEffect_l(const sp<EffectModule>& handle);
1742        size_t removeEffect_l(const sp<EffectModule>& handle);
1743
1744        int sessionId() const { return mSessionId; }
1745        void setSessionId(int sessionId) { mSessionId = sessionId; }
1746
1747        sp<EffectModule> getEffectFromDesc_l(effect_descriptor_t *descriptor);
1748        sp<EffectModule> getEffectFromId_l(int id);
1749        sp<EffectModule> getEffectFromType_l(const effect_uuid_t *type);
1750        bool setVolume_l(uint32_t *left, uint32_t *right);
1751        void setDevice_l(audio_devices_t device);
1752        void setMode_l(audio_mode_t mode);
1753
1754        void setInBuffer(int16_t *buffer, bool ownsBuffer = false) {
1755            mInBuffer = buffer;
1756            mOwnInBuffer = ownsBuffer;
1757        }
1758        int16_t *inBuffer() const {
1759            return mInBuffer;
1760        }
1761        void setOutBuffer(int16_t *buffer) {
1762            mOutBuffer = buffer;
1763        }
1764        int16_t *outBuffer() const {
1765            return mOutBuffer;
1766        }
1767
1768        void incTrackCnt() { android_atomic_inc(&mTrackCnt); }
1769        void decTrackCnt() { android_atomic_dec(&mTrackCnt); }
1770        int32_t trackCnt() const { return android_atomic_acquire_load(&mTrackCnt); }
1771
1772        void incActiveTrackCnt() { android_atomic_inc(&mActiveTrackCnt);
1773                                   mTailBufferCount = mMaxTailBuffers; }
1774        void decActiveTrackCnt() { android_atomic_dec(&mActiveTrackCnt); }
1775        int32_t activeTrackCnt() const { return android_atomic_acquire_load(&mActiveTrackCnt); }
1776
1777        uint32_t strategy() const { return mStrategy; }
1778        void setStrategy(uint32_t strategy)
1779                { mStrategy = strategy; }
1780
1781        // suspend effect of the given type
1782        void setEffectSuspended_l(const effect_uuid_t *type,
1783                                  bool suspend);
1784        // suspend all eligible effects
1785        void setEffectSuspendedAll_l(bool suspend);
1786        // check if effects should be suspend or restored when a given effect is enable or disabled
1787        void checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1788                                              bool enabled);
1789
1790        void clearInputBuffer();
1791
1792        void dump(int fd, const Vector<String16>& args);
1793
1794    protected:
1795        friend class AudioFlinger;  // for mThread, mEffects
1796        EffectChain(const EffectChain&);
1797        EffectChain& operator =(const EffectChain&);
1798
1799        class SuspendedEffectDesc : public RefBase {
1800        public:
1801            SuspendedEffectDesc() : mRefCount(0) {}
1802
1803            int mRefCount;
1804            effect_uuid_t mType;
1805            wp<EffectModule> mEffect;
1806        };
1807
1808        // get a list of effect modules to suspend when an effect of the type
1809        // passed is enabled.
1810        void                       getSuspendEligibleEffects(Vector< sp<EffectModule> > &effects);
1811
1812        // get an effect module if it is currently enable
1813        sp<EffectModule> getEffectIfEnabled(const effect_uuid_t *type);
1814        // true if the effect whose descriptor is passed can be suspended
1815        // OEMs can modify the rules implemented in this method to exclude specific effect
1816        // types or implementations from the suspend/restore mechanism.
1817        bool isEffectEligibleForSuspend(const effect_descriptor_t& desc);
1818
1819        void clearInputBuffer_l(sp<ThreadBase> thread);
1820
1821        wp<ThreadBase> mThread;     // parent mixer thread
1822        Mutex mLock;                // mutex protecting effect list
1823        Vector< sp<EffectModule> > mEffects; // list of effect modules
1824        int mSessionId;             // audio session ID
1825        int16_t *mInBuffer;         // chain input buffer
1826        int16_t *mOutBuffer;        // chain output buffer
1827
1828        // 'volatile' here means these are accessed with atomic operations instead of mutex
1829        volatile int32_t mActiveTrackCnt;    // number of active tracks connected
1830        volatile int32_t mTrackCnt;          // number of tracks connected
1831
1832        int32_t mTailBufferCount;   // current effect tail buffer count
1833        int32_t mMaxTailBuffers;    // maximum effect tail buffers
1834        bool mOwnInBuffer;          // true if the chain owns its input buffer
1835        int mVolumeCtrlIdx;         // index of insert effect having control over volume
1836        uint32_t mLeftVolume;       // previous volume on left channel
1837        uint32_t mRightVolume;      // previous volume on right channel
1838        uint32_t mNewLeftVolume;       // new volume on left channel
1839        uint32_t mNewRightVolume;      // new volume on right channel
1840        uint32_t mStrategy; // strategy for this effect chain
1841        // mSuspendedEffects lists all effects currently suspended in the chain.
1842        // Use effect type UUID timelow field as key. There is no real risk of identical
1843        // timeLow fields among effect type UUIDs.
1844        // Updated by updateSuspendedSessions_l() only.
1845        KeyedVector< int, sp<SuspendedEffectDesc> > mSuspendedEffects;
1846    };
1847
1848    // AudioStreamOut and AudioStreamIn are immutable, so their fields are const.
1849    // For emphasis, we could also make all pointers to them be "const *",
1850    // but that would clutter the code unnecessarily.
1851
1852    struct AudioStreamOut {
1853        audio_hw_device_t*  const hwDev;
1854        audio_stream_out_t* const stream;
1855
1856        AudioStreamOut(audio_hw_device_t *dev, audio_stream_out_t *out) :
1857            hwDev(dev), stream(out) {}
1858    };
1859
1860    struct AudioStreamIn {
1861        audio_hw_device_t* const hwDev;
1862        audio_stream_in_t* const stream;
1863
1864        AudioStreamIn(audio_hw_device_t *dev, audio_stream_in_t *in) :
1865            hwDev(dev), stream(in) {}
1866    };
1867
1868    // for mAudioSessionRefs only
1869    struct AudioSessionRef {
1870        AudioSessionRef(int sessionid, pid_t pid) :
1871            mSessionid(sessionid), mPid(pid), mCnt(1) {}
1872        const int   mSessionid;
1873        const pid_t mPid;
1874        int         mCnt;
1875    };
1876
1877    enum master_volume_support {
1878        // MVS_NONE:
1879        // Audio HAL has no support for master volume, either setting or
1880        // getting.  All master volume control must be implemented in SW by the
1881        // AudioFlinger mixing core.
1882        MVS_NONE,
1883
1884        // MVS_SETONLY:
1885        // Audio HAL has support for setting master volume, but not for getting
1886        // master volume (original HAL design did not include a getter).
1887        // AudioFlinger needs to keep track of the last set master volume in
1888        // addition to needing to set an initial, default, master volume at HAL
1889        // load time.
1890        MVS_SETONLY,
1891
1892        // MVS_FULL:
1893        // Audio HAL has support both for setting and getting master volume.
1894        // AudioFlinger should send all set and get master volume requests
1895        // directly to the HAL.
1896        MVS_FULL,
1897    };
1898
1899    enum master_mute_support {
1900        // MMS_NONE:
1901        // Audio HAL has no support for master mute, either setting or getting.
1902        // All master mute control must be implemented in SW by the
1903        // AudioFlinger mixing core.
1904        MMS_NONE,
1905
1906        // MMS_SETONLY:
1907        // Audio HAL has support for setting master mute, but not for getting
1908        // master mute.  AudioFlinger needs to keep track of the last set
1909        // master mute in addition to needing to set an initial, default,
1910        // master mute at HAL load time.
1911        MMS_SETONLY,
1912
1913        // MMS_FULL:
1914        // Audio HAL has support both for setting and getting master mute.
1915        // AudioFlinger should send all set and get master mute requests
1916        // directly to the HAL.
1917        MMS_FULL,
1918    };
1919
1920    class AudioHwDevice {
1921    public:
1922        AudioHwDevice(const char *moduleName, audio_hw_device_t *hwDevice) :
1923            mModuleName(strdup(moduleName)), mHwDevice(hwDevice){}
1924        /*virtual*/ ~AudioHwDevice() { free((void *)mModuleName); }
1925
1926        const char *moduleName() const { return mModuleName; }
1927        audio_hw_device_t *hwDevice() const { return mHwDevice; }
1928    private:
1929        const char * const mModuleName;
1930        audio_hw_device_t * const mHwDevice;
1931    };
1932
1933    mutable     Mutex                               mLock;
1934
1935                DefaultKeyedVector< pid_t, wp<Client> >     mClients;   // see ~Client()
1936
1937                mutable     Mutex                   mHardwareLock;
1938                // NOTE: If both mLock and mHardwareLock mutexes must be held,
1939                // always take mLock before mHardwareLock
1940
1941                // These two fields are immutable after onFirstRef(), so no lock needed to access
1942                audio_hw_device_t*                  mPrimaryHardwareDev; // mAudioHwDevs[0] or NULL
1943                DefaultKeyedVector<audio_module_handle_t, AudioHwDevice*>  mAudioHwDevs;
1944
1945    // for dump, indicates which hardware operation is currently in progress (but not stream ops)
1946    enum hardware_call_state {
1947        AUDIO_HW_IDLE = 0,              // no operation in progress
1948        AUDIO_HW_INIT,                  // init_check
1949        AUDIO_HW_OUTPUT_OPEN,           // open_output_stream
1950        AUDIO_HW_OUTPUT_CLOSE,          // unused
1951        AUDIO_HW_INPUT_OPEN,            // unused
1952        AUDIO_HW_INPUT_CLOSE,           // unused
1953        AUDIO_HW_STANDBY,               // unused
1954        AUDIO_HW_SET_MASTER_VOLUME,     // set_master_volume
1955        AUDIO_HW_GET_ROUTING,           // unused
1956        AUDIO_HW_SET_ROUTING,           // unused
1957        AUDIO_HW_GET_MODE,              // unused
1958        AUDIO_HW_SET_MODE,              // set_mode
1959        AUDIO_HW_GET_MIC_MUTE,          // get_mic_mute
1960        AUDIO_HW_SET_MIC_MUTE,          // set_mic_mute
1961        AUDIO_HW_SET_VOICE_VOLUME,      // set_voice_volume
1962        AUDIO_HW_SET_PARAMETER,         // set_parameters
1963        AUDIO_HW_GET_INPUT_BUFFER_SIZE, // get_input_buffer_size
1964        AUDIO_HW_GET_MASTER_VOLUME,     // get_master_volume
1965        AUDIO_HW_GET_PARAMETER,         // get_parameters
1966        AUDIO_HW_SET_MASTER_MUTE,       // set_master_mute
1967        AUDIO_HW_GET_MASTER_MUTE,       // get_master_mute
1968    };
1969
1970    mutable     hardware_call_state                 mHardwareStatus;    // for dump only
1971
1972
1973                DefaultKeyedVector< audio_io_handle_t, sp<PlaybackThread> >  mPlaybackThreads;
1974                stream_type_t                       mStreamTypes[AUDIO_STREAM_CNT];
1975
1976                // both are protected by mLock
1977                float                               mMasterVolume;
1978                float                               mMasterVolumeSW;
1979                master_volume_support               mMasterVolumeSupportLvl;
1980
1981                bool                                mMasterMute;
1982                bool                                mMasterMuteSW;
1983                master_mute_support                 mMasterMuteSupportLvl;
1984
1985                DefaultKeyedVector< audio_io_handle_t, sp<RecordThread> >    mRecordThreads;
1986
1987                DefaultKeyedVector< pid_t, sp<NotificationClient> >    mNotificationClients;
1988                volatile int32_t                    mNextUniqueId;  // updated by android_atomic_inc
1989                audio_mode_t                        mMode;
1990                bool                                mBtNrecIsOff;
1991
1992                // protected by mLock
1993                Vector<AudioSessionRef*> mAudioSessionRefs;
1994
1995                float       masterVolume_l() const;
1996                float       masterVolumeSW_l() const  { return mMasterVolumeSW; }
1997                bool        masterMute_l() const;
1998                bool        masterMuteSW_l() const    { return mMasterMuteSW; }
1999                audio_module_handle_t loadHwModule_l(const char *name);
2000
2001                Vector < sp<SyncEvent> > mPendingSyncEvents; // sync events awaiting for a session
2002                                                             // to be created
2003
2004private:
2005    sp<Client>  registerPid_l(pid_t pid);    // always returns non-0
2006
2007    // for use from destructor
2008    status_t    closeOutput_nonvirtual(audio_io_handle_t output);
2009    status_t    closeInput_nonvirtual(audio_io_handle_t input);
2010};
2011
2012
2013// ----------------------------------------------------------------------------
2014
2015}; // namespace android
2016
2017#endif // ANDROID_AUDIO_FLINGER_H
2018