AudioPolicyManagerBase.h revision 3775706211178bf0d252fd30b9ff1c00926c8535
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        // return the enabled output devices for the given stream type
110        virtual uint32_t getDevicesForStream(AudioSystem::stream_type stream);
111
112        virtual audio_io_handle_t getOutputForEffect(effect_descriptor_t *desc);
113        virtual status_t registerEffect(effect_descriptor_t *desc,
114                                        audio_io_handle_t output,
115                                        uint32_t strategy,
116                                        int session,
117                                        int id);
118        virtual status_t unregisterEffect(int id);
119
120        virtual bool isStreamActive(int stream, uint32_t inPastMs = 0) const;
121
122        virtual status_t dump(int fd);
123
124protected:
125
126        enum routing_strategy {
127            STRATEGY_MEDIA,
128            STRATEGY_PHONE,
129            STRATEGY_SONIFICATION,
130            STRATEGY_DTMF,
131            NUM_STRATEGIES
132        };
133
134        // descriptor for audio outputs. Used to maintain current configuration of each opened audio output
135        // and keep track of the usage of this output by each audio stream type.
136        class AudioOutputDescriptor
137        {
138        public:
139            AudioOutputDescriptor();
140
141            status_t    dump(int fd);
142
143            uint32_t device();
144            void changeRefCount(AudioSystem::stream_type, int delta);
145            uint32_t refCount();
146            uint32_t strategyRefCount(routing_strategy strategy);
147            bool isUsedByStrategy(routing_strategy strategy) { return (strategyRefCount(strategy) != 0);}
148            bool isDuplicated() { return (mOutput1 != NULL && mOutput2 != NULL); }
149
150            audio_io_handle_t mId;              // output handle
151            uint32_t mSamplingRate;             //
152            uint32_t mFormat;                   //
153            uint32_t mChannels;                 // output configuration
154            uint32_t mLatency;                  //
155            AudioSystem::output_flags mFlags;   //
156            uint32_t mDevice;                   // current device this output is routed to
157            uint32_t mRefCount[AudioSystem::NUM_STREAM_TYPES]; // number of streams of each type using this output
158            nsecs_t mStopTime[AudioSystem::NUM_STREAM_TYPES];
159            AudioOutputDescriptor *mOutput1;    // used by duplicated outputs: first output
160            AudioOutputDescriptor *mOutput2;    // used by duplicated outputs: second output
161            float mCurVolume[AudioSystem::NUM_STREAM_TYPES];   // current stream volume
162            int mMuteCount[AudioSystem::NUM_STREAM_TYPES];     // mute request counter
163        };
164
165        // descriptor for audio inputs. Used to maintain current configuration of each opened audio input
166        // and keep track of the usage of this input.
167        class AudioInputDescriptor
168        {
169        public:
170            AudioInputDescriptor();
171
172            status_t    dump(int fd);
173
174            uint32_t mSamplingRate;                     //
175            uint32_t mFormat;                           // input configuration
176            uint32_t mChannels;                         //
177            AudioSystem::audio_in_acoustics mAcoustics; //
178            uint32_t mDevice;                           // current device this input is routed to
179            uint32_t mRefCount;                         // number of AudioRecord clients using this output
180            int      mInputSource;                     // input source selected by application (mediarecorder.h)
181        };
182
183        // stream descriptor used for volume control
184        class StreamDescriptor
185        {
186        public:
187            StreamDescriptor()
188            :   mIndexMin(0), mIndexMax(1), mIndexCur(1), mCanBeMuted(true) {}
189
190            void dump(char* buffer, size_t size);
191
192            int mIndexMin;      // min volume index
193            int mIndexMax;      // max volume index
194            int mIndexCur;      // current volume index
195            bool mCanBeMuted;   // true is the stream can be muted
196
197            // 4 points to define the volume attenuation curve, each characterized by the volume
198            // index (from 0 to 100) at which they apply, and the attenuation in dB at that index.
199            int mVolIndex[NUM_VOL_CURVE_KNEES+2];   // minimum index, index at knees, and max index
200            float mVolDbAtt[NUM_VOL_CURVE_KNEES+2]; // largest attenuation, attenuation at knees,
201                                                    //     and attenuation at max vol (usually 0dB)
202            // indices in mVolIndex and mVolDbAtt respectively for points at lowest volume, knee 1,
203            //    knee 2 and highest volume.
204            enum { VOLMIN = 0, VOLKNEE1 = 1, VOLKNEE2 = 2, VOLMAX = 3 };
205        };
206
207        // stream descriptor used for volume control
208        class EffectDescriptor
209        {
210        public:
211
212            status_t dump(int fd);
213
214            int mOutput;                // output the effect is attached to
215            routing_strategy mStrategy; // routing strategy the effect is associated to
216            int mSession;               // audio session the effect is on
217            effect_descriptor_t mDesc;  // effect descriptor
218        };
219
220        void addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc);
221
222        // return the strategy corresponding to a given stream type
223        static routing_strategy getStrategy(AudioSystem::stream_type stream);
224        // return appropriate device for streams handled by the specified strategy according to current
225        // phone state, connected devices...
226        // if fromCache is true, the device is returned from mDeviceForStrategy[], otherwise it is determined
227        // by current state (device connected, phone state, force use, a2dp output...)
228        // This allows to:
229        //  1 speed up process when the state is stable (when starting or stopping an output)
230        //  2 access to either current device selection (fromCache == true) or
231        // "future" device selection (fromCache == false) when called from a context
232        //  where conditions are changing (setDeviceConnectionState(), setPhoneState()...) AND
233        //  before updateDeviceForStrategy() is called.
234        virtual uint32_t getDeviceForStrategy(routing_strategy strategy, bool fromCache = true);
235        // change the route of the specified output
236        void setOutputDevice(audio_io_handle_t output, uint32_t device, bool force = false, int delayMs = 0);
237        // select input device corresponding to requested audio source
238        virtual uint32_t getDeviceForInputSource(int inputSource);
239        // return io handle of active input or 0 if no input is active
240        audio_io_handle_t getActiveInput();
241        virtual void initializeVolumeCurves();
242        // compute the actual volume for a given stream according to the requested index and a particular
243        // device
244        virtual float computeVolume(int stream, int index, audio_io_handle_t output, uint32_t device);
245        // check that volume change is permitted, compute and send new volume to audio hardware
246        status_t checkAndSetVolume(int stream, int index, audio_io_handle_t output, uint32_t device, int delayMs = 0, bool force = false);
247        // apply all stream volumes to the specified output and device
248        void applyStreamVolumes(audio_io_handle_t output, uint32_t device, int delayMs = 0, bool force = false);
249        // Mute or unmute all streams handled by the specified strategy on the specified output
250        void setStrategyMute(routing_strategy strategy, bool on, audio_io_handle_t output, int delayMs = 0);
251        // Mute or unmute the stream on the specified output
252        void setStreamMute(int stream, bool on, audio_io_handle_t output, int delayMs = 0);
253        // handle special cases for sonification strategy while in call: mute streams or replace by
254        // a special tone in the device used for communication
255        void handleIncallSonification(int stream, bool starting, bool stateChange);
256        // true is current platform implements a back microphone
257        virtual bool hasBackMicrophone() const { return false; }
258        // true if device is in a telephony or VoIP call
259        virtual bool isInCall();
260        // true if given state represents a device in a telephony or VoIP call
261        virtual bool isStateInCall(int state);
262
263#ifdef WITH_A2DP
264        // true is current platform supports suplication of notifications and ringtones over A2DP output
265        virtual bool a2dpUsedForSonification() const { return true; }
266        status_t handleA2dpConnection(AudioSystem::audio_devices device,
267                                                            const char *device_address);
268        status_t handleA2dpDisconnection(AudioSystem::audio_devices device,
269                                                            const char *device_address);
270        void closeA2dpOutputs();
271        // checks and if necessary changes output (a2dp, duplicated or hardware) used for all strategies.
272        // must be called every time a condition that affects the output choice for a given strategy is
273        // changed: connected device, phone state, force use...
274        // Must be called before updateDeviceForStrategy()
275        void checkOutputForStrategy(routing_strategy strategy);
276        // Same as checkOutputForStrategy() but for a all strategies in order of priority
277        void checkOutputForAllStrategies();
278        // manages A2DP output suspend/restore according to phone state and BT SCO usage
279        void checkA2dpSuspend();
280#endif
281        // selects the most appropriate device on output for current state
282        // must be called every time a condition that affects the device choice for a given output is
283        // changed: connected device, phone state, force use, output start, output stop..
284        // see getDeviceForStrategy() for the use of fromCache parameter
285        uint32_t getNewDevice(audio_io_handle_t output, bool fromCache = true);
286        // updates cache of device used by all strategies (mDeviceForStrategy[])
287        // must be called every time a condition that affects the device choice for a given strategy is
288        // changed: connected device, phone state, force use...
289        // cached values are used by getDeviceForStrategy() if parameter fromCache is true.
290         // Must be called after checkOutputForAllStrategies()
291        void updateDeviceForStrategy();
292        // true if current platform requires a specific output to be opened for this particular
293        // set of parameters. This function is called by getOutput() and is implemented by platform
294        // specific audio policy manager.
295        virtual bool needsDirectOuput(AudioSystem::stream_type stream,
296                                    uint32_t samplingRate,
297                                    uint32_t format,
298                                    uint32_t channels,
299                                    AudioSystem::output_flags flags,
300                                    uint32_t device);
301        virtual uint32_t getMaxEffectsCpuLoad();
302        virtual uint32_t getMaxEffectsMemory();
303#ifdef AUDIO_POLICY_TEST
304        virtual     bool        threadLoop();
305                    void        exit();
306        int testOutputIndex(audio_io_handle_t output);
307#endif //AUDIO_POLICY_TEST
308
309        AudioPolicyClientInterface *mpClientInterface;  // audio policy client interface
310        audio_io_handle_t mHardwareOutput;              // hardware output handler
311        audio_io_handle_t mA2dpOutput;                  // A2DP output handler
312        audio_io_handle_t mDuplicatedOutput;            // duplicated output handler: outputs to hardware and A2DP.
313
314        KeyedVector<audio_io_handle_t, AudioOutputDescriptor *> mOutputs;   // list of output descriptors
315        KeyedVector<audio_io_handle_t, AudioInputDescriptor *> mInputs;     // list of input descriptors
316        uint32_t mAvailableOutputDevices;                                   // bit field of all available output devices
317        uint32_t mAvailableInputDevices;                                    // bit field of all available input devices
318        int mPhoneState;                                                    // current phone state
319        uint32_t                 mRingerMode;                               // current ringer mode
320        AudioSystem::forced_config mForceUse[AudioSystem::NUM_FORCE_USE];   // current forced use configuration
321
322        StreamDescriptor mStreams[AudioSystem::NUM_STREAM_TYPES];           // stream descriptors for volume control
323        String8 mA2dpDeviceAddress;                                         // A2DP device MAC address
324        String8 mScoDeviceAddress;                                          // SCO device MAC address
325        bool    mLimitRingtoneVolume;                                       // limit ringtone volume to music volume if headset connected
326        uint32_t mDeviceForStrategy[NUM_STRATEGIES];
327        float   mLastVoiceVolume;                                           // last voice volume value sent to audio HAL
328
329        // Maximum CPU load allocated to audio effects in 0.1 MIPS (ARMv5TE, 0 WS memory) units
330        static const uint32_t MAX_EFFECTS_CPU_LOAD = 1000;
331        // Maximum memory allocated to audio effects in KB
332        static const uint32_t MAX_EFFECTS_MEMORY = 512;
333        uint32_t mTotalEffectsCpuLoad; // current CPU load used by effects
334        uint32_t mTotalEffectsMemory;  // current memory used by effects
335        KeyedVector<int, EffectDescriptor *> mEffects;  // list of registered audio effects
336        bool    mA2dpSuspended;  // true if A2DP output is suspended
337
338#ifdef AUDIO_POLICY_TEST
339        Mutex   mLock;
340        Condition mWaitWorkCV;
341
342        int             mCurOutput;
343        bool            mDirectOutput;
344        audio_io_handle_t mTestOutputs[NUM_TEST_OUTPUTS];
345        int             mTestInput;
346        uint32_t        mTestDevice;
347        uint32_t        mTestSamplingRate;
348        uint32_t        mTestFormat;
349        uint32_t        mTestChannels;
350        uint32_t        mTestLatencyMs;
351#endif //AUDIO_POLICY_TEST
352
353private:
354        static float volIndexToAmpl(uint32_t device, const StreamDescriptor& streamDesc,
355                int indexInUi);
356};
357
358};
359