OSDN Git Service

audio policy: use configuration file
[android-x86/hardware-libhardware_legacy.git] / include / hardware_legacy / AudioPolicyManagerBase.h
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 <cutils/config_utils.h>
21 #include <cutils/misc.h>
22 #include <utils/Timers.h>
23 #include <utils/Errors.h>
24 #include <utils/KeyedVector.h>
25 #include <utils/SortedVector.h>
26 #include <hardware_legacy/AudioPolicyInterface.h>
27
28
29 namespace android_audio_legacy {
30     using android::KeyedVector;
31     using android::DefaultKeyedVector;
32     using android::SortedVector;
33
34 // ----------------------------------------------------------------------------
35
36 #define MAX_DEVICE_ADDRESS_LEN 20
37 // Attenuation applied to STRATEGY_SONIFICATION streams when a headset is connected: 6dB
38 #define SONIFICATION_HEADSET_VOLUME_FACTOR 0.5
39 // Min volume for STRATEGY_SONIFICATION streams when limited by music volume: -36dB
40 #define SONIFICATION_HEADSET_VOLUME_MIN  0.016
41 // Time in milliseconds during which we consider that music is still active after a music
42 // track was stopped - see computeVolume()
43 #define SONIFICATION_HEADSET_MUSIC_DELAY  5000
44 // Time in milliseconds after media stopped playing during which we consider that the
45 // sonification should be as unobtrusive as during the time media was playing.
46 #define SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY 5000
47 // Time in milliseconds during witch some streams are muted while the audio path
48 // is switched
49 #define MUTE_TIME_MS 2000
50
51 #define NUM_TEST_OUTPUTS 5
52
53 #define NUM_VOL_CURVE_KNEES 2
54
55 // ----------------------------------------------------------------------------
56 // AudioPolicyManagerBase implements audio policy manager behavior common to all platforms.
57 // Each platform must implement an AudioPolicyManager class derived from AudioPolicyManagerBase
58 // and override methods for which the platform specific behavior differs from the implementation
59 // in AudioPolicyManagerBase. Even if no specific behavior is required, the AudioPolicyManager
60 // class must be implemented as well as the class factory function createAudioPolicyManager()
61 // and provided in a shared library libaudiopolicy.so.
62 // ----------------------------------------------------------------------------
63
64 class AudioPolicyManagerBase: public AudioPolicyInterface
65 #ifdef AUDIO_POLICY_TEST
66     , public Thread
67 #endif //AUDIO_POLICY_TEST
68 {
69
70 public:
71                 AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface);
72         virtual ~AudioPolicyManagerBase();
73
74         // AudioPolicyInterface
75         virtual status_t setDeviceConnectionState(AudioSystem::audio_devices device,
76                                                           AudioSystem::device_connection_state state,
77                                                           const char *device_address);
78         virtual AudioSystem::device_connection_state getDeviceConnectionState(AudioSystem::audio_devices device,
79                                                                               const char *device_address);
80         virtual void setPhoneState(int state);
81         virtual void setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config);
82         virtual AudioSystem::forced_config getForceUse(AudioSystem::force_use usage);
83         virtual void setSystemProperty(const char* property, const char* value);
84         virtual status_t initCheck();
85         virtual audio_io_handle_t getOutput(AudioSystem::stream_type stream,
86                                             uint32_t samplingRate = 0,
87                                             uint32_t format = AudioSystem::FORMAT_DEFAULT,
88                                             uint32_t channels = 0,
89                                             AudioSystem::output_flags flags =
90                                                     AudioSystem::OUTPUT_FLAG_INDIRECT);
91         virtual status_t startOutput(audio_io_handle_t output,
92                                      AudioSystem::stream_type stream,
93                                      int session = 0);
94         virtual status_t stopOutput(audio_io_handle_t output,
95                                     AudioSystem::stream_type stream,
96                                     int session = 0);
97         virtual void releaseOutput(audio_io_handle_t output);
98         virtual audio_io_handle_t getInput(int inputSource,
99                                             uint32_t samplingRate,
100                                             uint32_t format,
101                                             uint32_t channels,
102                                             AudioSystem::audio_in_acoustics acoustics);
103
104         // indicates to the audio policy manager that the input starts being used.
105         virtual status_t startInput(audio_io_handle_t input);
106
107         // indicates to the audio policy manager that the input stops being used.
108         virtual status_t stopInput(audio_io_handle_t input);
109         virtual void releaseInput(audio_io_handle_t input);
110         virtual void initStreamVolume(AudioSystem::stream_type stream,
111                                                     int indexMin,
112                                                     int indexMax);
113         virtual status_t setStreamVolumeIndex(AudioSystem::stream_type stream,
114                                               int index,
115                                               audio_devices_t device);
116         virtual status_t getStreamVolumeIndex(AudioSystem::stream_type stream,
117                                               int *index,
118                                               audio_devices_t device);
119
120         // return the strategy corresponding to a given stream type
121         virtual uint32_t getStrategyForStream(AudioSystem::stream_type stream);
122
123         // return the enabled output devices for the given stream type
124         virtual audio_devices_t getDevicesForStream(AudioSystem::stream_type stream);
125
126         virtual audio_io_handle_t getOutputForEffect(effect_descriptor_t *desc);
127         virtual status_t registerEffect(effect_descriptor_t *desc,
128                                         audio_io_handle_t io,
129                                         uint32_t strategy,
130                                         int session,
131                                         int id);
132         virtual status_t unregisterEffect(int id);
133         virtual status_t setEffectEnabled(int id, bool enabled);
134
135         virtual bool isStreamActive(int stream, uint32_t inPastMs = 0) const;
136
137         virtual status_t dump(int fd);
138
139 protected:
140
141         enum routing_strategy {
142             STRATEGY_MEDIA,
143             STRATEGY_PHONE,
144             STRATEGY_SONIFICATION,
145             STRATEGY_SONIFICATION_RESPECTFUL,
146             STRATEGY_DTMF,
147             STRATEGY_ENFORCED_AUDIBLE,
148             NUM_STRATEGIES
149         };
150
151         // 4 points to define the volume attenuation curve, each characterized by the volume
152         // index (from 0 to 100) at which they apply, and the attenuation in dB at that index.
153         // we use 100 steps to avoid rounding errors when computing the volume in volIndexToAmpl()
154
155         enum { VOLMIN = 0, VOLKNEE1 = 1, VOLKNEE2 = 2, VOLMAX = 3, VOLCNT = 4};
156
157         class VolumeCurvePoint
158         {
159         public:
160             int mIndex;
161             float mDBAttenuation;
162         };
163
164         // device categories used for volume curve management.
165         enum device_category {
166             DEVICE_CATEGORY_HEADSET,
167             DEVICE_CATEGORY_SPEAKER,
168             DEVICE_CATEGORY_EARPIECE,
169             DEVICE_CATEGORY_CNT
170         };
171
172         // the IOProfile class describes the capabilities of an output or input stream.
173         // It is currently assumed that all combination of listed parameters are supported.
174         // It is used by the policy manager to determine if an output or input is suitable for
175         // a given use case,  open/close it accordingly and connect/disconnect audio tracks
176         // to/from it.
177         class IOProfile
178         {
179          public:
180             IOProfile(const char *module);
181             ~IOProfile();
182
183             void dump(int fd);
184
185             Vector <uint32_t> mSamplingRates; // supported sampling rates
186             Vector <audio_channel_mask_t> mChannelMasks; // supported channel masks
187             Vector <audio_format_t> mFormats; // supported audio formats
188             audio_devices_t mSupportedDevices; // supported devices (devices this output can be
189                                                // routed to)
190             audio_policy_output_flags_t mFlags; // attribute flags (e.g primary output,
191                                                 // direct output...). For outputs only.
192             char *mModuleName; // base name of the audio HW module exposing this I/O stream
193                                // (primary, a2dp ...)
194         };
195
196         // default volume curve
197         static const VolumeCurvePoint sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT];
198         // default volume curve for media strategy
199         static const VolumeCurvePoint sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT];
200         // volume curve for media strategy on speakers
201         static const VolumeCurvePoint sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT];
202         // volume curve for sonification strategy on speakers
203         static const VolumeCurvePoint sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT];
204         // default volume curves per strategy and device category. See initializeVolumeCurves()
205         static const VolumeCurvePoint *sVolumeProfiles[NUM_STRATEGIES][DEVICE_CATEGORY_CNT];
206
207         // descriptor for audio outputs. Used to maintain current configuration of each opened audio output
208         // and keep track of the usage of this output by each audio stream type.
209         class AudioOutputDescriptor
210         {
211         public:
212             AudioOutputDescriptor(const IOProfile *profile);
213
214             status_t    dump(int fd);
215
216             audio_devices_t device();
217             void changeRefCount(AudioSystem::stream_type, int delta);
218             uint32_t refCount();
219             uint32_t strategyRefCount(routing_strategy strategy);
220             bool isUsedByStrategy(routing_strategy strategy) { return (strategyRefCount(strategy) != 0);}
221             bool isDuplicated() const { return (mOutput1 != NULL && mOutput2 != NULL); }
222             audio_devices_t supportedDevices();
223             uint32_t latency();
224             bool sharesHwModuleWith(const AudioOutputDescriptor *outputDesc);
225
226             audio_io_handle_t mId;              // output handle
227             uint32_t mSamplingRate;             //
228             uint32_t mFormat;                   //
229             uint32_t mChannels;                 // output configuration
230             uint32_t mLatency;                  //
231             AudioSystem::output_flags mFlags;   //
232             audio_devices_t mDevice;                   // current device this output is routed to
233             uint32_t mRefCount[AudioSystem::NUM_STREAM_TYPES]; // number of streams of each type using this output
234             nsecs_t mStopTime[AudioSystem::NUM_STREAM_TYPES];
235             AudioOutputDescriptor *mOutput1;    // used by duplicated outputs: first output
236             AudioOutputDescriptor *mOutput2;    // used by duplicated outputs: second output
237             float mCurVolume[AudioSystem::NUM_STREAM_TYPES];   // current stream volume
238             int mMuteCount[AudioSystem::NUM_STREAM_TYPES];     // mute request counter
239             const IOProfile *mProfile;          // I/O profile this output derives from
240             bool mStrategyMutedByDevice[NUM_STRATEGIES]; // strategies muted because of incompatible
241                                                 // device selection. See checkDeviceMuteStrategies()
242         };
243
244         // descriptor for audio inputs. Used to maintain current configuration of each opened audio input
245         // and keep track of the usage of this input.
246         class AudioInputDescriptor
247         {
248         public:
249             AudioInputDescriptor(const IOProfile *profile);
250
251             status_t    dump(int fd);
252
253             uint32_t mSamplingRate;                     //
254             uint32_t mFormat;                           // input configuration
255             uint32_t mChannels;                         //
256             AudioSystem::audio_in_acoustics mAcoustics; //
257             audio_devices_t mDevice;                    // current device this input is routed to
258             uint32_t mRefCount;                         // number of AudioRecord clients using this output
259             int      mInputSource;                      // input source selected by application (mediarecorder.h)
260             const IOProfile *mProfile;                  // I/O profile this output derives from
261         };
262
263         // stream descriptor used for volume control
264         class StreamDescriptor
265         {
266         public:
267             StreamDescriptor();
268
269             int getVolumeIndex(audio_devices_t device);
270             void dump(int fd);
271
272             int mIndexMin;      // min volume index
273             int mIndexMax;      // max volume index
274             KeyedVector<audio_devices_t, int> mIndexCur;   // current volume index per device
275             bool mCanBeMuted;   // true is the stream can be muted
276
277             const VolumeCurvePoint *mVolumeCurve[DEVICE_CATEGORY_CNT];
278         };
279
280         // stream descriptor used for volume control
281         class EffectDescriptor
282         {
283         public:
284
285             status_t dump(int fd);
286
287             int mIo;                // io the effect is attached to
288             routing_strategy mStrategy; // routing strategy the effect is associated to
289             int mSession;               // audio session the effect is on
290             effect_descriptor_t mDesc;  // effect descriptor
291             bool mEnabled;              // enabled state: CPU load being used or not
292         };
293
294         void addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc);
295
296         // return the strategy corresponding to a given stream type
297         static routing_strategy getStrategy(AudioSystem::stream_type stream);
298
299         // return appropriate device for streams handled by the specified strategy according to current
300         // phone state, connected devices...
301         // if fromCache is true, the device is returned from mDeviceForStrategy[],
302         // otherwise it is determine by current state
303         // (device connected,phone state, force use, a2dp output...)
304         // This allows to:
305         //  1 speed up process when the state is stable (when starting or stopping an output)
306         //  2 access to either current device selection (fromCache == true) or
307         // "future" device selection (fromCache == false) when called from a context
308         //  where conditions are changing (setDeviceConnectionState(), setPhoneState()...) AND
309         //  before updateDeviceForStrategy() is called.
310         virtual audio_devices_t getDeviceForStrategy(routing_strategy strategy,
311                                                      bool fromCache);
312
313         // change the route of the specified output
314         void setOutputDevice(audio_io_handle_t output,
315                              audio_devices_t device,
316                              bool force = false,
317                              int delayMs = 0);
318
319         // select input device corresponding to requested audio source
320         virtual audio_devices_t getDeviceForInputSource(int inputSource);
321
322         // return io handle of active input or 0 if no input is active
323         audio_io_handle_t getActiveInput();
324
325         // initialize volume curves for each strategy and device category
326         void initializeVolumeCurves();
327
328         // compute the actual volume for a given stream according to the requested index and a particular
329         // device
330         virtual float computeVolume(int stream, int index, audio_io_handle_t output, audio_devices_t device);
331
332         // check that volume change is permitted, compute and send new volume to audio hardware
333         status_t checkAndSetVolume(int stream, int index, audio_io_handle_t output, audio_devices_t device, int delayMs = 0, bool force = false);
334
335         // apply all stream volumes to the specified output and device
336         void applyStreamVolumes(audio_io_handle_t output, audio_devices_t device, int delayMs = 0, bool force = false);
337
338         // Mute or unmute all streams handled by the specified strategy on the specified output
339         void setStrategyMute(routing_strategy strategy, bool on, audio_io_handle_t output, int delayMs = 0);
340
341         // Mute or unmute the stream on the specified output
342         void setStreamMute(int stream, bool on, audio_io_handle_t output, int delayMs = 0);
343
344         // handle special cases for sonification strategy while in call: mute streams or replace by
345         // a special tone in the device used for communication
346         void handleIncallSonification(int stream, bool starting, bool stateChange);
347
348         // true if device is in a telephony or VoIP call
349         virtual bool isInCall();
350
351         // true if given state represents a device in a telephony or VoIP call
352         virtual bool isStateInCall(int state);
353
354         // when a device is connected, checks if an open output can be routed
355         // to this device. If none is open, tries to open one of the available outputs.
356         // Returns an output suitable to this device or 0.
357         // when a device is disconnected, checks if an output is not used any more and
358         // returns its handle if any.
359         // transfers the audio tracks and effects from one output thread to another accordingly.
360         audio_io_handle_t checkOutputForDevice(audio_devices_t device,
361                                                AudioSystem::device_connection_state state);
362
363         // close an output and its companion duplicating output.
364         void closeOutput(audio_io_handle_t output);
365
366         // checks and if necessary changes outputs used for all strategies.
367         // must be called every time a condition that affects the output choice for a given strategy
368         // changes: connected device, phone state, force use...
369         // Must be called before updateDeviceForStrategy()
370         void checkOutputForStrategy(routing_strategy strategy);
371
372         // Same as checkOutputForStrategy() but for a all strategies in order of priority
373         void checkOutputForAllStrategies();
374
375         // manages A2DP output suspend/restore according to phone state and BT SCO usage
376         void checkA2dpSuspend();
377
378         // returns the A2DP output handle if it is open or 0 otherwise
379         audio_io_handle_t getA2dpOutput();
380
381         // selects the most appropriate device on output for current state
382         // must be called every time a condition that affects the device choice for a given output is
383         // changed: connected device, phone state, force use, output start, output stop..
384         // see getDeviceForStrategy() for the use of fromCache parameter
385
386         audio_devices_t getNewDevice(audio_io_handle_t output, bool fromCache);
387         // updates cache of device used by all strategies (mDeviceForStrategy[])
388         // must be called every time a condition that affects the device choice for a given strategy is
389         // changed: connected device, phone state, force use...
390         // cached values are used by getDeviceForStrategy() if parameter fromCache is true.
391          // Must be called after checkOutputForAllStrategies()
392
393         void updateDeviceForStrategy();
394
395         // true if current platform requires a specific output to be opened for this particular
396         // set of parameters. This function is called by getOutput() and is implemented by platform
397         // specific audio policy manager.
398         virtual bool needsDirectOuput(AudioSystem::stream_type stream,
399                                     uint32_t samplingRate,
400                                     uint32_t format,
401                                     uint32_t channels,
402                                     AudioSystem::output_flags flags,
403                                     uint32_t device);
404
405         virtual uint32_t getMaxEffectsCpuLoad();
406         virtual uint32_t getMaxEffectsMemory();
407 #ifdef AUDIO_POLICY_TEST
408         virtual     bool        threadLoop();
409                     void        exit();
410         int testOutputIndex(audio_io_handle_t output);
411 #endif //AUDIO_POLICY_TEST
412
413         status_t setEffectEnabled(EffectDescriptor *pDesc, bool enabled);
414
415         // returns the category the device belongs to with regard to volume curve management
416         static device_category getDeviceCategory(audio_devices_t device);
417
418         // extract one device relevant for volume control from multiple device selection
419         static audio_devices_t getDeviceForVolume(audio_devices_t device);
420
421         SortedVector<audio_io_handle_t> getOutputsForDevice(audio_devices_t device);
422         bool vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
423                                            SortedVector<audio_io_handle_t>& outputs2);
424
425         void checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
426                                        uint32_t delayMs);
427
428         audio_io_handle_t selectOutput(const SortedVector<audio_io_handle_t>& outputs,
429                                        AudioSystem::output_flags flags);
430         IOProfile *getInputProfile(audio_devices_t device,
431                                    uint32_t samplingRate,
432                                    uint32_t format,
433                                    uint32_t channelMask);
434
435         //
436         // Audio policy configuration file parsing (audio_policy.conf)
437         //
438         static uint32_t stringToEnum(const struct StringToEnum *table,
439                                      size_t size,
440                                      const char *name);
441         static audio_policy_output_flags_t parseFlagNames(char *name);
442         static audio_devices_t parseDeviceNames(char *name);
443         void loadSamplingRates(char *name, IOProfile *profile);
444         void loadFormats(char *name, IOProfile *profile);
445         void loadOutChannels(char *name, IOProfile *profile);
446         void loadInChannels(char *name, IOProfile *profile);
447         status_t loadOutput(cnode *root, const char *module);
448         status_t loadInput(cnode *root, const char *module);
449         void loadHwModule(cnode *root);
450         void loadHwModules(cnode *root);
451         void loadGlobalConfig(cnode *root);
452         status_t loadAudioPolicyConfig(const char *path);
453
454
455         AudioPolicyClientInterface *mpClientInterface;  // audio policy client interface
456         audio_io_handle_t mPrimaryOutput;              // primary output handle
457         DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> mOutputs;   // list of output descriptors
458         DefaultKeyedVector<audio_io_handle_t, AudioInputDescriptor *> mInputs;     // list of input descriptors
459         audio_devices_t mAvailableOutputDevices; // bit field of all available output devices
460         audio_devices_t mAvailableInputDevices; // bit field of all available input devices
461         int mPhoneState;                                                    // current phone state
462         AudioSystem::forced_config mForceUse[AudioSystem::NUM_FORCE_USE];   // current forced use configuration
463
464         StreamDescriptor mStreams[AudioSystem::NUM_STREAM_TYPES];           // stream descriptors for volume control
465         String8 mA2dpDeviceAddress;                                         // A2DP device MAC address
466         String8 mScoDeviceAddress;                                          // SCO device MAC address
467         bool    mLimitRingtoneVolume;                                       // limit ringtone volume to music volume if headset connected
468         audio_devices_t mDeviceForStrategy[NUM_STRATEGIES];
469         float   mLastVoiceVolume;                                           // last voice volume value sent to audio HAL
470
471         // Maximum CPU load allocated to audio effects in 0.1 MIPS (ARMv5TE, 0 WS memory) units
472         static const uint32_t MAX_EFFECTS_CPU_LOAD = 1000;
473         // Maximum memory allocated to audio effects in KB
474         static const uint32_t MAX_EFFECTS_MEMORY = 512;
475         uint32_t mTotalEffectsCpuLoad; // current CPU load used by effects
476         uint32_t mTotalEffectsMemory;  // current memory used by effects
477         KeyedVector<int, EffectDescriptor *> mEffects;  // list of registered audio effects
478         bool    mA2dpSuspended;  // true if A2DP output is suspended
479         bool mHasA2dp; // true on platforms with support for bluetooth A2DP
480         audio_devices_t mAttachedOutputDevices; // output devices always available on the platform
481         audio_devices_t mDefaultOutputDevice; // output device selected by default at boot time
482                                               // (must be in mAttachedOutputDevices)
483
484         Vector <IOProfile *> mOutputProfiles; // output profiles loaded from audio_policy.conf
485         Vector <IOProfile *> mInputProfiles;  // input profiles loaded from audio_policy.conf
486
487 #ifdef AUDIO_POLICY_TEST
488         Mutex   mLock;
489         Condition mWaitWorkCV;
490
491         int             mCurOutput;
492         bool            mDirectOutput;
493         audio_io_handle_t mTestOutputs[NUM_TEST_OUTPUTS];
494         int             mTestInput;
495         uint32_t        mTestDevice;
496         uint32_t        mTestSamplingRate;
497         uint32_t        mTestFormat;
498         uint32_t        mTestChannels;
499         uint32_t        mTestLatencyMs;
500 #endif //AUDIO_POLICY_TEST
501
502 private:
503         static float volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
504                 int indexInUi);
505         // updates device caching and output for streams that can influence the
506         //    routing of notifications
507         void handleNotificationRoutingForStream(AudioSystem::stream_type stream);
508 };
509
510 };