AudioFlinger.h revision 470aa50c36089fbe0427557f7cf4464dd26a1c52
1/*
2**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9**     http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18#ifndef ANDROID_AUDIO_FLINGER_H
19#define ANDROID_AUDIO_FLINGER_H
20
21#include <stdint.h>
22#include <sys/types.h>
23#include <limits.h>
24
25#include <common_time/cc_helper.h>
26
27#include <media/IAudioFlinger.h>
28#include <media/IAudioFlingerClient.h>
29#include <media/IAudioTrack.h>
30#include <media/IAudioRecord.h>
31#include <media/AudioSystem.h>
32#include <media/AudioTrack.h>
33
34#include <utils/Atomic.h>
35#include <utils/Errors.h>
36#include <utils/threads.h>
37#include <utils/SortedVector.h>
38#include <utils/TypeHelpers.h>
39#include <utils/Vector.h>
40
41#include <binder/BinderService.h>
42#include <binder/MemoryDealer.h>
43
44#include <system/audio.h>
45#include <hardware/audio.h>
46
47#include "AudioBufferProvider.h"
48
49#include <powermanager/IPowerManager.h>
50
51namespace android {
52
53class audio_track_cblk_t;
54class effect_param_cblk_t;
55class AudioMixer;
56class AudioBuffer;
57class AudioResampler;
58
59// ----------------------------------------------------------------------------
60
61// AudioFlinger has a hard-coded upper limit of 2 channels for capture and playback.
62// There is support for > 2 channel tracks down-mixed to 2 channel output via a down-mix effect.
63// Adding full support for > 2 channel capture or playback would require more than simply changing
64// this #define.  There is an independent hard-coded upper limit in AudioMixer;
65// removing that AudioMixer limit would be necessary but insufficient to support > 2 channels.
66// The macro FCC_2 highlights some (but not all) places where there is are 2-channel assumptions.
67// Search also for "2", "left", "right", "[0]", "[1]", ">> 16", "<< 16", etc.
68#define FCC_2 2     // FCC_2 = Fixed Channel Count 2
69
70static const nsecs_t kDefaultStandbyTimeInNsecs = seconds(3);
71
72class AudioFlinger :
73    public BinderService<AudioFlinger>,
74    public BnAudioFlinger
75{
76    friend class BinderService<AudioFlinger>;   // for AudioFlinger()
77public:
78    static const char* getServiceName() { return "media.audio_flinger"; }
79
80    virtual     status_t    dump(int fd, const Vector<String16>& args);
81
82    // IAudioFlinger interface, in binder opcode order
83    virtual sp<IAudioTrack> createTrack(
84                                pid_t pid,
85                                audio_stream_type_t streamType,
86                                uint32_t sampleRate,
87                                audio_format_t format,
88                                uint32_t channelMask,
89                                int frameCount,
90                                uint32_t flags,
91                                const sp<IMemory>& sharedBuffer,
92                                audio_io_handle_t output,
93                                bool isTimed,
94                                int *sessionId,
95                                status_t *status);
96
97    virtual sp<IAudioRecord> openRecord(
98                                pid_t pid,
99                                audio_io_handle_t input,
100                                uint32_t sampleRate,
101                                audio_format_t format,
102                                uint32_t channelMask,
103                                int frameCount,
104                                uint32_t flags,
105                                int *sessionId,
106                                status_t *status);
107
108    virtual     uint32_t    sampleRate(audio_io_handle_t output) const;
109    virtual     int         channelCount(audio_io_handle_t output) const;
110    virtual     audio_format_t format(audio_io_handle_t output) const;
111    virtual     size_t      frameCount(audio_io_handle_t output) const;
112    virtual     uint32_t    latency(audio_io_handle_t output) const;
113
114    virtual     status_t    setMasterVolume(float value);
115    virtual     status_t    setMasterMute(bool muted);
116
117    virtual     float       masterVolume() const;
118    virtual     float       masterVolumeSW() const;
119    virtual     bool        masterMute() const;
120
121    virtual     status_t    setStreamVolume(audio_stream_type_t stream, float value,
122                                            audio_io_handle_t output);
123    virtual     status_t    setStreamMute(audio_stream_type_t stream, bool muted);
124
125    virtual     float       streamVolume(audio_stream_type_t stream,
126                                         audio_io_handle_t output) const;
127    virtual     bool        streamMute(audio_stream_type_t stream) const;
128
129    virtual     status_t    setMode(audio_mode_t mode);
130
131    virtual     status_t    setMicMute(bool state);
132    virtual     bool        getMicMute() const;
133
134    virtual     status_t    setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs);
135    virtual     String8     getParameters(audio_io_handle_t ioHandle, const String8& keys) const;
136
137    virtual     void        registerClient(const sp<IAudioFlingerClient>& client);
138
139    virtual     size_t      getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const;
140
141    virtual audio_io_handle_t openOutput(uint32_t *pDevices,
142                                    uint32_t *pSamplingRate,
143                                    audio_format_t *pFormat,
144                                    uint32_t *pChannels,
145                                    uint32_t *pLatencyMs,
146                                    audio_policy_output_flags_t flags);
147
148    virtual audio_io_handle_t openDuplicateOutput(audio_io_handle_t output1,
149                                                  audio_io_handle_t output2);
150
151    virtual status_t closeOutput(audio_io_handle_t output);
152
153    virtual status_t suspendOutput(audio_io_handle_t output);
154
155    virtual status_t restoreOutput(audio_io_handle_t output);
156
157    virtual audio_io_handle_t openInput(uint32_t *pDevices,
158                            uint32_t *pSamplingRate,
159                            audio_format_t *pFormat,
160                            uint32_t *pChannels,
161                            audio_in_acoustics_t acoustics);
162
163    virtual status_t closeInput(audio_io_handle_t input);
164
165    virtual status_t setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output);
166
167    virtual status_t setVoiceVolume(float volume);
168
169    virtual status_t getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
170                                       audio_io_handle_t output) const;
171
172    virtual     unsigned int  getInputFramesLost(audio_io_handle_t ioHandle) const;
173
174    virtual int newAudioSessionId();
175
176    virtual void acquireAudioSessionId(int audioSession);
177
178    virtual void releaseAudioSessionId(int audioSession);
179
180    virtual status_t queryNumberEffects(uint32_t *numEffects) const;
181
182    virtual status_t queryEffect(uint32_t index, effect_descriptor_t *descriptor) const;
183
184    virtual status_t getEffectDescriptor(const effect_uuid_t *pUuid,
185                                         effect_descriptor_t *descriptor) const;
186
187    virtual sp<IEffect> createEffect(pid_t pid,
188                        effect_descriptor_t *pDesc,
189                        const sp<IEffectClient>& effectClient,
190                        int32_t priority,
191                        audio_io_handle_t io,
192                        int sessionId,
193                        status_t *status,
194                        int *id,
195                        int *enabled);
196
197    virtual status_t moveEffects(int sessionId, audio_io_handle_t srcOutput,
198                        audio_io_handle_t dstOutput);
199
200    virtual     status_t    onTransact(
201                                uint32_t code,
202                                const Parcel& data,
203                                Parcel* reply,
204                                uint32_t flags);
205
206    // end of IAudioFlinger interface
207
208private:
209               audio_mode_t getMode() const { return mMode; }
210
211                bool        btNrecIsOff() const { return mBtNrecIsOff; }
212
213                            AudioFlinger();
214    virtual                 ~AudioFlinger();
215
216    // call in any IAudioFlinger method that accesses mPrimaryHardwareDev
217    status_t                initCheck() const { return mPrimaryHardwareDev == NULL ? NO_INIT : NO_ERROR; }
218
219    // RefBase
220    virtual     void        onFirstRef();
221
222    audio_hw_device_t*      findSuitableHwDev_l(uint32_t devices);
223    void                    purgeStaleEffects_l();
224
225    // standby delay for MIXER and DUPLICATING playback threads is read from property
226    // ro.audio.flinger_standbytime_ms or defaults to kDefaultStandbyTimeInNsecs
227    static nsecs_t          mStandbyTimeInNsecs;
228
229    // Internal dump utilites.
230    status_t dumpPermissionDenial(int fd, const Vector<String16>& args);
231    status_t dumpClients(int fd, const Vector<String16>& args);
232    status_t dumpInternals(int fd, const Vector<String16>& args);
233
234    // --- Client ---
235    class Client : public RefBase {
236    public:
237                            Client(const sp<AudioFlinger>& audioFlinger, pid_t pid);
238        virtual             ~Client();
239        sp<MemoryDealer>    heap() const;
240        pid_t               pid() const { return mPid; }
241        sp<AudioFlinger>    audioFlinger() const { return mAudioFlinger; }
242
243        bool reserveTimedTrack();
244        void releaseTimedTrack();
245
246    private:
247                            Client(const Client&);
248                            Client& operator = (const Client&);
249        const sp<AudioFlinger> mAudioFlinger;
250        const sp<MemoryDealer> mMemoryDealer;
251        const pid_t         mPid;
252
253        Mutex               mTimedTrackLock;
254        int                 mTimedTrackCount;
255    };
256
257    // --- Notification Client ---
258    class NotificationClient : public IBinder::DeathRecipient {
259    public:
260                            NotificationClient(const sp<AudioFlinger>& audioFlinger,
261                                                const sp<IAudioFlingerClient>& client,
262                                                pid_t pid);
263        virtual             ~NotificationClient();
264
265                sp<IAudioFlingerClient> audioFlingerClient() const { return mAudioFlingerClient; }
266
267                // IBinder::DeathRecipient
268                virtual     void        binderDied(const wp<IBinder>& who);
269
270    private:
271                            NotificationClient(const NotificationClient&);
272                            NotificationClient& operator = (const NotificationClient&);
273
274        const sp<AudioFlinger>  mAudioFlinger;
275        const pid_t             mPid;
276        const sp<IAudioFlingerClient> mAudioFlingerClient;
277    };
278
279    class TrackHandle;
280    class RecordHandle;
281    class RecordThread;
282    class PlaybackThread;
283    class MixerThread;
284    class DirectOutputThread;
285    class DuplicatingThread;
286    class Track;
287    class RecordTrack;
288    class EffectModule;
289    class EffectHandle;
290    class EffectChain;
291    struct AudioStreamOut;
292    struct AudioStreamIn;
293
294    class ThreadBase : public Thread {
295    public:
296
297        enum type_t {
298            MIXER,              // Thread class is MixerThread
299            DIRECT,             // Thread class is DirectOutputThread
300            DUPLICATING,        // Thread class is DuplicatingThread
301            RECORD              // Thread class is RecordThread
302        };
303
304        ThreadBase (const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id, uint32_t device, type_t type);
305        virtual             ~ThreadBase();
306
307        status_t dumpBase(int fd, const Vector<String16>& args);
308        status_t dumpEffectChains(int fd, const Vector<String16>& args);
309
310        void clearPowerManager();
311
312        // base for record and playback
313        class TrackBase : public AudioBufferProvider, public RefBase {
314
315        public:
316            enum track_state {
317                IDLE,
318                TERMINATED,
319                // These are order-sensitive; do not change order without reviewing the impact.
320                // In particular there are assumptions about > STOPPED.
321                STOPPED,
322                RESUMING,
323                ACTIVE,
324                PAUSING,
325                PAUSED
326            };
327
328                                TrackBase(ThreadBase *thread,
329                                        const sp<Client>& client,
330                                        uint32_t sampleRate,
331                                        audio_format_t format,
332                                        uint32_t channelMask,
333                                        int frameCount,
334                                        const sp<IMemory>& sharedBuffer,
335                                        int sessionId);
336            virtual             ~TrackBase();
337
338            virtual status_t    start(pid_t tid) = 0;
339            virtual void        stop() = 0;
340                    sp<IMemory> getCblk() const { return mCblkMemory; }
341                    audio_track_cblk_t* cblk() const { return mCblk; }
342                    int         sessionId() const { return mSessionId; }
343
344        protected:
345                                TrackBase(const TrackBase&);
346                                TrackBase& operator = (const TrackBase&);
347
348            // AudioBufferProvider interface
349            virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts) = 0;
350            virtual void releaseBuffer(AudioBufferProvider::Buffer* buffer);
351
352            audio_format_t format() const {
353                return mFormat;
354            }
355
356            int channelCount() const { return mChannelCount; }
357
358            uint32_t channelMask() const { return mChannelMask; }
359
360            int sampleRate() const; // FIXME inline after cblk sr moved
361
362            void* getBuffer(uint32_t offset, uint32_t frames) const;
363
364            bool isStopped() const {
365                return mState == STOPPED;
366            }
367
368            bool isTerminated() const {
369                return mState == TERMINATED;
370            }
371
372            bool step();
373            void reset();
374
375            const wp<ThreadBase> mThread;
376            /*const*/ sp<Client> mClient;   // see explanation at ~TrackBase() why not const
377            sp<IMemory>         mCblkMemory;
378            audio_track_cblk_t* mCblk;
379            void*               mBuffer;
380            void*               mBufferEnd;
381            uint32_t            mFrameCount;
382            // we don't really need a lock for these
383            track_state         mState;
384            const audio_format_t mFormat;
385            bool                mStepServerFailed;
386            const int           mSessionId;
387            uint8_t             mChannelCount;
388            uint32_t            mChannelMask;
389        };
390
391        class ConfigEvent {
392        public:
393            ConfigEvent() : mEvent(0), mParam(0) {}
394
395            int mEvent;
396            int mParam;
397        };
398
399        class PMDeathRecipient : public IBinder::DeathRecipient {
400        public:
401                        PMDeathRecipient(const wp<ThreadBase>& thread) : mThread(thread) {}
402            virtual     ~PMDeathRecipient() {}
403
404            // IBinder::DeathRecipient
405            virtual     void        binderDied(const wp<IBinder>& who);
406
407        private:
408                        PMDeathRecipient(const PMDeathRecipient&);
409                        PMDeathRecipient& operator = (const PMDeathRecipient&);
410
411            wp<ThreadBase> mThread;
412        };
413
414        virtual     status_t    initCheck() const = 0;
415                    type_t      type() const { return mType; }
416                    uint32_t    sampleRate() const { return mSampleRate; }
417                    int         channelCount() const { return mChannelCount; }
418                    audio_format_t format() const { return mFormat; }
419                    size_t      frameCount() const { return mFrameCount; }
420                    void        wakeUp()    { mWaitWorkCV.broadcast(); }
421        // Should be "virtual status_t requestExitAndWait()" and override same
422        // method in Thread, but Thread::requestExitAndWait() is not yet virtual.
423                    void        exit();
424        virtual     bool        checkForNewParameters_l() = 0;
425        virtual     status_t    setParameters(const String8& keyValuePairs);
426        virtual     String8     getParameters(const String8& keys) = 0;
427        virtual     void        audioConfigChanged_l(int event, int param = 0) = 0;
428                    void        sendConfigEvent(int event, int param = 0);
429                    void        sendConfigEvent_l(int event, int param = 0);
430                    void        processConfigEvents();
431                    audio_io_handle_t id() const { return mId;}
432                    bool        standby() const { return mStandby; }
433                    uint32_t    device() const { return mDevice; }
434        virtual     audio_stream_t* stream() = 0;
435
436                    sp<EffectHandle> createEffect_l(
437                                        const sp<AudioFlinger::Client>& client,
438                                        const sp<IEffectClient>& effectClient,
439                                        int32_t priority,
440                                        int sessionId,
441                                        effect_descriptor_t *desc,
442                                        int *enabled,
443                                        status_t *status);
444                    void disconnectEffect(const sp< EffectModule>& effect,
445                                          const wp<EffectHandle>& handle,
446                                          bool unpinIfLast);
447
448                    // return values for hasAudioSession (bit field)
449                    enum effect_state {
450                        EFFECT_SESSION = 0x1,   // the audio session corresponds to at least one
451                                                // effect
452                        TRACK_SESSION = 0x2     // the audio session corresponds to at least one
453                                                // track
454                    };
455
456                    // get effect chain corresponding to session Id.
457                    sp<EffectChain> getEffectChain(int sessionId);
458                    // same as getEffectChain() but must be called with ThreadBase mutex locked
459                    sp<EffectChain> getEffectChain_l(int sessionId);
460                    // add an effect chain to the chain list (mEffectChains)
461        virtual     status_t addEffectChain_l(const sp<EffectChain>& chain) = 0;
462                    // remove an effect chain from the chain list (mEffectChains)
463        virtual     size_t removeEffectChain_l(const sp<EffectChain>& chain) = 0;
464                    // lock all effect chains Mutexes. Must be called before releasing the
465                    // ThreadBase mutex before processing the mixer and effects. This guarantees the
466                    // integrity of the chains during the process.
467                    // Also sets the parameter 'effectChains' to current value of mEffectChains.
468                    void lockEffectChains_l(Vector<sp <EffectChain> >& effectChains);
469                    // unlock effect chains after process
470                    void unlockEffectChains(const 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;      // for mEffectChains
531
532                    const type_t            mType;
533
534                    // Used by parameters, config events, addTrack_l, exit
535                    Condition               mWaitWorkCV;
536
537                    const sp<AudioFlinger>  mAudioFlinger;
538                    uint32_t                mSampleRate;
539                    size_t                  mFrameCount;
540                    uint32_t                mChannelMask;
541                    uint16_t                mChannelCount;
542                    size_t                  mFrameSize;
543                    audio_format_t          mFormat;
544
545                    // Parameter sequence by client: binder thread calling setParameters():
546                    //  1. Lock mLock
547                    //  2. Append to mNewParameters
548                    //  3. mWaitWorkCV.signal
549                    //  4. mParamCond.waitRelative with timeout
550                    //  5. read mParamStatus
551                    //  6. mWaitWorkCV.signal
552                    //  7. Unlock
553                    //
554                    // Parameter sequence by server: threadLoop calling checkForNewParameters_l():
555                    // 1. Lock mLock
556                    // 2. If there is an entry in mNewParameters proceed ...
557                    // 2. Read first entry in mNewParameters
558                    // 3. Process
559                    // 4. Remove first entry from mNewParameters
560                    // 5. Set mParamStatus
561                    // 6. mParamCond.signal
562                    // 7. mWaitWorkCV.wait with timeout (this is to avoid overwriting mParamStatus)
563                    // 8. Unlock
564                    Condition               mParamCond;
565                    Vector<String8>         mNewParameters;
566                    status_t                mParamStatus;
567
568                    Vector<ConfigEvent>     mConfigEvents;
569                    bool                    mStandby;
570                    const audio_io_handle_t mId;
571                    Vector< sp<EffectChain> > mEffectChains;
572                    uint32_t                mDevice;    // output device for PlaybackThread
573                                                        // input + output devices for RecordThread
574                    static const int        kNameLength = 16;   // prctl(PR_SET_NAME) limit
575                    char                    mName[kNameLength];
576                    sp<IPowerManager>       mPowerManager;
577                    sp<IBinder>             mWakeLockToken;
578                    const sp<PMDeathRecipient> mDeathRecipient;
579                    // list of suspended effects per session and per type. The first vector is
580                    // keyed by session ID, the second by type UUID timeLow field
581                    KeyedVector< int, KeyedVector< int, sp<SuspendedSessionDesc> > >  mSuspendedSessions;
582    };
583
584    struct  stream_type_t {
585        stream_type_t()
586            :   volume(1.0f),
587                mute(false),
588                valid(true)
589        {
590        }
591        float       volume;
592        bool        mute;
593        bool        valid;
594    };
595
596    // --- PlaybackThread ---
597    class PlaybackThread : public ThreadBase {
598    public:
599
600        enum mixer_state {
601            MIXER_IDLE,             // no active tracks
602            MIXER_TRACKS_ENABLED,   // at least one active track, but no track has any data ready
603            MIXER_TRACKS_READY      // at least one active track, and at least one track has data
604            // standby mode does not have an enum value
605            // suspend by audio policy manager is orthogonal to mixer state
606        };
607
608        // playback track
609        class Track : public TrackBase {
610        public:
611                                Track(  PlaybackThread *thread,
612                                        const sp<Client>& client,
613                                        audio_stream_type_t streamType,
614                                        uint32_t sampleRate,
615                                        audio_format_t format,
616                                        uint32_t channelMask,
617                                        int frameCount,
618                                        const sp<IMemory>& sharedBuffer,
619                                        int sessionId);
620            virtual             ~Track();
621
622                    void        dump(char* buffer, size_t size);
623            virtual status_t    start(pid_t tid);
624            virtual void        stop();
625                    void        pause();
626
627                    void        flush();
628                    void        destroy();
629                    void        mute(bool);
630                    int name() const {
631                        return mName;
632                    }
633
634                    audio_stream_type_t streamType() const {
635                        return mStreamType;
636                    }
637                    status_t    attachAuxEffect(int EffectId);
638                    void        setAuxBuffer(int EffectId, int32_t *buffer);
639                    int32_t     *auxBuffer() const { return mAuxBuffer; }
640                    void        setMainBuffer(int16_t *buffer) { mMainBuffer = buffer; }
641                    int16_t     *mainBuffer() const { return mMainBuffer; }
642                    int         auxEffectId() const { return mAuxEffectId; }
643
644        protected:
645            // for numerous
646            friend class PlaybackThread;
647            friend class MixerThread;
648            friend class DirectOutputThread;
649
650                                Track(const Track&);
651                                Track& operator = (const Track&);
652
653            // AudioBufferProvider interface
654            virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts = kInvalidPTS);
655            // releaseBuffer() not overridden
656
657            virtual uint32_t framesReady() const;
658
659            bool isMuted() const { return mMute; }
660            bool isPausing() const {
661                return mState == PAUSING;
662            }
663            bool isPaused() const {
664                return mState == PAUSED;
665            }
666            bool isReady() const;
667            void setPaused() { mState = PAUSED; }
668            void reset();
669
670            bool isOutputTrack() const {
671                return (mStreamType == AUDIO_STREAM_CNT);
672            }
673
674        public:
675            virtual bool isTimedTrack() const { return false; }
676        protected:
677
678            // we don't really need a lock for these
679            volatile bool       mMute;
680            // FILLED state is used for suppressing volume ramp at begin of playing
681            enum {FS_FILLING, FS_FILLED, FS_ACTIVE};
682            mutable uint8_t     mFillingUpStatus;
683            int8_t              mRetryCount;
684            sp<IMemory>         mSharedBuffer;
685            bool                mResetDone;
686            audio_stream_type_t mStreamType;
687            int                 mName;
688            int16_t             *mMainBuffer;
689            int32_t             *mAuxBuffer;
690            int                 mAuxEffectId;
691            bool                mHasVolumeController;
692        };  // end of Track
693
694        class TimedTrack : public Track {
695          public:
696            static sp<TimedTrack> create(PlaybackThread *thread,
697                                         const sp<Client>& client,
698                                         audio_stream_type_t streamType,
699                                         uint32_t sampleRate,
700                                         audio_format_t format,
701                                         uint32_t channelMask,
702                                         int frameCount,
703                                         const sp<IMemory>& sharedBuffer,
704                                         int sessionId);
705            ~TimedTrack();
706
707            class TimedBuffer {
708              public:
709                TimedBuffer();
710                TimedBuffer(const sp<IMemory>& buffer, int64_t pts);
711                const sp<IMemory>& buffer() const { return mBuffer; }
712                int64_t pts() const { return mPTS; }
713                int position() const { return mPosition; }
714                void setPosition(int pos) { mPosition = pos; }
715              private:
716                sp<IMemory> mBuffer;
717                int64_t mPTS;
718                int mPosition;
719            };
720
721            virtual bool isTimedTrack() const { return true; }
722
723            virtual uint32_t framesReady() const;
724
725            // AudioBufferProvider interface
726            virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts);
727            virtual void releaseBuffer(AudioBufferProvider::Buffer* buffer);
728
729            void timedYieldSamples(AudioBufferProvider::Buffer* buffer);
730            void timedYieldSilence(uint32_t numFrames,
731                                   AudioBufferProvider::Buffer* buffer);
732
733            status_t    allocateTimedBuffer(size_t size,
734                                            sp<IMemory>* buffer);
735            status_t    queueTimedBuffer(const sp<IMemory>& buffer,
736                                         int64_t pts);
737            status_t    setMediaTimeTransform(const LinearTransform& xform,
738                                              TimedAudioTrack::TargetTimeline target);
739            void        trimTimedBufferQueue_l();
740
741          private:
742            TimedTrack(PlaybackThread *thread,
743                       const sp<Client>& client,
744                       audio_stream_type_t streamType,
745                       uint32_t sampleRate,
746                       audio_format_t format,
747                       uint32_t channelMask,
748                       int frameCount,
749                       const sp<IMemory>& sharedBuffer,
750                       int sessionId);
751
752            uint64_t            mLocalTimeFreq;
753            LinearTransform     mLocalTimeToSampleTransform;
754            sp<MemoryDealer>    mTimedMemoryDealer;
755            Vector<TimedBuffer> mTimedBufferQueue;
756            uint8_t*            mTimedSilenceBuffer;
757            uint32_t            mTimedSilenceBufferSize;
758            mutable Mutex       mTimedBufferQueueLock;
759            bool                mTimedAudioOutputOnTime;
760            CCHelper            mCCHelper;
761
762            Mutex               mMediaTimeTransformLock;
763            LinearTransform     mMediaTimeTransform;
764            bool                mMediaTimeTransformValid;
765            TimedAudioTrack::TargetTimeline mMediaTimeTransformTarget;
766        };
767
768
769        // playback track
770        class OutputTrack : public Track {
771        public:
772
773            class Buffer: public AudioBufferProvider::Buffer {
774            public:
775                int16_t *mBuffer;
776            };
777
778                                OutputTrack(PlaybackThread *thread,
779                                        DuplicatingThread *sourceThread,
780                                        uint32_t sampleRate,
781                                        audio_format_t format,
782                                        uint32_t channelMask,
783                                        int frameCount);
784            virtual             ~OutputTrack();
785
786            virtual status_t    start(pid_t tid);
787            virtual void        stop();
788                    bool        write(int16_t* data, uint32_t frames);
789                    bool        bufferQueueEmpty() const { return mBufferQueue.size() == 0; }
790                    bool        isActive() const { return mActive; }
791            const wp<ThreadBase>& thread() const { return mThread; }
792
793        private:
794
795            enum {
796                NO_MORE_BUFFERS = 0x80000001,   // same in AudioTrack.h, ok to be different value
797            };
798
799            status_t            obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs);
800            void                clearBufferQueue();
801
802            // Maximum number of pending buffers allocated by OutputTrack::write()
803            static const uint8_t kMaxOverFlowBuffers = 10;
804
805            Vector < Buffer* >          mBufferQueue;
806            AudioBufferProvider::Buffer mOutBuffer;
807            bool                        mActive;
808            DuplicatingThread* const mSourceThread; // for waitTimeMs() in write()
809        };  // end of OutputTrack
810
811        PlaybackThread (const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
812                        audio_io_handle_t id, uint32_t device, type_t type);
813        virtual             ~PlaybackThread();
814
815                    status_t    dump(int fd, const Vector<String16>& args);
816
817        // Thread virtuals
818        virtual     status_t    readyToRun();
819        virtual     bool        threadLoop();
820
821        // RefBase
822        virtual     void        onFirstRef();
823
824protected:
825        // Code snippets that were lifted up out of threadLoop()
826        virtual     void        threadLoop_mix() = 0;
827        virtual     void        threadLoop_sleepTime() = 0;
828        virtual     void        threadLoop_write();
829        virtual     void        threadLoop_standby();
830
831        // Non-trivial for DIRECT only
832        virtual     void        applyVolume() { }
833
834                    // prepareTracks_l reads and writes mActiveTracks, and also returns the
835                    // pending set of tracks to remove via Vector 'tracksToRemove'.  The caller is
836                    // responsible for clearing or destroying this Vector later on, when it
837                    // is safe to do so. That will drop the final ref count and destroy the tracks.
838        virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove) = 0;
839
840public:
841
842        virtual     status_t    initCheck() const { return (mOutput == NULL) ? NO_INIT : NO_ERROR; }
843
844                    // return estimated latency in milliseconds, as reported by HAL
845                    uint32_t    latency() const;
846
847                    void        setMasterVolume(float value);
848                    void        setMasterMute(bool muted);
849
850                    void        setStreamVolume(audio_stream_type_t stream, float value);
851                    void        setStreamMute(audio_stream_type_t stream, bool muted);
852
853                    float       streamVolume(audio_stream_type_t stream) const;
854
855                    sp<Track>   createTrack_l(
856                                    const sp<AudioFlinger::Client>& client,
857                                    audio_stream_type_t streamType,
858                                    uint32_t sampleRate,
859                                    audio_format_t format,
860                                    uint32_t channelMask,
861                                    int frameCount,
862                                    const sp<IMemory>& sharedBuffer,
863                                    int sessionId,
864                                    bool isTimed,
865                                    status_t *status);
866
867                    AudioStreamOut* getOutput() const;
868                    AudioStreamOut* clearOutput();
869                    virtual audio_stream_t* stream();
870
871                    void        suspend() { mSuspended++; }
872                    void        restore() { if (mSuspended > 0) mSuspended--; }
873                    bool        isSuspended() const { return (mSuspended > 0); }
874        virtual     String8     getParameters(const String8& keys);
875        virtual     void        audioConfigChanged_l(int event, int param = 0);
876                    status_t    getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames);
877                    int16_t     *mixBuffer() const { return mMixBuffer; };
878
879        virtual     void detachAuxEffect_l(int effectId);
880                    status_t attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track> track,
881                            int EffectId);
882                    status_t attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track> track,
883                            int EffectId);
884
885                    virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
886                    virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
887                    virtual uint32_t hasAudioSession(int sessionId);
888                    virtual uint32_t getStrategyForSession_l(int sessionId);
889
890                            void setStreamValid(audio_stream_type_t streamType, bool valid);
891
892    protected:
893        int16_t*                        mMixBuffer;
894        uint32_t                        mSuspended;     // suspend count, > 0 means suspended
895        int                             mBytesWritten;
896    private:
897        // mMasterMute is in both PlaybackThread and in AudioFlinger.  When a
898        // PlaybackThread needs to find out if master-muted, it checks it's local
899        // copy rather than the one in AudioFlinger.  This optimization saves a lock.
900        bool                            mMasterMute;
901                    void        setMasterMute_l(bool muted) { mMasterMute = muted; }
902    protected:
903        SortedVector< wp<Track> >       mActiveTracks;
904
905        virtual int             getTrackName_l() = 0;
906        virtual void            deleteTrackName_l(int name) = 0;
907        virtual uint32_t        activeSleepTimeUs();
908        virtual uint32_t        idleSleepTimeUs() = 0;
909        virtual uint32_t        suspendSleepTimeUs() = 0;
910
911        // Code snippets that are temporarily lifted up out of threadLoop() until the merge
912                    void        checkSilentMode_l();
913
914        // Non-trivial for DUPLICATING only
915        virtual     void        saveOutputTracks() { }
916        virtual     void        clearOutputTracks() { }
917
918        // Cache various calculated values, at threadLoop() entry and after a parameter change
919        virtual     void        cacheParameters_l();
920
921    private:
922
923        friend class AudioFlinger;      // for numerous
924
925        PlaybackThread(const Client&);
926        PlaybackThread& operator = (const PlaybackThread&);
927
928        status_t    addTrack_l(const sp<Track>& track);
929        void        destroyTrack_l(const sp<Track>& track);
930        void        removeTrack_l(const sp<Track>& track);
931
932        void        readOutputParameters();
933
934        virtual status_t    dumpInternals(int fd, const Vector<String16>& args);
935        status_t    dumpTracks(int fd, const Vector<String16>& args);
936
937        SortedVector< sp<Track> >       mTracks;
938        // mStreamTypes[] uses 1 additional stream type internally for the OutputTrack used by DuplicatingThread
939        stream_type_t                   mStreamTypes[AUDIO_STREAM_CNT + 1];
940        AudioStreamOut                  *mOutput;
941        float                           mMasterVolume;
942        nsecs_t                         mLastWriteTime;
943        int                             mNumWrites;
944        int                             mNumDelayedWrites;
945        bool                            mInWrite;
946
947        // FIXME rename these former local variables of threadLoop to standard "m" names
948        nsecs_t                         standbyTime;
949        size_t                          mixBufferSize;
950
951        // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l()
952        uint32_t                        activeSleepTime;
953        uint32_t                        idleSleepTime;
954
955        uint32_t                        sleepTime;
956
957        // mixer status returned by prepareTracks_l()
958        mixer_state                     mMixerStatus;       // current cycle
959        mixer_state                     mPrevMixerStatus;   // previous cycle
960
961        // FIXME move these declarations into the specific sub-class that needs them
962        // MIXER only
963        bool                            longStandbyExit;
964        uint32_t                        sleepTimeShift;
965
966        // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value
967        nsecs_t                         standbyDelay;
968
969        // MIXER only
970        nsecs_t                         maxPeriod;
971
972        // DUPLICATING only
973        uint32_t                        writeFrames;
974    };
975
976    class MixerThread : public PlaybackThread {
977    public:
978        MixerThread (const sp<AudioFlinger>& audioFlinger,
979                     AudioStreamOut* output,
980                     audio_io_handle_t id,
981                     uint32_t device,
982                     type_t type = MIXER);
983        virtual             ~MixerThread();
984
985        // Thread virtuals
986
987                    void        invalidateTracks(audio_stream_type_t streamType);
988        virtual     bool        checkForNewParameters_l();
989        virtual     status_t    dumpInternals(int fd, const Vector<String16>& args);
990
991    protected:
992        virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
993        virtual     int         getTrackName_l();
994        virtual     void        deleteTrackName_l(int name);
995        virtual     uint32_t    idleSleepTimeUs();
996        virtual     uint32_t    suspendSleepTimeUs();
997        virtual     void        cacheParameters_l();
998
999        // threadLoop snippets
1000        virtual     void        threadLoop_mix();
1001        virtual     void        threadLoop_sleepTime();
1002
1003                    AudioMixer* mAudioMixer;
1004    };
1005
1006    class DirectOutputThread : public PlaybackThread {
1007    public:
1008
1009        DirectOutputThread (const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
1010                            audio_io_handle_t id, uint32_t device);
1011        virtual                 ~DirectOutputThread();
1012
1013        // Thread virtuals
1014
1015        virtual     bool        checkForNewParameters_l();
1016
1017    protected:
1018        virtual     int         getTrackName_l();
1019        virtual     void        deleteTrackName_l(int name);
1020        virtual     uint32_t    activeSleepTimeUs();
1021        virtual     uint32_t    idleSleepTimeUs();
1022        virtual     uint32_t    suspendSleepTimeUs();
1023        virtual     void        cacheParameters_l();
1024
1025        // threadLoop snippets
1026        virtual     mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
1027        virtual     void        threadLoop_mix();
1028        virtual     void        threadLoop_sleepTime();
1029
1030        // volumes last sent to audio HAL with stream->set_volume()
1031        // FIXME use standard representation and names
1032        float mLeftVolFloat;
1033        float mRightVolFloat;
1034        uint16_t mLeftVolShort;
1035        uint16_t mRightVolShort;
1036
1037        // FIXME rename these former local variables of threadLoop to standard names
1038        // next 3 were local to the while !exitingPending loop
1039        bool rampVolume;
1040        uint16_t leftVol;
1041        uint16_t rightVol;
1042
1043private:
1044                    void        applyVolume();  // FIXME inline into threadLoop_mix()
1045
1046        // prepareTracks_l() tells threadLoop_mix() the name of the single active track
1047        sp<Track>               mActiveTrack;
1048    };
1049
1050    class DuplicatingThread : public MixerThread {
1051    public:
1052        DuplicatingThread (const sp<AudioFlinger>& audioFlinger, MixerThread* mainThread,
1053                           audio_io_handle_t id);
1054        virtual                 ~DuplicatingThread();
1055
1056        // Thread virtuals
1057                    void        addOutputTrack(MixerThread* thread);
1058                    void        removeOutputTrack(MixerThread* thread);
1059                    uint32_t    waitTimeMs() { return mWaitTimeMs; }
1060    protected:
1061        virtual     uint32_t    activeSleepTimeUs();
1062
1063    private:
1064                    bool        outputsReady(const SortedVector<sp<OutputTrack> > &outputTracks);
1065    protected:
1066        // threadLoop snippets
1067        virtual     void        threadLoop_mix();
1068        virtual     void        threadLoop_sleepTime();
1069        virtual     void        threadLoop_write();
1070        virtual     void        threadLoop_standby();
1071        virtual     void        cacheParameters_l();
1072
1073    private:
1074        // called from threadLoop, addOutputTrack, removeOutputTrack
1075        virtual     void        updateWaitTime_l();
1076    protected:
1077        virtual     void        saveOutputTracks();
1078        virtual     void        clearOutputTracks();
1079    private:
1080
1081                    uint32_t    mWaitTimeMs;
1082        SortedVector < sp<OutputTrack> >  outputTracks;
1083        SortedVector < sp<OutputTrack> >  mOutputTracks;
1084    };
1085
1086              PlaybackThread *checkPlaybackThread_l(audio_io_handle_t output) const;
1087              MixerThread *checkMixerThread_l(audio_io_handle_t output) const;
1088              RecordThread *checkRecordThread_l(audio_io_handle_t input) const;
1089              // no range check, AudioFlinger::mLock held
1090              bool streamMute_l(audio_stream_type_t stream) const
1091                                { return mStreamTypes[stream].mute; }
1092              // no range check, doesn't check per-thread stream volume, AudioFlinger::mLock held
1093              float streamVolume_l(audio_stream_type_t stream) const
1094                                { return mStreamTypes[stream].volume; }
1095              void audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2);
1096
1097              // allocate an audio_io_handle_t, session ID, or effect ID
1098              uint32_t nextUniqueId();
1099
1100              status_t moveEffectChain_l(int sessionId,
1101                                     PlaybackThread *srcThread,
1102                                     PlaybackThread *dstThread,
1103                                     bool reRegister);
1104              // return thread associated with primary hardware device, or NULL
1105              PlaybackThread *primaryPlaybackThread_l() const;
1106              uint32_t primaryOutputDevice_l() const;
1107
1108    // server side of the client's IAudioTrack
1109    class TrackHandle : public android::BnAudioTrack {
1110    public:
1111                            TrackHandle(const sp<PlaybackThread::Track>& track);
1112        virtual             ~TrackHandle();
1113        virtual sp<IMemory> getCblk() const;
1114        virtual status_t    start(pid_t tid);
1115        virtual void        stop();
1116        virtual void        flush();
1117        virtual void        mute(bool);
1118        virtual void        pause();
1119        virtual status_t    attachAuxEffect(int effectId);
1120        virtual status_t    allocateTimedBuffer(size_t size,
1121                                                sp<IMemory>* buffer);
1122        virtual status_t    queueTimedBuffer(const sp<IMemory>& buffer,
1123                                             int64_t pts);
1124        virtual status_t    setMediaTimeTransform(const LinearTransform& xform,
1125                                                  int target);
1126        virtual status_t onTransact(
1127            uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags);
1128    private:
1129        const sp<PlaybackThread::Track> mTrack;
1130    };
1131
1132                void        removeClient_l(pid_t pid);
1133                void        removeNotificationClient(pid_t pid);
1134
1135
1136    // record thread
1137    class RecordThread : public ThreadBase, public AudioBufferProvider
1138    {
1139    public:
1140
1141        // record track
1142        class RecordTrack : public TrackBase {
1143        public:
1144                                RecordTrack(RecordThread *thread,
1145                                        const sp<Client>& client,
1146                                        uint32_t sampleRate,
1147                                        audio_format_t format,
1148                                        uint32_t channelMask,
1149                                        int frameCount,
1150                                        int sessionId);
1151            virtual             ~RecordTrack();
1152
1153            virtual status_t    start(pid_t tid);
1154            virtual void        stop();
1155
1156                    bool        overflow() { bool tmp = mOverflow; mOverflow = false; return tmp; }
1157                    bool        setOverflow() { bool tmp = mOverflow; mOverflow = true; return tmp; }
1158
1159                    void        dump(char* buffer, size_t size);
1160
1161        private:
1162            friend class AudioFlinger;  // for mState
1163
1164                                RecordTrack(const RecordTrack&);
1165                                RecordTrack& operator = (const RecordTrack&);
1166
1167            // AudioBufferProvider interface
1168            virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts = kInvalidPTS);
1169            // releaseBuffer() not overridden
1170
1171            bool                mOverflow;
1172        };
1173
1174
1175                RecordThread(const sp<AudioFlinger>& audioFlinger,
1176                        AudioStreamIn *input,
1177                        uint32_t sampleRate,
1178                        uint32_t channels,
1179                        audio_io_handle_t id,
1180                        uint32_t device);
1181                virtual     ~RecordThread();
1182
1183        // Thread
1184        virtual bool        threadLoop();
1185        virtual status_t    readyToRun();
1186
1187        // RefBase
1188        virtual void        onFirstRef();
1189
1190        virtual status_t    initCheck() const { return (mInput == NULL) ? NO_INIT : NO_ERROR; }
1191                sp<AudioFlinger::RecordThread::RecordTrack>  createRecordTrack_l(
1192                        const sp<AudioFlinger::Client>& client,
1193                        uint32_t sampleRate,
1194                        audio_format_t format,
1195                        int channelMask,
1196                        int frameCount,
1197                        int sessionId,
1198                        status_t *status);
1199
1200                status_t    start(RecordTrack* recordTrack);
1201                status_t    start(RecordTrack* recordTrack, pid_t tid);
1202                void        stop(RecordTrack* recordTrack);
1203                status_t    dump(int fd, const Vector<String16>& args);
1204                AudioStreamIn* getInput() const;
1205                AudioStreamIn* clearInput();
1206                virtual audio_stream_t* stream();
1207
1208        // AudioBufferProvider interface
1209        virtual status_t    getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts);
1210        virtual void        releaseBuffer(AudioBufferProvider::Buffer* buffer);
1211
1212        virtual bool        checkForNewParameters_l();
1213        virtual String8     getParameters(const String8& keys);
1214        virtual void        audioConfigChanged_l(int event, int param = 0);
1215                void        readInputParameters();
1216        virtual unsigned int  getInputFramesLost();
1217
1218        virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
1219        virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
1220        virtual uint32_t hasAudioSession(int sessionId);
1221                RecordTrack* track();
1222
1223    private:
1224                RecordThread();
1225                AudioStreamIn                       *mInput;
1226                RecordTrack*                        mTrack;
1227                sp<RecordTrack>                     mActiveTrack;
1228                Condition                           mStartStopCond;
1229                AudioResampler                      *mResampler;
1230                int32_t                             *mRsmpOutBuffer;
1231                int16_t                             *mRsmpInBuffer;
1232                size_t                              mRsmpInIndex;
1233                size_t                              mInputBytes;
1234                const int                           mReqChannelCount;
1235                const uint32_t                      mReqSampleRate;
1236                ssize_t                             mBytesRead;
1237    };
1238
1239    // server side of the client's IAudioRecord
1240    class RecordHandle : public android::BnAudioRecord {
1241    public:
1242        RecordHandle(const sp<RecordThread::RecordTrack>& recordTrack);
1243        virtual             ~RecordHandle();
1244        virtual sp<IMemory> getCblk() const;
1245        virtual status_t    start(pid_t tid);
1246        virtual void        stop();
1247        virtual status_t onTransact(
1248            uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags);
1249    private:
1250        const sp<RecordThread::RecordTrack> mRecordTrack;
1251    };
1252
1253    //--- Audio Effect Management
1254
1255    // EffectModule and EffectChain classes both have their own mutex to protect
1256    // state changes or resource modifications. Always respect the following order
1257    // if multiple mutexes must be acquired to avoid cross deadlock:
1258    // AudioFlinger -> ThreadBase -> EffectChain -> EffectModule
1259
1260    // The EffectModule class is a wrapper object controlling the effect engine implementation
1261    // in the effect library. It prevents concurrent calls to process() and command() functions
1262    // from different client threads. It keeps a list of EffectHandle objects corresponding
1263    // to all client applications using this effect and notifies applications of effect state,
1264    // control or parameter changes. It manages the activation state machine to send appropriate
1265    // reset, enable, disable commands to effect engine and provide volume
1266    // ramping when effects are activated/deactivated.
1267    // When controlling an auxiliary effect, the EffectModule also provides an input buffer used by
1268    // the attached track(s) to accumulate their auxiliary channel.
1269    class EffectModule: public RefBase {
1270    public:
1271        EffectModule(ThreadBase *thread,
1272                        const wp<AudioFlinger::EffectChain>& chain,
1273                        effect_descriptor_t *desc,
1274                        int id,
1275                        int sessionId);
1276        virtual ~EffectModule();
1277
1278        enum effect_state {
1279            IDLE,
1280            RESTART,
1281            STARTING,
1282            ACTIVE,
1283            STOPPING,
1284            STOPPED,
1285            DESTROYED
1286        };
1287
1288        int         id() const { return mId; }
1289        void process();
1290        void updateState();
1291        status_t command(uint32_t cmdCode,
1292                         uint32_t cmdSize,
1293                         void *pCmdData,
1294                         uint32_t *replySize,
1295                         void *pReplyData);
1296
1297        void reset_l();
1298        status_t configure();
1299        status_t init();
1300        effect_state state() const {
1301            return mState;
1302        }
1303        uint32_t status() {
1304            return mStatus;
1305        }
1306        int sessionId() const {
1307            return mSessionId;
1308        }
1309        status_t    setEnabled(bool enabled);
1310        bool isEnabled() const;
1311        bool isProcessEnabled() const;
1312
1313        void        setInBuffer(int16_t *buffer) { mConfig.inputCfg.buffer.s16 = buffer; }
1314        int16_t     *inBuffer() { return mConfig.inputCfg.buffer.s16; }
1315        void        setOutBuffer(int16_t *buffer) { mConfig.outputCfg.buffer.s16 = buffer; }
1316        int16_t     *outBuffer() { return mConfig.outputCfg.buffer.s16; }
1317        void        setChain(const wp<EffectChain>& chain) { mChain = chain; }
1318        void        setThread(const wp<ThreadBase>& thread) { mThread = thread; }
1319        const wp<ThreadBase>& thread() { return mThread; }
1320
1321        status_t addHandle(const sp<EffectHandle>& handle);
1322        void disconnect(const wp<EffectHandle>& handle, bool unpinIfLast);
1323        size_t removeHandle (const wp<EffectHandle>& handle);
1324
1325        effect_descriptor_t& desc() { return mDescriptor; }
1326        wp<EffectChain>&     chain() { return mChain; }
1327
1328        status_t         setDevice(uint32_t device);
1329        status_t         setVolume(uint32_t *left, uint32_t *right, bool controller);
1330        status_t         setMode(audio_mode_t mode);
1331        status_t         start();
1332        status_t         stop();
1333        void             setSuspended(bool suspended);
1334        bool             suspended() const;
1335
1336        sp<EffectHandle> controlHandle();
1337
1338        bool             isPinned() const { return mPinned; }
1339        void             unPin() { mPinned = false; }
1340
1341        status_t         dump(int fd, const Vector<String16>& args);
1342
1343    protected:
1344        friend class AudioFlinger;      // for mHandles
1345        bool                mPinned;
1346
1347        // Maximum time allocated to effect engines to complete the turn off sequence
1348        static const uint32_t MAX_DISABLE_TIME_MS = 10000;
1349
1350        EffectModule(const EffectModule&);
1351        EffectModule& operator = (const EffectModule&);
1352
1353        status_t start_l();
1354        status_t stop_l();
1355
1356mutable Mutex               mLock;      // mutex for process, commands and handles list protection
1357        wp<ThreadBase>      mThread;    // parent thread
1358        wp<EffectChain>     mChain;     // parent effect chain
1359        int                 mId;        // this instance unique ID
1360        int                 mSessionId; // audio session ID
1361        effect_descriptor_t mDescriptor;// effect descriptor received from effect engine
1362        effect_config_t     mConfig;    // input and output audio configuration
1363        effect_handle_t  mEffectInterface; // Effect module C API
1364        status_t            mStatus;    // initialization status
1365        effect_state        mState;     // current activation state
1366        Vector< wp<EffectHandle> > mHandles;    // list of client handles
1367                    // First handle in mHandles has highest priority and controls the effect module
1368        uint32_t mMaxDisableWaitCnt;    // maximum grace period before forcing an effect off after
1369                                        // sending disable command.
1370        uint32_t mDisableWaitCnt;       // current process() calls count during disable period.
1371        bool     mSuspended;            // effect is suspended: temporarily disabled by framework
1372    };
1373
1374    // The EffectHandle class implements the IEffect interface. It provides resources
1375    // to receive parameter updates, keeps track of effect control
1376    // ownership and state and has a pointer to the EffectModule object it is controlling.
1377    // There is one EffectHandle object for each application controlling (or using)
1378    // an effect module.
1379    // The EffectHandle is obtained by calling AudioFlinger::createEffect().
1380    class EffectHandle: public android::BnEffect {
1381    public:
1382
1383        EffectHandle(const sp<EffectModule>& effect,
1384                const sp<AudioFlinger::Client>& client,
1385                const sp<IEffectClient>& effectClient,
1386                int32_t priority);
1387        virtual ~EffectHandle();
1388
1389        // IEffect
1390        virtual status_t enable();
1391        virtual status_t disable();
1392        virtual status_t command(uint32_t cmdCode,
1393                                 uint32_t cmdSize,
1394                                 void *pCmdData,
1395                                 uint32_t *replySize,
1396                                 void *pReplyData);
1397        virtual void disconnect();
1398    private:
1399                void disconnect(bool unpinIfLast);
1400    public:
1401        virtual sp<IMemory> getCblk() const { return mCblkMemory; }
1402        virtual status_t onTransact(uint32_t code, const Parcel& data,
1403                Parcel* reply, uint32_t flags);
1404
1405
1406        // Give or take control of effect module
1407        // - hasControl: true if control is given, false if removed
1408        // - signal: true client app should be signaled of change, false otherwise
1409        // - enabled: state of the effect when control is passed
1410        void setControl(bool hasControl, bool signal, bool enabled);
1411        void commandExecuted(uint32_t cmdCode,
1412                             uint32_t cmdSize,
1413                             void *pCmdData,
1414                             uint32_t replySize,
1415                             void *pReplyData);
1416        void setEnabled(bool enabled);
1417        bool enabled() const { return mEnabled; }
1418
1419        // Getters
1420        int id() const { return mEffect->id(); }
1421        int priority() const { return mPriority; }
1422        bool hasControl() const { return mHasControl; }
1423        sp<EffectModule> effect() const { return mEffect; }
1424
1425        void dump(char* buffer, size_t size);
1426
1427    protected:
1428        friend class AudioFlinger;          // for mEffect, mHasControl, mEnabled
1429        EffectHandle(const EffectHandle&);
1430        EffectHandle& operator =(const EffectHandle&);
1431
1432        sp<EffectModule> mEffect;           // pointer to controlled EffectModule
1433        sp<IEffectClient> mEffectClient;    // callback interface for client notifications
1434        /*const*/ sp<Client> mClient;       // client for shared memory allocation, see disconnect()
1435        sp<IMemory>         mCblkMemory;    // shared memory for control block
1436        effect_param_cblk_t* mCblk;         // control block for deferred parameter setting via shared memory
1437        uint8_t*            mBuffer;        // pointer to parameter area in shared memory
1438        int mPriority;                      // client application priority to control the effect
1439        bool mHasControl;                   // true if this handle is controlling the effect
1440        bool mEnabled;                      // cached enable state: needed when the effect is
1441                                            // restored after being suspended
1442    };
1443
1444    // the EffectChain class represents a group of effects associated to one audio session.
1445    // There can be any number of EffectChain objects per output mixer thread (PlaybackThread).
1446    // The EffecChain with session ID 0 contains global effects applied to the output mix.
1447    // Effects in this chain can be insert or auxiliary. Effects in other chains (attached to tracks)
1448    // are insert only. The EffectChain maintains an ordered list of effect module, the order corresponding
1449    // in the effect process order. When attached to a track (session ID != 0), it also provide it's own
1450    // input buffer used by the track as accumulation buffer.
1451    class EffectChain: public RefBase {
1452    public:
1453        EffectChain(const wp<ThreadBase>& wThread, int sessionId);
1454        EffectChain(ThreadBase *thread, int sessionId);
1455        virtual ~EffectChain();
1456
1457        // special key used for an entry in mSuspendedEffects keyed vector
1458        // corresponding to a suspend all request.
1459        static const int        kKeyForSuspendAll = 0;
1460
1461        // minimum duration during which we force calling effect process when last track on
1462        // a session is stopped or removed to allow effect tail to be rendered
1463        static const int        kProcessTailDurationMs = 1000;
1464
1465        void process_l();
1466
1467        void lock() {
1468            mLock.lock();
1469        }
1470        void unlock() {
1471            mLock.unlock();
1472        }
1473
1474        status_t addEffect_l(const sp<EffectModule>& handle);
1475        size_t removeEffect_l(const sp<EffectModule>& handle);
1476
1477        int sessionId() const { return mSessionId; }
1478        void setSessionId(int sessionId) { mSessionId = sessionId; }
1479
1480        sp<EffectModule> getEffectFromDesc_l(effect_descriptor_t *descriptor);
1481        sp<EffectModule> getEffectFromId_l(int id);
1482        sp<EffectModule> getEffectFromType_l(const effect_uuid_t *type);
1483        bool setVolume_l(uint32_t *left, uint32_t *right);
1484        void setDevice_l(uint32_t device);
1485        void setMode_l(audio_mode_t mode);
1486
1487        void setInBuffer(int16_t *buffer, bool ownsBuffer = false) {
1488            mInBuffer = buffer;
1489            mOwnInBuffer = ownsBuffer;
1490        }
1491        int16_t *inBuffer() const {
1492            return mInBuffer;
1493        }
1494        void setOutBuffer(int16_t *buffer) {
1495            mOutBuffer = buffer;
1496        }
1497        int16_t *outBuffer() const {
1498            return mOutBuffer;
1499        }
1500
1501        void incTrackCnt() { android_atomic_inc(&mTrackCnt); }
1502        void decTrackCnt() { android_atomic_dec(&mTrackCnt); }
1503        int32_t trackCnt() const { return mTrackCnt;}
1504
1505        void incActiveTrackCnt() { android_atomic_inc(&mActiveTrackCnt);
1506                                   mTailBufferCount = mMaxTailBuffers; }
1507        void decActiveTrackCnt() { android_atomic_dec(&mActiveTrackCnt); }
1508        int32_t activeTrackCnt() const { return mActiveTrackCnt;}
1509
1510        uint32_t strategy() const { return mStrategy; }
1511        void setStrategy(uint32_t strategy)
1512                 { mStrategy = strategy; }
1513
1514        // suspend effect of the given type
1515        void setEffectSuspended_l(const effect_uuid_t *type,
1516                                  bool suspend);
1517        // suspend all eligible effects
1518        void setEffectSuspendedAll_l(bool suspend);
1519        // check if effects should be suspend or restored when a given effect is enable or disabled
1520        void checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1521                                              bool enabled);
1522
1523        status_t dump(int fd, const Vector<String16>& args);
1524
1525    protected:
1526        friend class AudioFlinger;  // for mThread, mEffects
1527        EffectChain(const EffectChain&);
1528        EffectChain& operator =(const EffectChain&);
1529
1530        class SuspendedEffectDesc : public RefBase {
1531        public:
1532            SuspendedEffectDesc() : mRefCount(0) {}
1533
1534            int mRefCount;
1535            effect_uuid_t mType;
1536            wp<EffectModule> mEffect;
1537        };
1538
1539        // get a list of effect modules to suspend when an effect of the type
1540        // passed is enabled.
1541        void                       getSuspendEligibleEffects(Vector< sp<EffectModule> > &effects);
1542
1543        // get an effect module if it is currently enable
1544        sp<EffectModule> getEffectIfEnabled(const effect_uuid_t *type);
1545        // true if the effect whose descriptor is passed can be suspended
1546        // OEMs can modify the rules implemented in this method to exclude specific effect
1547        // types or implementations from the suspend/restore mechanism.
1548        bool isEffectEligibleForSuspend(const effect_descriptor_t& desc);
1549
1550        wp<ThreadBase> mThread;     // parent mixer thread
1551        Mutex mLock;                // mutex protecting effect list
1552        Vector<sp<EffectModule> > mEffects; // list of effect modules
1553        int mSessionId;             // audio session ID
1554        int16_t *mInBuffer;         // chain input buffer
1555        int16_t *mOutBuffer;        // chain output buffer
1556        volatile int32_t mActiveTrackCnt;  // number of active tracks connected
1557        volatile int32_t mTrackCnt;        // number of tracks connected
1558        int32_t mTailBufferCount;   // current effect tail buffer count
1559        int32_t mMaxTailBuffers;    // maximum effect tail buffers
1560        bool mOwnInBuffer;          // true if the chain owns its input buffer
1561        int mVolumeCtrlIdx;         // index of insert effect having control over volume
1562        uint32_t mLeftVolume;       // previous volume on left channel
1563        uint32_t mRightVolume;      // previous volume on right channel
1564        uint32_t mNewLeftVolume;       // new volume on left channel
1565        uint32_t mNewRightVolume;      // new volume on right channel
1566        uint32_t mStrategy; // strategy for this effect chain
1567        // mSuspendedEffects lists all effect currently suspended in the chain
1568        // use effect type UUID timelow field as key. There is no real risk of identical
1569        // timeLow fields among effect type UUIDs.
1570        KeyedVector< int, sp<SuspendedEffectDesc> > mSuspendedEffects;
1571    };
1572
1573    // AudioStreamOut and AudioStreamIn are immutable, so their fields are const.
1574    // For emphasis, we could also make all pointers to them be "const *",
1575    // but that would clutter the code unnecessarily.
1576
1577    struct AudioStreamOut {
1578        audio_hw_device_t*  const hwDev;
1579        audio_stream_out_t* const stream;
1580
1581        AudioStreamOut(audio_hw_device_t *dev, audio_stream_out_t *out) :
1582            hwDev(dev), stream(out) {}
1583    };
1584
1585    struct AudioStreamIn {
1586        audio_hw_device_t* const hwDev;
1587        audio_stream_in_t* const stream;
1588
1589        AudioStreamIn(audio_hw_device_t *dev, audio_stream_in_t *in) :
1590            hwDev(dev), stream(in) {}
1591    };
1592
1593    // for mAudioSessionRefs only
1594    struct AudioSessionRef {
1595        AudioSessionRef(int sessionid, pid_t pid) :
1596            mSessionid(sessionid), mPid(pid), mCnt(1) {}
1597        const int   mSessionid;
1598        const pid_t mPid;
1599        int         mCnt;
1600    };
1601
1602    enum master_volume_support {
1603        // MVS_NONE:
1604        // Audio HAL has no support for master volume, either setting or
1605        // getting.  All master volume control must be implemented in SW by the
1606        // AudioFlinger mixing core.
1607        MVS_NONE,
1608
1609        // MVS_SETONLY:
1610        // Audio HAL has support for setting master volume, but not for getting
1611        // master volume (original HAL design did not include a getter).
1612        // AudioFlinger needs to keep track of the last set master volume in
1613        // addition to needing to set an initial, default, master volume at HAL
1614        // load time.
1615        MVS_SETONLY,
1616
1617        // MVS_FULL:
1618        // Audio HAL has support both for setting and getting master volume.
1619        // AudioFlinger should send all set and get master volume requests
1620        // directly to the HAL.
1621        MVS_FULL,
1622    };
1623
1624    mutable     Mutex                               mLock;
1625
1626                DefaultKeyedVector< pid_t, wp<Client> >     mClients;   // see ~Client()
1627
1628                mutable     Mutex                   mHardwareLock;
1629
1630                // These two fields are immutable after onFirstRef(), so no lock needed to access
1631                audio_hw_device_t*                  mPrimaryHardwareDev; // mAudioHwDevs[0] or NULL
1632                Vector<audio_hw_device_t*>          mAudioHwDevs;
1633
1634    // for dump, indicates which hardware operation is currently in progress (but not stream ops)
1635    enum hardware_call_state {
1636        AUDIO_HW_IDLE = 0,              // no operation in progress
1637        AUDIO_HW_INIT,                  // init_check
1638        AUDIO_HW_OUTPUT_OPEN,           // open_output_stream
1639        AUDIO_HW_OUTPUT_CLOSE,          // unused
1640        AUDIO_HW_INPUT_OPEN,            // unused
1641        AUDIO_HW_INPUT_CLOSE,           // unused
1642        AUDIO_HW_STANDBY,               // unused
1643        AUDIO_HW_SET_MASTER_VOLUME,     // set_master_volume
1644        AUDIO_HW_GET_ROUTING,           // unused
1645        AUDIO_HW_SET_ROUTING,           // unused
1646        AUDIO_HW_GET_MODE,              // unused
1647        AUDIO_HW_SET_MODE,              // set_mode
1648        AUDIO_HW_GET_MIC_MUTE,          // get_mic_mute
1649        AUDIO_HW_SET_MIC_MUTE,          // set_mic_mute
1650        AUDIO_HW_SET_VOICE_VOLUME,      // set_voice_volume
1651        AUDIO_HW_SET_PARAMETER,         // set_parameters
1652        AUDIO_HW_GET_INPUT_BUFFER_SIZE, // get_input_buffer_size
1653        AUDIO_HW_GET_MASTER_VOLUME,     // get_master_volume
1654        AUDIO_HW_GET_PARAMETER,         // get_parameters
1655    };
1656
1657    mutable     hardware_call_state                 mHardwareStatus;    // for dump only
1658
1659
1660                DefaultKeyedVector< audio_io_handle_t, sp<PlaybackThread> >  mPlaybackThreads;
1661                stream_type_t                       mStreamTypes[AUDIO_STREAM_CNT];
1662
1663                // both are protected by mLock
1664                float                               mMasterVolume;
1665                float                               mMasterVolumeSW;
1666                master_volume_support               mMasterVolumeSupportLvl;
1667                bool                                mMasterMute;
1668
1669                DefaultKeyedVector< audio_io_handle_t, sp<RecordThread> >    mRecordThreads;
1670
1671                DefaultKeyedVector< pid_t, sp<NotificationClient> >    mNotificationClients;
1672                volatile int32_t                    mNextUniqueId;  // updated by android_atomic_inc
1673                audio_mode_t                        mMode;
1674                bool                                mBtNrecIsOff;
1675
1676                // protected by mLock
1677                Vector<AudioSessionRef*> mAudioSessionRefs;
1678
1679                float       masterVolume_l() const;
1680                float       masterVolumeSW_l() const  { return mMasterVolumeSW; }
1681                bool        masterMute_l() const    { return mMasterMute; }
1682
1683private:
1684    sp<Client>  registerPid_l(pid_t pid);    // always returns non-0
1685
1686};
1687
1688
1689// ----------------------------------------------------------------------------
1690
1691}; // namespace android
1692
1693#endif // ANDROID_AUDIO_FLINGER_H
1694