AudioPolicyManagerBase.h revision 793dd9f2be9c802c5e78831fe6765d697466eaf4
1/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17
18#include <stdint.h>
19#include <sys/types.h>
20#include <utils/Timers.h>
21#include <utils/Errors.h>
22#include <utils/KeyedVector.h>
23#include <hardware_legacy/AudioPolicyInterface.h>
24
25
26namespace android {
27
28// ----------------------------------------------------------------------------
29
30#define MAX_DEVICE_ADDRESS_LEN 20
31// Attenuation applied to STRATEGY_SONIFICATION streams when a headset is connected: 6dB
32#define SONIFICATION_HEADSET_VOLUME_FACTOR 0.5
33// Min volume for STRATEGY_SONIFICATION streams when limited by music volume: -36dB
34#define SONIFICATION_HEADSET_VOLUME_MIN  0.016
35// Time in milliseconds during which we consider that music is still active after a music
36// track was stopped - see computeVolume()
37#define SONIFICATION_HEADSET_MUSIC_DELAY  5000
38// Time in milliseconds during witch some streams are muted while the audio path
39// is switched
40#define MUTE_TIME_MS 2000
41
42#define NUM_TEST_OUTPUTS 5
43
44#define NUM_VOL_CURVE_KNEES 2
45
46// ----------------------------------------------------------------------------
47// AudioPolicyManagerBase implements audio policy manager behavior common to all platforms.
48// Each platform must implement an AudioPolicyManager class derived from AudioPolicyManagerBase
49// and override methods for which the platform specific behavior differs from the implementation
50// in AudioPolicyManagerBase. Even if no specific behavior is required, the AudioPolicyManager
51// class must be implemented as well as the class factory function createAudioPolicyManager()
52// and provided in a shared library libaudiopolicy.so.
53// ----------------------------------------------------------------------------
54
55class AudioPolicyManagerBase: public AudioPolicyInterface
56#ifdef AUDIO_POLICY_TEST
57    , public Thread
58#endif //AUDIO_POLICY_TEST
59{
60
61public:
62                AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface);
63        virtual ~AudioPolicyManagerBase();
64
65        // AudioPolicyInterface
66        virtual status_t setDeviceConnectionState(AudioSystem::audio_devices device,
67                                                          AudioSystem::device_connection_state state,
68                                                          const char *device_address);
69        virtual AudioSystem::device_connection_state getDeviceConnectionState(AudioSystem::audio_devices device,
70                                                                              const char *device_address);
71        virtual void setPhoneState(int state);
72        virtual void setRingerMode(uint32_t mode, uint32_t mask);
73        virtual void setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config);
74        virtual AudioSystem::forced_config getForceUse(AudioSystem::force_use usage);
75        virtual void setSystemProperty(const char* property, const char* value);
76        virtual status_t initCheck();
77        virtual audio_io_handle_t getOutput(AudioSystem::stream_type stream,
78                                            uint32_t samplingRate = 0,
79                                            uint32_t format = AudioSystem::FORMAT_DEFAULT,
80                                            uint32_t channels = 0,
81                                            AudioSystem::output_flags flags =
82                                                    AudioSystem::OUTPUT_FLAG_INDIRECT);
83        virtual status_t startOutput(audio_io_handle_t output,
84                                     AudioSystem::stream_type stream,
85                                     int session = 0);
86        virtual status_t stopOutput(audio_io_handle_t output,
87                                    AudioSystem::stream_type stream,
88                                    int session = 0);
89        virtual void releaseOutput(audio_io_handle_t output);
90        virtual audio_io_handle_t getInput(int inputSource,
91                                            uint32_t samplingRate,
92                                            uint32_t format,
93                                            uint32_t channels,
94                                            AudioSystem::audio_in_acoustics acoustics);
95        // indicates to the audio policy manager that the input starts being used.
96        virtual status_t startInput(audio_io_handle_t input);
97        // indicates to the audio policy manager that the input stops being used.
98        virtual status_t stopInput(audio_io_handle_t input);
99        virtual void releaseInput(audio_io_handle_t input);
100        virtual void initStreamVolume(AudioSystem::stream_type stream,
101                                                    int indexMin,
102                                                    int indexMax);
103        virtual status_t setStreamVolumeIndex(AudioSystem::stream_type stream, int index);
104        virtual status_t getStreamVolumeIndex(AudioSystem::stream_type stream, int *index);
105
106        // return the strategy corresponding to a given stream type
107        virtual uint32_t getStrategyForStream(AudioSystem::stream_type stream);
108
109        virtual audio_io_handle_t getOutputForEffect(effect_descriptor_t *desc);
110        virtual status_t registerEffect(effect_descriptor_t *desc,
111                                        audio_io_handle_t output,
112                                        uint32_t strategy,
113                                        int session,
114                                        int id);
115        virtual status_t unregisterEffect(int id);
116
117        virtual bool isStreamActive(int stream, uint32_t inPastMs = 0) const;
118
119        virtual status_t dump(int fd);
120
121protected:
122
123        enum routing_strategy {
124            STRATEGY_MEDIA,
125            STRATEGY_PHONE,
126            STRATEGY_SONIFICATION,
127            STRATEGY_DTMF,
128            NUM_STRATEGIES
129        };
130
131        // descriptor for audio outputs. Used to maintain current configuration of each opened audio output
132        // and keep track of the usage of this output by each audio stream type.
133        class AudioOutputDescriptor
134        {
135        public:
136            AudioOutputDescriptor();
137
138            status_t    dump(int fd);
139
140            uint32_t device();
141            void changeRefCount(AudioSystem::stream_type, int delta);
142            uint32_t refCount();
143            uint32_t strategyRefCount(routing_strategy strategy);
144            bool isUsedByStrategy(routing_strategy strategy) { return (strategyRefCount(strategy) != 0);}
145            bool isDuplicated() { return (mOutput1 != NULL && mOutput2 != NULL); }
146
147            audio_io_handle_t mId;              // output handle
148            uint32_t mSamplingRate;             //
149            uint32_t mFormat;                   //
150            uint32_t mChannels;                 // output configuration
151            uint32_t mLatency;                  //
152            AudioSystem::output_flags mFlags;   //
153            uint32_t mDevice;                   // current device this output is routed to
154            uint32_t mRefCount[AudioSystem::NUM_STREAM_TYPES]; // number of streams of each type using this output
155            nsecs_t mStopTime[AudioSystem::NUM_STREAM_TYPES];
156            AudioOutputDescriptor *mOutput1;    // used by duplicated outputs: first output
157            AudioOutputDescriptor *mOutput2;    // used by duplicated outputs: second output
158            float mCurVolume[AudioSystem::NUM_STREAM_TYPES];   // current stream volume
159            int mMuteCount[AudioSystem::NUM_STREAM_TYPES];     // mute request counter
160        };
161
162        // descriptor for audio inputs. Used to maintain current configuration of each opened audio input
163        // and keep track of the usage of this input.
164        class AudioInputDescriptor
165        {
166        public:
167            AudioInputDescriptor();
168
169            status_t    dump(int fd);
170
171            uint32_t mSamplingRate;                     //
172            uint32_t mFormat;                           // input configuration
173            uint32_t mChannels;                         //
174            AudioSystem::audio_in_acoustics mAcoustics; //
175            uint32_t mDevice;                           // current device this input is routed to
176            uint32_t mRefCount;                         // number of AudioRecord clients using this output
177            int      mInputSource;                     // input source selected by application (mediarecorder.h)
178        };
179
180        // stream descriptor used for volume control
181        class StreamDescriptor
182        {
183        public:
184            StreamDescriptor()
185            :   mIndexMin(0), mIndexMax(1), mIndexCur(1), mCanBeMuted(true) {}
186
187            void dump(char* buffer, size_t size);
188
189            int mIndexMin;      // min volume index
190            int mIndexMax;      // max volume index
191            int mIndexCur;      // current volume index
192            bool mCanBeMuted;   // true is the stream can be muted
193
194            // 4 points to define the volume attenuation curve, each characterized by the volume
195            // index (from 0 to 100) at which they apply, and the attenuation in dB at that index.
196            int mVolIndex[NUM_VOL_CURVE_KNEES+2];   // minimum index, index at knees, and max index
197            float mVolDbAtt[NUM_VOL_CURVE_KNEES+2]; // largest attenuation, attenuation at knees,
198                                                    //     and attenuation at max vol (usually 0dB)
199            // indices in mVolIndex and mVolDbAtt respectively for points at lowest volume, knee 1,
200            //    knee 2 and highest volume.
201            enum { VOLMIN = 0, VOLKNEE1 = 1, VOLKNEE2 = 2, VOLMAX = 3 };
202        };
203
204        // stream descriptor used for volume control
205        class EffectDescriptor
206        {
207        public:
208
209            status_t dump(int fd);
210
211            int mOutput;                // output the effect is attached to
212            routing_strategy mStrategy; // routing strategy the effect is associated to
213            int mSession;               // audio session the effect is on
214            effect_descriptor_t mDesc;  // effect descriptor
215        };
216
217        void addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc);
218
219        // return the strategy corresponding to a given stream type
220        static routing_strategy getStrategy(AudioSystem::stream_type stream);
221        // return appropriate device for streams handled by the specified strategy according to current
222        // phone state, connected devices...
223        // if fromCache is true, the device is returned from mDeviceForStrategy[], otherwise it is determined
224        // by current state (device connected, phone state, force use, a2dp output...)
225        // This allows to:
226        //  1 speed up process when the state is stable (when starting or stopping an output)
227        //  2 access to either current device selection (fromCache == true) or
228        // "future" device selection (fromCache == false) when called from a context
229        //  where conditions are changing (setDeviceConnectionState(), setPhoneState()...) AND
230        //  before updateDeviceForStrategy() is called.
231        virtual uint32_t getDeviceForStrategy(routing_strategy strategy, bool fromCache = true);
232        // change the route of the specified output
233        void setOutputDevice(audio_io_handle_t output, uint32_t device, bool force = false, int delayMs = 0);
234        // select input device corresponding to requested audio source
235        virtual uint32_t getDeviceForInputSource(int inputSource);
236        // return io handle of active input or 0 if no input is active
237        audio_io_handle_t getActiveInput();
238        virtual void initializeVolumeCurves();
239        // compute the actual volume for a given stream according to the requested index and a particular
240        // device
241        virtual float computeVolume(int stream, int index, audio_io_handle_t output, uint32_t device);
242        // check that volume change is permitted, compute and send new volume to audio hardware
243        status_t checkAndSetVolume(int stream, int index, audio_io_handle_t output, uint32_t device, int delayMs = 0, bool force = false);
244        // apply all stream volumes to the specified output and device
245        void applyStreamVolumes(audio_io_handle_t output, uint32_t device, int delayMs = 0);
246        // Mute or unmute all streams handled by the specified strategy on the specified output
247        void setStrategyMute(routing_strategy strategy, bool on, audio_io_handle_t output, int delayMs = 0);
248        // Mute or unmute the stream on the specified output
249        void setStreamMute(int stream, bool on, audio_io_handle_t output, int delayMs = 0);
250        // handle special cases for sonification strategy while in call: mute streams or replace by
251        // a special tone in the device used for communication
252        void handleIncallSonification(int stream, bool starting, bool stateChange);
253        // true is current platform implements a back microphone
254        virtual bool hasBackMicrophone() const { return false; }
255        // true if device is in a telephony or VoIP call
256        virtual bool isInCall();
257        // true if given state represents a device in a telephony or VoIP call
258        virtual bool isStateInCall(int state);
259
260#ifdef WITH_A2DP
261        // true is current platform supports suplication of notifications and ringtones over A2DP output
262        virtual bool a2dpUsedForSonification() const { return true; }
263        status_t handleA2dpConnection(AudioSystem::audio_devices device,
264                                                            const char *device_address);
265        status_t handleA2dpDisconnection(AudioSystem::audio_devices device,
266                                                            const char *device_address);
267        void closeA2dpOutputs();
268        // checks and if necessary changes output (a2dp, duplicated or hardware) used for all strategies.
269        // must be called every time a condition that affects the output choice for a given strategy is
270        // changed: connected device, phone state, force use...
271        // Must be called before updateDeviceForStrategy()
272        void checkOutputForStrategy(routing_strategy strategy);
273        // Same as checkOutputForStrategy() but for a all strategies in order of priority
274        void checkOutputForAllStrategies();
275        // manages A2DP output suspend/restore according to phone state and BT SCO usage
276        void checkA2dpSuspend();
277#endif
278        // selects the most appropriate device on output for current state
279        // must be called every time a condition that affects the device choice for a given output is
280        // changed: connected device, phone state, force use, output start, output stop..
281        // see getDeviceForStrategy() for the use of fromCache parameter
282        uint32_t getNewDevice(audio_io_handle_t output, bool fromCache = true);
283        // updates cache of device used by all strategies (mDeviceForStrategy[])
284        // must be called every time a condition that affects the device choice for a given strategy is
285        // changed: connected device, phone state, force use...
286        // cached values are used by getDeviceForStrategy() if parameter fromCache is true.
287         // Must be called after checkOutputForAllStrategies()
288        void updateDeviceForStrategy();
289        // true if current platform requires a specific output to be opened for this particular
290        // set of parameters. This function is called by getOutput() and is implemented by platform
291        // specific audio policy manager.
292        virtual bool needsDirectOuput(AudioSystem::stream_type stream,
293                                    uint32_t samplingRate,
294                                    uint32_t format,
295                                    uint32_t channels,
296                                    AudioSystem::output_flags flags,
297                                    uint32_t device);
298        virtual uint32_t getMaxEffectsCpuLoad();
299        virtual uint32_t getMaxEffectsMemory();
300#ifdef AUDIO_POLICY_TEST
301        virtual     bool        threadLoop();
302                    void        exit();
303        int testOutputIndex(audio_io_handle_t output);
304#endif //AUDIO_POLICY_TEST
305
306        AudioPolicyClientInterface *mpClientInterface;  // audio policy client interface
307        audio_io_handle_t mHardwareOutput;              // hardware output handler
308        audio_io_handle_t mA2dpOutput;                  // A2DP output handler
309        audio_io_handle_t mDuplicatedOutput;            // duplicated output handler: outputs to hardware and A2DP.
310
311        KeyedVector<audio_io_handle_t, AudioOutputDescriptor *> mOutputs;   // list of output descriptors
312        KeyedVector<audio_io_handle_t, AudioInputDescriptor *> mInputs;     // list of input descriptors
313        uint32_t mAvailableOutputDevices;                                   // bit field of all available output devices
314        uint32_t mAvailableInputDevices;                                    // bit field of all available input devices
315        int mPhoneState;                                                    // current phone state
316        uint32_t                 mRingerMode;                               // current ringer mode
317        AudioSystem::forced_config mForceUse[AudioSystem::NUM_FORCE_USE];   // current forced use configuration
318
319        StreamDescriptor mStreams[AudioSystem::NUM_STREAM_TYPES];           // stream descriptors for volume control
320        String8 mA2dpDeviceAddress;                                         // A2DP device MAC address
321        String8 mScoDeviceAddress;                                          // SCO device MAC address
322        bool    mLimitRingtoneVolume;                                       // limit ringtone volume to music volume if headset connected
323        uint32_t mDeviceForStrategy[NUM_STRATEGIES];
324        float   mLastVoiceVolume;                                           // last voice volume value sent to audio HAL
325
326        // Maximum CPU load allocated to audio effects in 0.1 MIPS (ARMv5TE, 0 WS memory) units
327        static const uint32_t MAX_EFFECTS_CPU_LOAD = 1000;
328        // Maximum memory allocated to audio effects in KB
329        static const uint32_t MAX_EFFECTS_MEMORY = 512;
330        uint32_t mTotalEffectsCpuLoad; // current CPU load used by effects
331        uint32_t mTotalEffectsMemory;  // current memory used by effects
332        KeyedVector<int, EffectDescriptor *> mEffects;  // list of registered audio effects
333        bool    mA2dpSuspended;  // true if A2DP output is suspended
334
335#ifdef AUDIO_POLICY_TEST
336        Mutex   mLock;
337        Condition mWaitWorkCV;
338
339        int             mCurOutput;
340        bool            mDirectOutput;
341        audio_io_handle_t mTestOutputs[NUM_TEST_OUTPUTS];
342        int             mTestInput;
343        uint32_t        mTestDevice;
344        uint32_t        mTestSamplingRate;
345        uint32_t        mTestFormat;
346        uint32_t        mTestChannels;
347        uint32_t        mTestLatencyMs;
348#endif //AUDIO_POLICY_TEST
349
350private:
351        static float volIndexToAmpl(uint32_t device, const StreamDescriptor& streamDesc,
352                int indexInUi);
353};
354
355};
356