AudioFlinger.h revision b28686f95daee16edeb5f39af2cd5274ac3dc99f
1/* //device/include/server/AudioFlinger/AudioFlinger.h
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 <media/IAudioFlinger.h>
26#include <media/IAudioFlingerClient.h>
27#include <media/IAudioTrack.h>
28#include <media/IAudioRecord.h>
29#include <media/AudioSystem.h>
30
31#include <utils/Atomic.h>
32#include <utils/Errors.h>
33#include <utils/threads.h>
34#include <utils/SortedVector.h>
35#include <utils/TypeHelpers.h>
36#include <utils/Vector.h>
37
38#include <binder/BinderService.h>
39#include <binder/MemoryDealer.h>
40
41#include <system/audio.h>
42#include <hardware/audio.h>
43
44#include "AudioBufferProvider.h"
45
46#include <powermanager/IPowerManager.h>
47
48namespace android {
49
50class audio_track_cblk_t;
51class effect_param_cblk_t;
52class AudioMixer;
53class AudioBuffer;
54class AudioResampler;
55
56// ----------------------------------------------------------------------------
57
58static const nsecs_t kStandbyTimeInNsecs = seconds(3);
59
60class AudioFlinger :
61    public BinderService<AudioFlinger>,
62    public BnAudioFlinger
63{
64    friend class BinderService<AudioFlinger>;
65public:
66    static const char* getServiceName() { return "media.audio_flinger"; }
67
68    virtual     status_t    dump(int fd, const Vector<String16>& args);
69
70    // IAudioFlinger interface
71    virtual sp<IAudioTrack> createTrack(
72                                pid_t pid,
73                                audio_stream_type_t streamType,
74                                uint32_t sampleRate,
75                                audio_format_t format,
76                                uint32_t channelMask,
77                                int frameCount,
78                                uint32_t flags,
79                                const sp<IMemory>& sharedBuffer,
80                                audio_io_handle_t output,
81                                int *sessionId,
82                                status_t *status);
83
84    virtual     uint32_t    sampleRate(audio_io_handle_t output) const;
85    virtual     int         channelCount(audio_io_handle_t output) const;
86    virtual     audio_format_t format(audio_io_handle_t output) const;
87    virtual     size_t      frameCount(audio_io_handle_t output) const;
88    virtual     uint32_t    latency(audio_io_handle_t output) const;
89
90    virtual     status_t    setMasterVolume(float value);
91    virtual     status_t    setMasterMute(bool muted);
92
93    virtual     float       masterVolume() const;
94    virtual     bool        masterMute() const;
95
96    virtual     status_t    setStreamVolume(audio_stream_type_t stream, float value,
97                                            audio_io_handle_t output);
98    virtual     status_t    setStreamMute(audio_stream_type_t stream, bool muted);
99
100    virtual     float       streamVolume(audio_stream_type_t stream,
101                                         audio_io_handle_t output) const;
102    virtual     bool        streamMute(audio_stream_type_t stream) const;
103
104    virtual     status_t    setMode(audio_mode_t mode);
105
106    virtual     status_t    setMicMute(bool state);
107    virtual     bool        getMicMute() const;
108
109    virtual     status_t    setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs);
110    virtual     String8     getParameters(audio_io_handle_t ioHandle, const String8& keys) const;
111
112    virtual     void        registerClient(const sp<IAudioFlingerClient>& client);
113
114    virtual     size_t      getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const;
115    virtual     unsigned int  getInputFramesLost(audio_io_handle_t ioHandle) const;
116
117    virtual audio_io_handle_t openOutput(uint32_t *pDevices,
118                                    uint32_t *pSamplingRate,
119                                    audio_format_t *pFormat,
120                                    uint32_t *pChannels,
121                                    uint32_t *pLatencyMs,
122                                    uint32_t flags);
123
124    virtual audio_io_handle_t openDuplicateOutput(audio_io_handle_t output1,
125                                                  audio_io_handle_t output2);
126
127    virtual status_t closeOutput(audio_io_handle_t output);
128
129    virtual status_t suspendOutput(audio_io_handle_t output);
130
131    virtual status_t restoreOutput(audio_io_handle_t output);
132
133    virtual audio_io_handle_t openInput(uint32_t *pDevices,
134                            uint32_t *pSamplingRate,
135                            audio_format_t *pFormat,
136                            uint32_t *pChannels,
137                            audio_in_acoustics_t acoustics);
138
139    virtual status_t closeInput(audio_io_handle_t input);
140
141    virtual status_t setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output);
142
143    virtual status_t setVoiceVolume(float volume);
144
145    virtual status_t getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
146                                       audio_io_handle_t output) const;
147
148    virtual int newAudioSessionId();
149
150    virtual void acquireAudioSessionId(int audioSession);
151
152    virtual void releaseAudioSessionId(int audioSession);
153
154    virtual status_t queryNumberEffects(uint32_t *numEffects) const;
155
156    virtual status_t queryEffect(uint32_t index, effect_descriptor_t *descriptor) const;
157
158    virtual status_t getEffectDescriptor(const effect_uuid_t *pUuid,
159                                         effect_descriptor_t *descriptor) const;
160
161    virtual sp<IEffect> createEffect(pid_t pid,
162                        effect_descriptor_t *pDesc,
163                        const sp<IEffectClient>& effectClient,
164                        int32_t priority,
165                        audio_io_handle_t io,
166                        int sessionId,
167                        status_t *status,
168                        int *id,
169                        int *enabled);
170
171    virtual status_t moveEffects(int sessionId, audio_io_handle_t srcOutput,
172                        audio_io_handle_t dstOutput);
173
174    enum hardware_call_state {
175        AUDIO_HW_IDLE = 0,
176        AUDIO_HW_INIT,
177        AUDIO_HW_OUTPUT_OPEN,
178        AUDIO_HW_OUTPUT_CLOSE,
179        AUDIO_HW_INPUT_OPEN,
180        AUDIO_HW_INPUT_CLOSE,
181        AUDIO_HW_STANDBY,
182        AUDIO_HW_SET_MASTER_VOLUME,
183        AUDIO_HW_GET_ROUTING,
184        AUDIO_HW_SET_ROUTING,
185        AUDIO_HW_GET_MODE,
186        AUDIO_HW_SET_MODE,
187        AUDIO_HW_GET_MIC_MUTE,
188        AUDIO_HW_SET_MIC_MUTE,
189        AUDIO_SET_VOICE_VOLUME,
190        AUDIO_SET_PARAMETER,
191    };
192
193    // record interface
194    virtual sp<IAudioRecord> openRecord(
195                                pid_t pid,
196                                audio_io_handle_t input,
197                                uint32_t sampleRate,
198                                audio_format_t format,
199                                uint32_t channelMask,
200                                int frameCount,
201                                uint32_t flags,
202                                int *sessionId,
203                                status_t *status);
204
205    virtual     status_t    onTransact(
206                                uint32_t code,
207                                const Parcel& data,
208                                Parcel* reply,
209                                uint32_t flags);
210
211               audio_mode_t getMode() const { return mMode; }
212
213                bool        btNrecIsOff() const { return mBtNrecIsOff; }
214
215private:
216
217                            AudioFlinger();
218    virtual                 ~AudioFlinger();
219
220    status_t                initCheck() const;
221    virtual     void        onFirstRef();
222    audio_hw_device_t*      findSuitableHwDev_l(uint32_t devices);
223    void                    purgeStaleEffects_l();
224
225    // Internal dump utilites.
226    status_t dumpPermissionDenial(int fd, const Vector<String16>& args);
227    status_t dumpClients(int fd, const Vector<String16>& args);
228    status_t dumpInternals(int fd, const Vector<String16>& args);
229
230    // --- Client ---
231    class Client : public RefBase {
232    public:
233                            Client(const sp<AudioFlinger>& audioFlinger, pid_t pid);
234        virtual             ~Client();
235        sp<MemoryDealer>    heap() const;
236        pid_t               pid() const { return mPid; }
237        sp<AudioFlinger>    audioFlinger() const { return mAudioFlinger; }
238
239    private:
240                            Client(const Client&);
241                            Client& operator = (const Client&);
242        const sp<AudioFlinger> mAudioFlinger;
243        const sp<MemoryDealer> mMemoryDealer;
244        const pid_t         mPid;
245    };
246
247    // --- Notification Client ---
248    class NotificationClient : public IBinder::DeathRecipient {
249    public:
250                            NotificationClient(const sp<AudioFlinger>& audioFlinger,
251                                                const sp<IAudioFlingerClient>& client,
252                                                pid_t pid);
253        virtual             ~NotificationClient();
254
255                sp<IAudioFlingerClient> audioFlingerClient() const { return mAudioFlingerClient; }
256
257                // IBinder::DeathRecipient
258                virtual     void        binderDied(const wp<IBinder>& who);
259
260    private:
261                            NotificationClient(const NotificationClient&);
262                            NotificationClient& operator = (const NotificationClient&);
263
264        const sp<AudioFlinger>  mAudioFlinger;
265        const pid_t             mPid;
266        const sp<IAudioFlingerClient> mAudioFlingerClient;
267    };
268
269    class TrackHandle;
270    class RecordHandle;
271    class RecordThread;
272    class PlaybackThread;
273    class MixerThread;
274    class DirectOutputThread;
275    class DuplicatingThread;
276    class Track;
277    class RecordTrack;
278    class EffectModule;
279    class EffectHandle;
280    class EffectChain;
281    struct AudioStreamOut;
282    struct AudioStreamIn;
283
284    class ThreadBase : public Thread {
285    public:
286
287        enum type_t {
288            MIXER,              // Thread class is MixerThread
289            DIRECT,             // Thread class is DirectOutputThread
290            DUPLICATING,        // Thread class is DuplicatingThread
291            RECORD              // Thread class is RecordThread
292        };
293
294        ThreadBase (const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id, uint32_t device, type_t type);
295        virtual             ~ThreadBase();
296
297        status_t dumpBase(int fd, const Vector<String16>& args);
298        status_t dumpEffectChains(int fd, const Vector<String16>& args);
299
300        void clearPowerManager();
301
302        // base for record and playback
303        class TrackBase : public AudioBufferProvider, public RefBase {
304
305        public:
306            enum track_state {
307                IDLE,
308                TERMINATED,
309                STOPPED,
310                RESUMING,
311                ACTIVE,
312                PAUSING,
313                PAUSED
314            };
315
316            enum track_flags {
317                STEPSERVER_FAILED = 0x01, //  StepServer could not acquire cblk->lock mutex
318                SYSTEM_FLAGS_MASK = 0x0000ffffUL,
319                // The upper 16 bits are used for track-specific flags.
320            };
321
322                                TrackBase(const wp<ThreadBase>& thread,
323                                        const sp<Client>& client,
324                                        uint32_t sampleRate,
325                                        audio_format_t format,
326                                        uint32_t channelMask,
327                                        int frameCount,
328                                        uint32_t flags,
329                                        const sp<IMemory>& sharedBuffer,
330                                        int sessionId);
331            virtual             ~TrackBase();
332
333            virtual status_t    start() = 0;
334            virtual void        stop() = 0;
335                    sp<IMemory> getCblk() const { return mCblkMemory; }
336                    audio_track_cblk_t* cblk() const { return mCblk; }
337                    int         sessionId() const { return mSessionId; }
338
339        protected:
340            friend class ThreadBase;
341            friend class RecordHandle;
342            friend class PlaybackThread;
343            friend class RecordThread;
344            friend class MixerThread;
345            friend class DirectOutputThread;
346
347                                TrackBase(const TrackBase&);
348                                TrackBase& operator = (const TrackBase&);
349
350            virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer) = 0;
351            virtual void releaseBuffer(AudioBufferProvider::Buffer* buffer);
352
353            audio_format_t format() const {
354                return mFormat;
355            }
356
357            int channelCount() const { return mChannelCount; }
358
359            uint32_t channelMask() const { return mChannelMask; }
360
361            int sampleRate() const; // FIXME inline after cblk sr moved
362
363            void* getBuffer(uint32_t offset, uint32_t frames) const;
364
365            bool isStopped() const {
366                return mState == STOPPED;
367            }
368
369            bool isTerminated() const {
370                return mState == TERMINATED;
371            }
372
373            bool step();
374            void reset();
375
376            const wp<ThreadBase> mThread;
377            /*const*/ sp<Client> mClient;   // see explanation at ~TrackBase() why not const
378            sp<IMemory>         mCblkMemory;
379            audio_track_cblk_t* mCblk;
380            void*               mBuffer;
381            void*               mBufferEnd;
382            uint32_t            mFrameCount;
383            // we don't really need a lock for these
384            track_state         mState;
385            const audio_format_t mFormat;
386            uint32_t            mFlags;
387            const int           mSessionId;
388            uint8_t             mChannelCount;
389            uint32_t            mChannelMask;
390        };
391
392        class ConfigEvent {
393        public:
394            ConfigEvent() : mEvent(0), mParam(0) {}
395
396            int mEvent;
397            int mParam;
398        };
399
400        class PMDeathRecipient : public IBinder::DeathRecipient {
401        public:
402                        PMDeathRecipient(const wp<ThreadBase>& thread) : mThread(thread) {}
403            virtual     ~PMDeathRecipient() {}
404
405            // IBinder::DeathRecipient
406            virtual     void        binderDied(const wp<IBinder>& who);
407
408        private:
409                        PMDeathRecipient(const PMDeathRecipient&);
410                        PMDeathRecipient& operator = (const PMDeathRecipient&);
411
412            wp<ThreadBase> mThread;
413        };
414
415        virtual     status_t    initCheck() const = 0;
416                    type_t      type() const { return mType; }
417                    uint32_t    sampleRate() const { return mSampleRate; }
418                    int         channelCount() const { return mChannelCount; }
419                    audio_format_t format() const { return mFormat; }
420                    size_t      frameCount() const { return mFrameCount; }
421                    void        wakeUp()    { mWaitWorkCV.broadcast(); }
422        // Should be "virtual status_t requestExitAndWait()" and override same
423        // method in Thread, but Thread::requestExitAndWait() is not yet virtual.
424                    void        exit();
425        virtual     bool        checkForNewParameters_l() = 0;
426        virtual     status_t    setParameters(const String8& keyValuePairs);
427        virtual     String8     getParameters(const String8& keys) = 0;
428        virtual     void        audioConfigChanged_l(int event, int param = 0) = 0;
429                    void        sendConfigEvent(int event, int param = 0);
430                    void        sendConfigEvent_l(int event, int param = 0);
431                    void        processConfigEvents();
432                    audio_io_handle_t id() const { return mId;}
433                    bool        standby() { return mStandby; }
434                    uint32_t    device() { return mDevice; }
435        virtual     audio_stream_t* stream() = 0;
436
437                    sp<EffectHandle> createEffect_l(
438                                        const sp<AudioFlinger::Client>& client,
439                                        const sp<IEffectClient>& effectClient,
440                                        int32_t priority,
441                                        int sessionId,
442                                        effect_descriptor_t *desc,
443                                        int *enabled,
444                                        status_t *status);
445                    void disconnectEffect(const sp< EffectModule>& effect,
446                                          const wp<EffectHandle>& handle,
447                                          bool unpiniflast);
448
449                    // return values for hasAudioSession (bit field)
450                    enum effect_state {
451                        EFFECT_SESSION = 0x1,   // the audio session corresponds to at least one
452                                                // effect
453                        TRACK_SESSION = 0x2     // the audio session corresponds to at least one
454                                                // track
455                    };
456
457                    // get effect chain corresponding to session Id.
458                    sp<EffectChain> getEffectChain(int sessionId);
459                    // same as getEffectChain() but must be called with ThreadBase mutex locked
460                    sp<EffectChain> getEffectChain_l(int sessionId);
461                    // add an effect chain to the chain list (mEffectChains)
462        virtual     status_t addEffectChain_l(const sp<EffectChain>& chain) = 0;
463                    // remove an effect chain from the chain list (mEffectChains)
464        virtual     size_t removeEffectChain_l(const sp<EffectChain>& chain) = 0;
465                    // lock mall effect chains Mutexes. Must be called before releasing the
466                    // ThreadBase mutex before processing the mixer and effects. This guarantees the
467                    // integrity of the chains during the process.
468                    void lockEffectChains_l(Vector<sp <EffectChain> >& effectChains);
469                    // unlock effect chains after process
470                    void unlockEffectChains(Vector<sp <EffectChain> >& effectChains);
471                    // set audio mode to all effect chains
472                    void setMode(audio_mode_t mode);
473                    // get effect module with corresponding ID on specified audio session
474                    sp<AudioFlinger::EffectModule> getEffect_l(int sessionId, int effectId);
475                    // add and effect module. Also creates the effect chain is none exists for
476                    // the effects audio session
477                    status_t addEffect_l(const sp< EffectModule>& effect);
478                    // remove and effect module. Also removes the effect chain is this was the last
479                    // effect
480                    void removeEffect_l(const sp< EffectModule>& effect);
481                    // detach all tracks connected to an auxiliary effect
482        virtual     void detachAuxEffect_l(int effectId) {}
483                    // returns either EFFECT_SESSION if effects on this audio session exist in one
484                    // chain, or TRACK_SESSION if tracks on this audio session exist, or both
485                    virtual uint32_t hasAudioSession(int sessionId) = 0;
486                    // the value returned by default implementation is not important as the
487                    // strategy is only meaningful for PlaybackThread which implements this method
488                    virtual uint32_t getStrategyForSession_l(int sessionId) { return 0; }
489
490                    // suspend or restore effect according to the type of effect passed. a NULL
491                    // type pointer means suspend all effects in the session
492                    void setEffectSuspended(const effect_uuid_t *type,
493                                            bool suspend,
494                                            int sessionId = AUDIO_SESSION_OUTPUT_MIX);
495                    // check if some effects must be suspended/restored when an effect is enabled
496                    // or disabled
497                    void checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
498                                                     bool enabled,
499                                                     int sessionId = AUDIO_SESSION_OUTPUT_MIX);
500                    void checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
501                                                       bool enabled,
502                                                       int sessionId = AUDIO_SESSION_OUTPUT_MIX);
503        mutable     Mutex                   mLock;
504
505    protected:
506
507                    // entry describing an effect being suspended in mSuspendedSessions keyed vector
508                    class SuspendedSessionDesc : public RefBase {
509                    public:
510                        SuspendedSessionDesc() : mRefCount(0) {}
511
512                        int mRefCount;          // number of active suspend requests
513                        effect_uuid_t mType;    // effect type UUID
514                    };
515
516                    void        acquireWakeLock();
517                    void        acquireWakeLock_l();
518                    void        releaseWakeLock();
519                    void        releaseWakeLock_l();
520                    void setEffectSuspended_l(const effect_uuid_t *type,
521                                              bool suspend,
522                                              int sessionId = AUDIO_SESSION_OUTPUT_MIX);
523                    // updated mSuspendedSessions when an effect suspended or restored
524                    void        updateSuspendedSessions_l(const effect_uuid_t *type,
525                                                          bool suspend,
526                                                          int sessionId);
527                    // check if some effects must be suspended when an effect chain is added
528                    void checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain);
529
530        friend class AudioFlinger;
531        friend class Track;
532        friend class TrackBase;
533        friend class PlaybackThread;
534        friend class MixerThread;
535        friend class DirectOutputThread;
536        friend class DuplicatingThread;
537        friend class RecordThread;
538        friend class RecordTrack;
539
540                    const type_t            mType;
541                    Condition               mWaitWorkCV;
542                    const sp<AudioFlinger>  mAudioFlinger;
543                    uint32_t                mSampleRate;
544                    size_t                  mFrameCount;
545                    uint32_t                mChannelMask;
546                    uint16_t                mChannelCount;
547                    size_t                  mFrameSize;
548                    audio_format_t          mFormat;
549                    Condition               mParamCond;
550                    Vector<String8>         mNewParameters;
551                    status_t                mParamStatus;
552                    Vector<ConfigEvent>     mConfigEvents;
553                    bool                    mStandby;
554                    const audio_io_handle_t mId;
555                    Vector< sp<EffectChain> > mEffectChains;
556                    uint32_t                mDevice;    // output device for PlaybackThread
557                                                        // input + output devices for RecordThread
558                    static const int        kNameLength = 32;
559                    char                    mName[kNameLength];
560                    sp<IPowerManager>       mPowerManager;
561                    sp<IBinder>             mWakeLockToken;
562                    const sp<PMDeathRecipient> mDeathRecipient;
563                    // list of suspended effects per session and per type. The first vector is
564                    // keyed by session ID, the second by type UUID timeLow field
565                    KeyedVector< int, KeyedVector< int, sp<SuspendedSessionDesc> > >  mSuspendedSessions;
566    };
567
568    // --- PlaybackThread ---
569    class PlaybackThread : public ThreadBase {
570    public:
571
572        enum mixer_state {
573            MIXER_IDLE,
574            MIXER_TRACKS_ENABLED,
575            MIXER_TRACKS_READY
576        };
577
578        // playback track
579        class Track : public TrackBase {
580        public:
581                                Track(  const wp<ThreadBase>& thread,
582                                        const sp<Client>& client,
583                                        audio_stream_type_t streamType,
584                                        uint32_t sampleRate,
585                                        audio_format_t format,
586                                        uint32_t channelMask,
587                                        int frameCount,
588                                        const sp<IMemory>& sharedBuffer,
589                                        int sessionId);
590            virtual             ~Track();
591
592                    void        dump(char* buffer, size_t size);
593            virtual status_t    start();
594            virtual void        stop();
595                    void        pause();
596
597                    void        flush();
598                    void        destroy();
599                    void        mute(bool);
600                    int name() const {
601                        return mName;
602                    }
603
604                    audio_stream_type_t type() const {
605                        return mStreamType;
606                    }
607                    status_t    attachAuxEffect(int EffectId);
608                    void        setAuxBuffer(int EffectId, int32_t *buffer);
609                    int32_t     *auxBuffer() const { return mAuxBuffer; }
610                    void        setMainBuffer(int16_t *buffer) { mMainBuffer = buffer; }
611                    int16_t     *mainBuffer() const { return mMainBuffer; }
612                    int         auxEffectId() const { return mAuxEffectId; }
613
614
615        protected:
616            friend class ThreadBase;
617            friend class TrackHandle;
618            friend class PlaybackThread;
619            friend class MixerThread;
620            friend class DirectOutputThread;
621
622                                Track(const Track&);
623                                Track& operator = (const Track&);
624
625            virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer);
626            bool isMuted() const { return mMute; }
627            bool isPausing() const {
628                return mState == PAUSING;
629            }
630            bool isPaused() const {
631                return mState == PAUSED;
632            }
633            bool isReady() const;
634            void setPaused() { mState = PAUSED; }
635            void reset();
636
637            bool isOutputTrack() const {
638                return (mStreamType == AUDIO_STREAM_CNT);
639            }
640
641            // we don't really need a lock for these
642            volatile bool       mMute;
643            // FILLED state is used for suppressing volume ramp at begin of playing
644            enum {FS_FILLING, FS_FILLED, FS_ACTIVE};
645            mutable uint8_t     mFillingUpStatus;
646            int8_t              mRetryCount;
647            sp<IMemory>         mSharedBuffer;
648            bool                mResetDone;
649            audio_stream_type_t mStreamType;
650            int                 mName;
651            int16_t             *mMainBuffer;
652            int32_t             *mAuxBuffer;
653            int                 mAuxEffectId;
654            bool                mHasVolumeController;
655        };  // end of Track
656
657
658        // playback track
659        class OutputTrack : public Track {
660        public:
661
662            class Buffer: public AudioBufferProvider::Buffer {
663            public:
664                int16_t *mBuffer;
665            };
666
667                                OutputTrack(  const wp<ThreadBase>& thread,
668                                        DuplicatingThread *sourceThread,
669                                        uint32_t sampleRate,
670                                        audio_format_t format,
671                                        uint32_t channelMask,
672                                        int frameCount);
673            virtual             ~OutputTrack();
674
675            virtual status_t    start();
676            virtual void        stop();
677                    bool        write(int16_t* data, uint32_t frames);
678                    bool        bufferQueueEmpty() const { return (mBufferQueue.size() == 0) ? true : false; }
679                    bool        isActive() const { return mActive; }
680            const wp<ThreadBase>& thread() const { return mThread; }
681
682        private:
683
684            enum {
685                NO_MORE_BUFFERS = 0x80000001,   // same in AudioTrack.h, ok to be different value
686            };
687
688            status_t            obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs);
689            void                clearBufferQueue();
690
691            // Maximum number of pending buffers allocated by OutputTrack::write()
692            static const uint8_t kMaxOverFlowBuffers = 10;
693
694            Vector < Buffer* >          mBufferQueue;
695            AudioBufferProvider::Buffer mOutBuffer;
696            bool                        mActive;
697            DuplicatingThread* const mSourceThread; // for waitTimeMs() in write()
698        };  // end of OutputTrack
699
700        PlaybackThread (const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
701                        audio_io_handle_t id, uint32_t device, type_t type);
702        virtual             ~PlaybackThread();
703
704        virtual     status_t    dump(int fd, const Vector<String16>& args);
705
706        // Thread virtuals
707        virtual     status_t    readyToRun();
708        virtual     void        onFirstRef();
709
710        virtual     status_t    initCheck() const { return (mOutput == NULL) ? NO_INIT : NO_ERROR; }
711
712        virtual     uint32_t    latency() const;
713
714        virtual     status_t    setMasterVolume(float value);
715        virtual     status_t    setMasterMute(bool muted);
716
717        virtual     float       masterVolume() const { return mMasterVolume; }
718        virtual     bool        masterMute() const { return mMasterMute; }
719
720        virtual     status_t    setStreamVolume(audio_stream_type_t stream, float value);
721        virtual     status_t    setStreamMute(audio_stream_type_t stream, bool muted);
722
723        virtual     float       streamVolume(audio_stream_type_t stream) const;
724        virtual     bool        streamMute(audio_stream_type_t stream) const;
725
726                    sp<Track>   createTrack_l(
727                                    const sp<AudioFlinger::Client>& client,
728                                    audio_stream_type_t streamType,
729                                    uint32_t sampleRate,
730                                    audio_format_t format,
731                                    uint32_t channelMask,
732                                    int frameCount,
733                                    const sp<IMemory>& sharedBuffer,
734                                    int sessionId,
735                                    status_t *status);
736
737                    AudioStreamOut* getOutput() const;
738                    AudioStreamOut* clearOutput();
739                    virtual audio_stream_t* stream();
740
741                    void        suspend() { mSuspended++; }
742                    void        restore() { if (mSuspended) mSuspended--; }
743                    bool        isSuspended() const { return (mSuspended != 0); }
744        virtual     String8     getParameters(const String8& keys);
745        virtual     void        audioConfigChanged_l(int event, int param = 0);
746        virtual     status_t    getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames);
747                    int16_t     *mixBuffer() const { return mMixBuffer; };
748
749        virtual     void detachAuxEffect_l(int effectId);
750                    status_t attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track> track,
751                            int EffectId);
752                    status_t attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track> track,
753                            int EffectId);
754
755                    virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
756                    virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
757                    virtual uint32_t hasAudioSession(int sessionId);
758                    virtual uint32_t getStrategyForSession_l(int sessionId);
759
760                            void setStreamValid(audio_stream_type_t streamType, bool valid);
761
762        struct  stream_type_t {
763            stream_type_t()
764                :   volume(1.0f),
765                    mute(false),
766                    valid(true)
767            {
768            }
769            float       volume;
770            bool        mute;
771            bool        valid;
772        };
773
774    protected:
775        int16_t*                        mMixBuffer;
776        int                             mSuspended;
777        int                             mBytesWritten;
778    private:
779        bool                            mMasterMute;
780    protected:
781        SortedVector< wp<Track> >       mActiveTracks;
782
783        virtual int             getTrackName_l() = 0;
784        virtual void            deleteTrackName_l(int name) = 0;
785        virtual uint32_t        activeSleepTimeUs();
786        virtual uint32_t        idleSleepTimeUs() = 0;
787        virtual uint32_t        suspendSleepTimeUs() = 0;
788
789    private:
790
791        friend class AudioFlinger;
792        friend class OutputTrack;
793        friend class Track;
794        friend class TrackBase;
795        friend class MixerThread;
796        friend class DirectOutputThread;
797        friend class DuplicatingThread;
798
799        PlaybackThread(const Client&);
800        PlaybackThread& operator = (const PlaybackThread&);
801
802        status_t    addTrack_l(const sp<Track>& track);
803        void        destroyTrack_l(const sp<Track>& track);
804        void        removeTrack_l(const sp<Track>& track);
805
806        void        readOutputParameters();
807
808        virtual status_t    dumpInternals(int fd, const Vector<String16>& args);
809        status_t    dumpTracks(int fd, const Vector<String16>& args);
810
811        SortedVector< sp<Track> >       mTracks;
812        // mStreamTypes[] uses 1 additional stream type internally for the OutputTrack used by DuplicatingThread
813        stream_type_t                   mStreamTypes[AUDIO_STREAM_CNT + 1];
814        AudioStreamOut                  *mOutput;
815        float                           mMasterVolume;
816        nsecs_t                         mLastWriteTime;
817        int                             mNumWrites;
818        int                             mNumDelayedWrites;
819        bool                            mInWrite;
820    };
821
822    class MixerThread : public PlaybackThread {
823    public:
824        MixerThread (const sp<AudioFlinger>& audioFlinger,
825                     AudioStreamOut* output,
826                     audio_io_handle_t id,
827                     uint32_t device,
828                     type_t type = MIXER);
829        virtual             ~MixerThread();
830
831        // Thread virtuals
832        virtual     bool        threadLoop();
833
834                    void        invalidateTracks(audio_stream_type_t streamType);
835        virtual     bool        checkForNewParameters_l();
836        virtual     status_t    dumpInternals(int fd, const Vector<String16>& args);
837
838    protected:
839                    mixer_state prepareTracks_l(const SortedVector< wp<Track> >& activeTracks,
840                                                Vector< sp<Track> > *tracksToRemove);
841        virtual     int         getTrackName_l();
842        virtual     void        deleteTrackName_l(int name);
843        virtual     uint32_t    idleSleepTimeUs();
844        virtual     uint32_t    suspendSleepTimeUs();
845
846                    AudioMixer* mAudioMixer;
847                    mixer_state mPrevMixerStatus; // previous status returned by prepareTracks_l()
848    };
849
850    class DirectOutputThread : public PlaybackThread {
851    public:
852
853        DirectOutputThread (const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
854                            audio_io_handle_t id, uint32_t device);
855        virtual                 ~DirectOutputThread();
856
857        // Thread virtuals
858        virtual     bool        threadLoop();
859
860        virtual     bool        checkForNewParameters_l();
861
862    protected:
863        virtual     int         getTrackName_l();
864        virtual     void        deleteTrackName_l(int name);
865        virtual     uint32_t    activeSleepTimeUs();
866        virtual     uint32_t    idleSleepTimeUs();
867        virtual     uint32_t    suspendSleepTimeUs();
868
869    private:
870        void applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp);
871
872        float mLeftVolFloat;
873        float mRightVolFloat;
874        uint16_t mLeftVolShort;
875        uint16_t mRightVolShort;
876    };
877
878    class DuplicatingThread : public MixerThread {
879    public:
880        DuplicatingThread (const sp<AudioFlinger>& audioFlinger, MixerThread* mainThread,
881                           audio_io_handle_t id);
882        virtual                 ~DuplicatingThread();
883
884        // Thread virtuals
885        virtual     bool        threadLoop();
886                    void        addOutputTrack(MixerThread* thread);
887                    void        removeOutputTrack(MixerThread* thread);
888                    uint32_t    waitTimeMs() { return mWaitTimeMs; }
889    protected:
890        virtual     uint32_t    activeSleepTimeUs();
891
892    private:
893                    bool        outputsReady(SortedVector< sp<OutputTrack> > &outputTracks);
894                    void        updateWaitTime();
895
896        SortedVector < sp<OutputTrack> >  mOutputTracks;
897                    uint32_t    mWaitTimeMs;
898    };
899
900              PlaybackThread *checkPlaybackThread_l(audio_io_handle_t output) const;
901              MixerThread *checkMixerThread_l(audio_io_handle_t output) const;
902              RecordThread *checkRecordThread_l(audio_io_handle_t input) const;
903              float streamVolumeInternal(audio_stream_type_t stream) const
904                                { return mStreamTypes[stream].volume; }
905              void audioConfigChanged_l(int event, audio_io_handle_t ioHandle, void *param2);
906
907              // allocate an audio_io_handle_t, session ID, or effect ID
908              uint32_t nextUniqueId();
909
910              status_t moveEffectChain_l(int sessionId,
911                                     AudioFlinger::PlaybackThread *srcThread,
912                                     AudioFlinger::PlaybackThread *dstThread,
913                                     bool reRegister);
914              PlaybackThread *primaryPlaybackThread_l();
915              uint32_t primaryOutputDevice_l();
916
917    friend class AudioBuffer;
918
919    class TrackHandle : public android::BnAudioTrack {
920    public:
921                            TrackHandle(const sp<PlaybackThread::Track>& track);
922        virtual             ~TrackHandle();
923        virtual sp<IMemory> getCblk() const;
924        virtual status_t    start();
925        virtual void        stop();
926        virtual void        flush();
927        virtual void        mute(bool);
928        virtual void        pause();
929        virtual status_t    attachAuxEffect(int effectId);
930        virtual status_t onTransact(
931            uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags);
932    private:
933        const sp<PlaybackThread::Track> mTrack;
934    };
935
936    friend class Client;
937    friend class PlaybackThread::Track;
938
939
940                void        removeClient_l(pid_t pid);
941                void        removeNotificationClient(pid_t pid);
942
943
944    // record thread
945    class RecordThread : public ThreadBase, public AudioBufferProvider
946    {
947    public:
948
949        // record track
950        class RecordTrack : public TrackBase {
951        public:
952                                RecordTrack(const wp<ThreadBase>& thread,
953                                        const sp<Client>& client,
954                                        uint32_t sampleRate,
955                                        audio_format_t format,
956                                        uint32_t channelMask,
957                                        int frameCount,
958                                        uint32_t flags,
959                                        int sessionId);
960            virtual             ~RecordTrack();
961
962            virtual status_t    start();
963            virtual void        stop();
964
965                    bool        overflow() { bool tmp = mOverflow; mOverflow = false; return tmp; }
966                    bool        setOverflow() { bool tmp = mOverflow; mOverflow = true; return tmp; }
967
968                    void        dump(char* buffer, size_t size);
969
970        private:
971            friend class AudioFlinger;
972            friend class RecordThread;
973
974                                RecordTrack(const RecordTrack&);
975                                RecordTrack& operator = (const RecordTrack&);
976
977            virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer);
978
979            bool                mOverflow;
980        };
981
982
983                RecordThread(const sp<AudioFlinger>& audioFlinger,
984                        AudioStreamIn *input,
985                        uint32_t sampleRate,
986                        uint32_t channels,
987                        audio_io_handle_t id,
988                        uint32_t device);
989                virtual     ~RecordThread();
990
991        virtual bool        threadLoop();
992        virtual status_t    readyToRun();
993        virtual void        onFirstRef();
994
995        virtual status_t    initCheck() const { return (mInput == NULL) ? NO_INIT : NO_ERROR; }
996                sp<AudioFlinger::RecordThread::RecordTrack>  createRecordTrack_l(
997                        const sp<AudioFlinger::Client>& client,
998                        uint32_t sampleRate,
999                        audio_format_t format,
1000                        int channelMask,
1001                        int frameCount,
1002                        uint32_t flags,
1003                        int sessionId,
1004                        status_t *status);
1005
1006                status_t    start(RecordTrack* recordTrack);
1007                void        stop(RecordTrack* recordTrack);
1008                status_t    dump(int fd, const Vector<String16>& args);
1009                AudioStreamIn* getInput() const;
1010                AudioStreamIn* clearInput();
1011                virtual audio_stream_t* stream();
1012
1013        virtual status_t    getNextBuffer(AudioBufferProvider::Buffer* buffer);
1014        virtual void        releaseBuffer(AudioBufferProvider::Buffer* buffer);
1015        virtual bool        checkForNewParameters_l();
1016        virtual String8     getParameters(const String8& keys);
1017        virtual void        audioConfigChanged_l(int event, int param = 0);
1018                void        readInputParameters();
1019        virtual unsigned int  getInputFramesLost();
1020
1021        virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
1022        virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
1023        virtual uint32_t hasAudioSession(int sessionId);
1024                RecordTrack* track();
1025
1026    private:
1027                RecordThread();
1028                AudioStreamIn                       *mInput;
1029                RecordTrack*                        mTrack;
1030                sp<RecordTrack>                     mActiveTrack;
1031                Condition                           mStartStopCond;
1032                AudioResampler                      *mResampler;
1033                int32_t                             *mRsmpOutBuffer;
1034                int16_t                             *mRsmpInBuffer;
1035                size_t                              mRsmpInIndex;
1036                size_t                              mInputBytes;
1037                const int                           mReqChannelCount;
1038                const uint32_t                      mReqSampleRate;
1039                ssize_t                             mBytesRead;
1040    };
1041
1042    class RecordHandle : public android::BnAudioRecord {
1043    public:
1044        RecordHandle(const sp<RecordThread::RecordTrack>& recordTrack);
1045        virtual             ~RecordHandle();
1046        virtual sp<IMemory> getCblk() const;
1047        virtual status_t    start();
1048        virtual void        stop();
1049        virtual status_t onTransact(
1050            uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags);
1051    private:
1052        const sp<RecordThread::RecordTrack> mRecordTrack;
1053    };
1054
1055    //--- Audio Effect Management
1056
1057    // EffectModule and EffectChain classes both have their own mutex to protect
1058    // state changes or resource modifications. Always respect the following order
1059    // if multiple mutexes must be acquired to avoid cross deadlock:
1060    // AudioFlinger -> ThreadBase -> EffectChain -> EffectModule
1061
1062    // The EffectModule class is a wrapper object controlling the effect engine implementation
1063    // in the effect library. It prevents concurrent calls to process() and command() functions
1064    // from different client threads. It keeps a list of EffectHandle objects corresponding
1065    // to all client applications using this effect and notifies applications of effect state,
1066    // control or parameter changes. It manages the activation state machine to send appropriate
1067    // reset, enable, disable commands to effect engine and provide volume
1068    // ramping when effects are activated/deactivated.
1069    // When controlling an auxiliary effect, the EffectModule also provides an input buffer used by
1070    // the attached track(s) to accumulate their auxiliary channel.
1071    class EffectModule: public RefBase {
1072    public:
1073        EffectModule(const wp<ThreadBase>& wThread,
1074                        const wp<AudioFlinger::EffectChain>& chain,
1075                        effect_descriptor_t *desc,
1076                        int id,
1077                        int sessionId);
1078        virtual ~EffectModule();
1079
1080        enum effect_state {
1081            IDLE,
1082            RESTART,
1083            STARTING,
1084            ACTIVE,
1085            STOPPING,
1086            STOPPED,
1087            DESTROYED
1088        };
1089
1090        int         id() const { return mId; }
1091        void process();
1092        void updateState();
1093        status_t command(uint32_t cmdCode,
1094                         uint32_t cmdSize,
1095                         void *pCmdData,
1096                         uint32_t *replySize,
1097                         void *pReplyData);
1098
1099        void reset_l();
1100        status_t configure();
1101        status_t init();
1102        effect_state state() const {
1103            return mState;
1104        }
1105        uint32_t status() {
1106            return mStatus;
1107        }
1108        int sessionId() const {
1109            return mSessionId;
1110        }
1111        status_t    setEnabled(bool enabled);
1112        bool isEnabled() const;
1113        bool isProcessEnabled() const;
1114
1115        void        setInBuffer(int16_t *buffer) { mConfig.inputCfg.buffer.s16 = buffer; }
1116        int16_t     *inBuffer() { return mConfig.inputCfg.buffer.s16; }
1117        void        setOutBuffer(int16_t *buffer) { mConfig.outputCfg.buffer.s16 = buffer; }
1118        int16_t     *outBuffer() { return mConfig.outputCfg.buffer.s16; }
1119        void        setChain(const wp<EffectChain>& chain) { mChain = chain; }
1120        void        setThread(const wp<ThreadBase>& thread) { mThread = thread; }
1121        const wp<ThreadBase>& thread() { return mThread; }
1122
1123        status_t addHandle(const sp<EffectHandle>& handle);
1124        void disconnect(const wp<EffectHandle>& handle, bool unpiniflast);
1125        size_t removeHandle (const wp<EffectHandle>& handle);
1126
1127        effect_descriptor_t& desc() { return mDescriptor; }
1128        wp<EffectChain>&     chain() { return mChain; }
1129
1130        status_t         setDevice(uint32_t device);
1131        status_t         setVolume(uint32_t *left, uint32_t *right, bool controller);
1132        status_t         setMode(audio_mode_t mode);
1133        status_t         start();
1134        status_t         stop();
1135        void             setSuspended(bool suspended);
1136        bool             suspended() const;
1137
1138        sp<EffectHandle> controlHandle();
1139
1140        bool             isPinned() const { return mPinned; }
1141        void             unPin() { mPinned = false; }
1142
1143        status_t         dump(int fd, const Vector<String16>& args);
1144
1145    protected:
1146        friend class EffectHandle;
1147        friend class AudioFlinger;
1148        bool                mPinned;
1149
1150        // Maximum time allocated to effect engines to complete the turn off sequence
1151        static const uint32_t MAX_DISABLE_TIME_MS = 10000;
1152
1153        EffectModule(const EffectModule&);
1154        EffectModule& operator = (const EffectModule&);
1155
1156        status_t start_l();
1157        status_t stop_l();
1158
1159mutable Mutex               mLock;      // mutex for process, commands and handles list protection
1160        wp<ThreadBase>      mThread;    // parent thread
1161        wp<EffectChain>     mChain;     // parent effect chain
1162        int                 mId;        // this instance unique ID
1163        int                 mSessionId; // audio session ID
1164        effect_descriptor_t mDescriptor;// effect descriptor received from effect engine
1165        effect_config_t     mConfig;    // input and output audio configuration
1166        effect_handle_t  mEffectInterface; // Effect module C API
1167        status_t            mStatus;    // initialization status
1168        effect_state        mState;     // current activation state
1169        Vector< wp<EffectHandle> > mHandles;    // list of client handles
1170        uint32_t mMaxDisableWaitCnt;    // maximum grace period before forcing an effect off after
1171                                        // sending disable command.
1172        uint32_t mDisableWaitCnt;       // current process() calls count during disable period.
1173        bool     mSuspended;            // effect is suspended: temporarily disabled by framework
1174    };
1175
1176    // The EffectHandle class implements the IEffect interface. It provides resources
1177    // to receive parameter updates, keeps track of effect control
1178    // ownership and state and has a pointer to the EffectModule object it is controlling.
1179    // There is one EffectHandle object for each application controlling (or using)
1180    // an effect module.
1181    // The EffectHandle is obtained by calling AudioFlinger::createEffect().
1182    class EffectHandle: public android::BnEffect {
1183    public:
1184
1185        EffectHandle(const sp<EffectModule>& effect,
1186                const sp<AudioFlinger::Client>& client,
1187                const sp<IEffectClient>& effectClient,
1188                int32_t priority);
1189        virtual ~EffectHandle();
1190
1191        // IEffect
1192        virtual status_t enable();
1193        virtual status_t disable();
1194        virtual status_t command(uint32_t cmdCode,
1195                                 uint32_t cmdSize,
1196                                 void *pCmdData,
1197                                 uint32_t *replySize,
1198                                 void *pReplyData);
1199        virtual void disconnect();
1200        virtual void disconnect(bool unpiniflast);
1201        virtual sp<IMemory> getCblk() const { return mCblkMemory; }
1202        virtual status_t onTransact(uint32_t code, const Parcel& data,
1203                Parcel* reply, uint32_t flags);
1204
1205
1206        // Give or take control of effect module
1207        // - hasControl: true if control is given, false if removed
1208        // - signal: true client app should be signaled of change, false otherwise
1209        // - enabled: state of the effect when control is passed
1210        void setControl(bool hasControl, bool signal, bool enabled);
1211        void commandExecuted(uint32_t cmdCode,
1212                             uint32_t cmdSize,
1213                             void *pCmdData,
1214                             uint32_t replySize,
1215                             void *pReplyData);
1216        void setEnabled(bool enabled);
1217        bool enabled() const { return mEnabled; }
1218
1219        // Getters
1220        int id() const { return mEffect->id(); }
1221        int priority() const { return mPriority; }
1222        bool hasControl() const { return mHasControl; }
1223        sp<EffectModule> effect() const { return mEffect; }
1224
1225        void dump(char* buffer, size_t size);
1226
1227    protected:
1228        friend class AudioFlinger;
1229        friend class EffectModule;
1230        EffectHandle(const EffectHandle&);
1231        EffectHandle& operator =(const EffectHandle&);
1232
1233        sp<EffectModule> mEffect;           // pointer to controlled EffectModule
1234        sp<IEffectClient> mEffectClient;    // callback interface for client notifications
1235        /*const*/ sp<Client> mClient;       // client for shared memory allocation, see disconnect()
1236        sp<IMemory>         mCblkMemory;    // shared memory for control block
1237        effect_param_cblk_t* mCblk;         // control block for deferred parameter setting via shared memory
1238        uint8_t*            mBuffer;        // pointer to parameter area in shared memory
1239        int mPriority;                      // client application priority to control the effect
1240        bool mHasControl;                   // true if this handle is controlling the effect
1241        bool mEnabled;                      // cached enable state: needed when the effect is
1242                                            // restored after being suspended
1243    };
1244
1245    // the EffectChain class represents a group of effects associated to one audio session.
1246    // There can be any number of EffectChain objects per output mixer thread (PlaybackThread).
1247    // The EffecChain with session ID 0 contains global effects applied to the output mix.
1248    // Effects in this chain can be insert or auxiliary. Effects in other chains (attached to tracks)
1249    // are insert only. The EffectChain maintains an ordered list of effect module, the order corresponding
1250    // in the effect process order. When attached to a track (session ID != 0), it also provide it's own
1251    // input buffer used by the track as accumulation buffer.
1252    class EffectChain: public RefBase {
1253    public:
1254        EffectChain(const wp<ThreadBase>& wThread, int sessionId);
1255        virtual ~EffectChain();
1256
1257        // special key used for an entry in mSuspendedEffects keyed vector
1258        // corresponding to a suspend all request.
1259        static const int        kKeyForSuspendAll = 0;
1260
1261        // minimum duration during which we force calling effect process when last track on
1262        // a session is stopped or removed to allow effect tail to be rendered
1263        static const int        kProcessTailDurationMs = 1000;
1264
1265        void process_l();
1266
1267        void lock() {
1268            mLock.lock();
1269        }
1270        void unlock() {
1271            mLock.unlock();
1272        }
1273
1274        status_t addEffect_l(const sp<EffectModule>& handle);
1275        size_t removeEffect_l(const sp<EffectModule>& handle);
1276
1277        int sessionId() const { return mSessionId; }
1278        void setSessionId(int sessionId) { mSessionId = sessionId; }
1279
1280        sp<EffectModule> getEffectFromDesc_l(effect_descriptor_t *descriptor);
1281        sp<EffectModule> getEffectFromId_l(int id);
1282        sp<EffectModule> getEffectFromType_l(const effect_uuid_t *type);
1283        bool setVolume_l(uint32_t *left, uint32_t *right);
1284        void setDevice_l(uint32_t device);
1285        void setMode_l(audio_mode_t mode);
1286
1287        void setInBuffer(int16_t *buffer, bool ownsBuffer = false) {
1288            mInBuffer = buffer;
1289            mOwnInBuffer = ownsBuffer;
1290        }
1291        int16_t *inBuffer() const {
1292            return mInBuffer;
1293        }
1294        void setOutBuffer(int16_t *buffer) {
1295            mOutBuffer = buffer;
1296        }
1297        int16_t *outBuffer() const {
1298            return mOutBuffer;
1299        }
1300
1301        void incTrackCnt() { android_atomic_inc(&mTrackCnt); }
1302        void decTrackCnt() { android_atomic_dec(&mTrackCnt); }
1303        int32_t trackCnt() const { return mTrackCnt;}
1304
1305        void incActiveTrackCnt() { android_atomic_inc(&mActiveTrackCnt);
1306                                   mTailBufferCount = mMaxTailBuffers; }
1307        void decActiveTrackCnt() { android_atomic_dec(&mActiveTrackCnt); }
1308        int32_t activeTrackCnt() const { return mActiveTrackCnt;}
1309
1310        uint32_t strategy() const { return mStrategy; }
1311        void setStrategy(uint32_t strategy)
1312                 { mStrategy = strategy; }
1313
1314        // suspend effect of the given type
1315        void setEffectSuspended_l(const effect_uuid_t *type,
1316                                  bool suspend);
1317        // suspend all eligible effects
1318        void setEffectSuspendedAll_l(bool suspend);
1319        // check if effects should be suspend or restored when a given effect is enable or disabled
1320        void checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1321                                              bool enabled);
1322
1323        status_t dump(int fd, const Vector<String16>& args);
1324
1325    protected:
1326        friend class AudioFlinger;
1327        EffectChain(const EffectChain&);
1328        EffectChain& operator =(const EffectChain&);
1329
1330        class SuspendedEffectDesc : public RefBase {
1331        public:
1332            SuspendedEffectDesc() : mRefCount(0) {}
1333
1334            int mRefCount;
1335            effect_uuid_t mType;
1336            wp<EffectModule> mEffect;
1337        };
1338
1339        // get a list of effect modules to suspend when an effect of the type
1340        // passed is enabled.
1341        void                       getSuspendEligibleEffects(Vector< sp<EffectModule> > &effects);
1342
1343        // get an effect module if it is currently enable
1344        sp<EffectModule> getEffectIfEnabled(const effect_uuid_t *type);
1345        // true if the effect whose descriptor is passed can be suspended
1346        // OEMs can modify the rules implemented in this method to exclude specific effect
1347        // types or implementations from the suspend/restore mechanism.
1348        bool isEffectEligibleForSuspend(const effect_descriptor_t& desc);
1349
1350        wp<ThreadBase> mThread;     // parent mixer thread
1351        Mutex mLock;                // mutex protecting effect list
1352        Vector<sp<EffectModule> > mEffects; // list of effect modules
1353        int mSessionId;             // audio session ID
1354        int16_t *mInBuffer;         // chain input buffer
1355        int16_t *mOutBuffer;        // chain output buffer
1356        volatile int32_t mActiveTrackCnt;  // number of active tracks connected
1357        volatile int32_t mTrackCnt;        // number of tracks connected
1358        int32_t mTailBufferCount;   // current effect tail buffer count
1359        int32_t mMaxTailBuffers;    // maximum effect tail buffers
1360        bool mOwnInBuffer;          // true if the chain owns its input buffer
1361        int mVolumeCtrlIdx;         // index of insert effect having control over volume
1362        uint32_t mLeftVolume;       // previous volume on left channel
1363        uint32_t mRightVolume;      // previous volume on right channel
1364        uint32_t mNewLeftVolume;       // new volume on left channel
1365        uint32_t mNewRightVolume;      // new volume on right channel
1366        uint32_t mStrategy; // strategy for this effect chain
1367        // mSuspendedEffects lists all effect currently suspended in the chain
1368        // use effect type UUID timelow field as key. There is no real risk of identical
1369        // timeLow fields among effect type UUIDs.
1370        KeyedVector< int, sp<SuspendedEffectDesc> > mSuspendedEffects;
1371    };
1372
1373    // AudioStreamOut and AudioStreamIn are immutable, so their fields are const.
1374    // For emphasis, we could also make all pointers to them be "const *",
1375    // but that would clutter the code unnecessarily.
1376
1377    struct AudioStreamOut {
1378        audio_hw_device_t*  const hwDev;
1379        audio_stream_out_t* const stream;
1380
1381        AudioStreamOut(audio_hw_device_t *dev, audio_stream_out_t *out) :
1382            hwDev(dev), stream(out) {}
1383    };
1384
1385    struct AudioStreamIn {
1386        audio_hw_device_t* const hwDev;
1387        audio_stream_in_t* const stream;
1388
1389        AudioStreamIn(audio_hw_device_t *dev, audio_stream_in_t *in) :
1390            hwDev(dev), stream(in) {}
1391    };
1392
1393    struct AudioSessionRef {
1394        // FIXME rename parameter names when fields get "m" prefix
1395        AudioSessionRef(int sessionid_, pid_t pid_) :
1396            sessionid(sessionid_), pid(pid_), cnt(1) {}
1397        const int sessionid;
1398        const pid_t pid;
1399        int cnt;
1400    };
1401
1402    friend class RecordThread;
1403    friend class PlaybackThread;
1404
1405    mutable     Mutex                               mLock;
1406
1407                DefaultKeyedVector< pid_t, wp<Client> >     mClients;   // see ~Client()
1408
1409                mutable     Mutex                   mHardwareLock;
1410                audio_hw_device_t*                  mPrimaryHardwareDev;
1411                Vector<audio_hw_device_t*>          mAudioHwDevs;
1412    mutable     hardware_call_state                 mHardwareStatus;    // for dump only
1413
1414
1415                DefaultKeyedVector< audio_io_handle_t, sp<PlaybackThread> >  mPlaybackThreads;
1416                PlaybackThread::stream_type_t       mStreamTypes[AUDIO_STREAM_CNT];
1417
1418                // both are protected by mLock
1419                float                               mMasterVolume;
1420                bool                                mMasterMute;
1421
1422                DefaultKeyedVector< audio_io_handle_t, sp<RecordThread> >    mRecordThreads;
1423
1424                DefaultKeyedVector< pid_t, sp<NotificationClient> >    mNotificationClients;
1425                volatile int32_t                    mNextUniqueId;
1426                audio_mode_t                        mMode;
1427                bool                                mBtNrecIsOff;
1428
1429                Vector<AudioSessionRef*> mAudioSessionRefs;
1430
1431                float       masterVolume_l() const  { return mMasterVolume; }
1432                bool        masterMute_l() const    { return mMasterMute; }
1433
1434private:
1435    sp<Client>  registerPid_l(pid_t pid);    // always returns non-0
1436
1437};
1438
1439
1440// ----------------------------------------------------------------------------
1441
1442}; // namespace android
1443
1444#endif // ANDROID_AUDIO_FLINGER_H
1445