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