2 * Copyright (C) 2009 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <sys/types.h>
20 #include <utils/Timers.h>
21 #include <utils/Errors.h>
22 #include <utils/KeyedVector.h>
23 #include <utils/SortedVector.h>
24 #include <hardware_legacy/AudioPolicyInterface.h>
27 namespace android_audio_legacy {
28 using android::KeyedVector;
29 using android::DefaultKeyedVector;
30 using android::SortedVector;
32 // ----------------------------------------------------------------------------
34 #define MAX_DEVICE_ADDRESS_LEN 20
35 // Attenuation applied to STRATEGY_SONIFICATION streams when a headset is connected: 6dB
36 #define SONIFICATION_HEADSET_VOLUME_FACTOR 0.5
37 // Min volume for STRATEGY_SONIFICATION streams when limited by music volume: -36dB
38 #define SONIFICATION_HEADSET_VOLUME_MIN 0.016
39 // Time in milliseconds during which we consider that music is still active after a music
40 // track was stopped - see computeVolume()
41 #define SONIFICATION_HEADSET_MUSIC_DELAY 5000
42 // Time in milliseconds after media stopped playing during which we consider that the
43 // sonification should be as unobtrusive as during the time media was playing.
44 #define SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY 5000
45 // Time in milliseconds during witch some streams are muted while the audio path
47 #define MUTE_TIME_MS 2000
49 #define NUM_TEST_OUTPUTS 5
51 #define NUM_VOL_CURVE_KNEES 2
53 // ----------------------------------------------------------------------------
54 // AudioPolicyManagerBase implements audio policy manager behavior common to all platforms.
55 // Each platform must implement an AudioPolicyManager class derived from AudioPolicyManagerBase
56 // and override methods for which the platform specific behavior differs from the implementation
57 // in AudioPolicyManagerBase. Even if no specific behavior is required, the AudioPolicyManager
58 // class must be implemented as well as the class factory function createAudioPolicyManager()
59 // and provided in a shared library libaudiopolicy.so.
60 // ----------------------------------------------------------------------------
62 // the output_profile_s structure describes the capabilities of an output stream.
63 // It is currently assumed that all combination of listed parameters are supported.
64 // It is used by the policy manager to determine if an output is suitable for a given use case,
65 // open/close it accordingly and connect/disconnect audio tracks to/from it.
66 typedef struct output_profile_s {
67 uint32_t* mSamplingRates; // supported sampling rates (terminated by 0)
68 audio_channel_mask_t* mChannelMasks; // supported channel masks (terminated by 0)
69 audio_format_t* mFormats; // supported audio formats (terminated by 0)
70 audio_devices_t mSupportedDevices; // supported devices (devices this output can be
72 audio_policy_output_flags_t mFlags; // attribute flags (e.g primary output,
76 class AudioPolicyManagerBase: public AudioPolicyInterface
77 #ifdef AUDIO_POLICY_TEST
79 #endif //AUDIO_POLICY_TEST
83 AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface);
84 virtual ~AudioPolicyManagerBase();
86 // AudioPolicyInterface
87 virtual status_t setDeviceConnectionState(AudioSystem::audio_devices device,
88 AudioSystem::device_connection_state state,
89 const char *device_address);
90 virtual AudioSystem::device_connection_state getDeviceConnectionState(AudioSystem::audio_devices device,
91 const char *device_address);
92 virtual void setPhoneState(int state);
93 virtual void setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config);
94 virtual AudioSystem::forced_config getForceUse(AudioSystem::force_use usage);
95 virtual void setSystemProperty(const char* property, const char* value);
96 virtual status_t initCheck();
97 virtual audio_io_handle_t getOutput(AudioSystem::stream_type stream,
98 uint32_t samplingRate = 0,
99 uint32_t format = AudioSystem::FORMAT_DEFAULT,
100 uint32_t channels = 0,
101 AudioSystem::output_flags flags =
102 AudioSystem::OUTPUT_FLAG_INDIRECT);
103 virtual status_t startOutput(audio_io_handle_t output,
104 AudioSystem::stream_type stream,
106 virtual status_t stopOutput(audio_io_handle_t output,
107 AudioSystem::stream_type stream,
109 virtual void releaseOutput(audio_io_handle_t output);
110 virtual audio_io_handle_t getInput(int inputSource,
111 uint32_t samplingRate,
114 AudioSystem::audio_in_acoustics acoustics);
116 // indicates to the audio policy manager that the input starts being used.
117 virtual status_t startInput(audio_io_handle_t input);
119 // indicates to the audio policy manager that the input stops being used.
120 virtual status_t stopInput(audio_io_handle_t input);
121 virtual void releaseInput(audio_io_handle_t input);
122 virtual void initStreamVolume(AudioSystem::stream_type stream,
125 virtual status_t setStreamVolumeIndex(AudioSystem::stream_type stream,
127 audio_devices_t device);
128 virtual status_t getStreamVolumeIndex(AudioSystem::stream_type stream,
130 audio_devices_t device);
132 // return the strategy corresponding to a given stream type
133 virtual uint32_t getStrategyForStream(AudioSystem::stream_type stream);
135 // return the enabled output devices for the given stream type
136 virtual audio_devices_t getDevicesForStream(AudioSystem::stream_type stream);
138 virtual audio_io_handle_t getOutputForEffect(effect_descriptor_t *desc);
139 virtual status_t registerEffect(effect_descriptor_t *desc,
140 audio_io_handle_t io,
144 virtual status_t unregisterEffect(int id);
145 virtual status_t setEffectEnabled(int id, bool enabled);
147 virtual bool isStreamActive(int stream, uint32_t inPastMs = 0) const;
149 virtual status_t dump(int fd);
153 enum routing_strategy {
156 STRATEGY_SONIFICATION,
157 STRATEGY_SONIFICATION_RESPECTFUL,
159 STRATEGY_ENFORCED_AUDIBLE,
163 // 4 points to define the volume attenuation curve, each characterized by the volume
164 // index (from 0 to 100) at which they apply, and the attenuation in dB at that index.
165 // we use 100 steps to avoid rounding errors when computing the volume in volIndexToAmpl()
167 enum { VOLMIN = 0, VOLKNEE1 = 1, VOLKNEE2 = 2, VOLMAX = 3, VOLCNT = 4};
169 class VolumeCurvePoint
173 float mDBAttenuation;
176 // device categories used for volume curve management.
177 enum device_category {
178 DEVICE_CATEGORY_HEADSET,
179 DEVICE_CATEGORY_SPEAKER,
180 DEVICE_CATEGORY_EARPIECE,
184 // default volume curve
185 static const VolumeCurvePoint sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT];
186 // default volume curve for media strategy
187 static const VolumeCurvePoint sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT];
188 // volume curve for media strategy on speakers
189 static const VolumeCurvePoint sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT];
190 // volume curve for sonification strategy on speakers
191 static const VolumeCurvePoint sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT];
192 // default volume curves per strategy and device category. See initializeVolumeCurves()
193 static const VolumeCurvePoint *sVolumeProfiles[NUM_STRATEGIES][DEVICE_CATEGORY_CNT];
195 // descriptor for audio outputs. Used to maintain current configuration of each opened audio output
196 // and keep track of the usage of this output by each audio stream type.
197 class AudioOutputDescriptor
200 AudioOutputDescriptor(const output_profile_t *profile);
202 status_t dump(int fd);
204 audio_devices_t device();
205 void changeRefCount(AudioSystem::stream_type, int delta);
207 uint32_t strategyRefCount(routing_strategy strategy);
208 bool isUsedByStrategy(routing_strategy strategy) { return (strategyRefCount(strategy) != 0);}
209 bool isDuplicated() { return (mOutput1 != NULL && mOutput2 != NULL); }
210 audio_devices_t supportedDevices();
212 audio_io_handle_t mId; // output handle
213 uint32_t mSamplingRate; //
215 uint32_t mChannels; // output configuration
216 uint32_t mLatency; //
217 AudioSystem::output_flags mFlags; //
218 audio_devices_t mDevice; // current device this output is routed to
219 uint32_t mRefCount[AudioSystem::NUM_STREAM_TYPES]; // number of streams of each type using this output
220 nsecs_t mStopTime[AudioSystem::NUM_STREAM_TYPES];
221 AudioOutputDescriptor *mOutput1; // used by duplicated outputs: first output
222 AudioOutputDescriptor *mOutput2; // used by duplicated outputs: second output
223 float mCurVolume[AudioSystem::NUM_STREAM_TYPES]; // current stream volume
224 int mMuteCount[AudioSystem::NUM_STREAM_TYPES]; // mute request counter
225 const output_profile_t *mProfile;
228 // descriptor for audio inputs. Used to maintain current configuration of each opened audio input
229 // and keep track of the usage of this input.
230 class AudioInputDescriptor
233 AudioInputDescriptor();
235 status_t dump(int fd);
237 uint32_t mSamplingRate; //
238 uint32_t mFormat; // input configuration
239 uint32_t mChannels; //
240 AudioSystem::audio_in_acoustics mAcoustics; //
241 audio_devices_t mDevice; // current device this input is routed to
242 uint32_t mRefCount; // number of AudioRecord clients using this output
243 int mInputSource; // input source selected by application (mediarecorder.h)
246 // stream descriptor used for volume control
247 class StreamDescriptor
252 int getVolumeIndex(audio_devices_t device);
255 int mIndexMin; // min volume index
256 int mIndexMax; // max volume index
257 KeyedVector<audio_devices_t, int> mIndexCur; // current volume index per device
258 bool mCanBeMuted; // true is the stream can be muted
260 const VolumeCurvePoint *mVolumeCurve[DEVICE_CATEGORY_CNT];
263 // stream descriptor used for volume control
264 class EffectDescriptor
268 status_t dump(int fd);
270 int mIo; // io the effect is attached to
271 routing_strategy mStrategy; // routing strategy the effect is associated to
272 int mSession; // audio session the effect is on
273 effect_descriptor_t mDesc; // effect descriptor
274 bool mEnabled; // enabled state: CPU load being used or not
277 void addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc);
279 // return the strategy corresponding to a given stream type
280 static routing_strategy getStrategy(AudioSystem::stream_type stream);
282 // return appropriate device for streams handled by the specified strategy according to current
283 // phone state, connected devices...
284 // if fromCache is true, the device is returned from mDeviceForStrategy[], otherwise it is determined
285 // by current state (device connected, phone state, force use, a2dp output...)
287 // 1 speed up process when the state is stable (when starting or stopping an output)
288 // 2 access to either current device selection (fromCache == true) or
289 // "future" device selection (fromCache == false) when called from a context
290 // where conditions are changing (setDeviceConnectionState(), setPhoneState()...) AND
291 // before updateDeviceForStrategy() is called.
292 virtual audio_devices_t getDeviceForStrategy(routing_strategy strategy, bool fromCache = true);
294 // change the route of the specified output
295 void setOutputDevice(audio_io_handle_t output,
296 audio_devices_t device,
300 // select input device corresponding to requested audio source
301 virtual audio_devices_t getDeviceForInputSource(int inputSource);
303 // return io handle of active input or 0 if no input is active
304 audio_io_handle_t getActiveInput();
306 // initialize volume curves for each strategy and device category
307 void initializeVolumeCurves();
309 // compute the actual volume for a given stream according to the requested index and a particular
311 virtual float computeVolume(int stream, int index, audio_io_handle_t output, audio_devices_t device);
313 // check that volume change is permitted, compute and send new volume to audio hardware
314 status_t checkAndSetVolume(int stream, int index, audio_io_handle_t output, audio_devices_t device, int delayMs = 0, bool force = false);
316 // apply all stream volumes to the specified output and device
317 void applyStreamVolumes(audio_io_handle_t output, audio_devices_t device, int delayMs = 0, bool force = false);
319 // Mute or unmute all streams handled by the specified strategy on the specified output
320 void setStrategyMute(routing_strategy strategy, bool on, audio_io_handle_t output, int delayMs = 0);
322 // Mute or unmute the stream on the specified output
323 void setStreamMute(int stream, bool on, audio_io_handle_t output, int delayMs = 0);
325 // handle special cases for sonification strategy while in call: mute streams or replace by
326 // a special tone in the device used for communication
327 void handleIncallSonification(int stream, bool starting, bool stateChange);
329 // true is current platform implements a back microphone
330 virtual bool hasBackMicrophone() const { return false; }
332 // true if device is in a telephony or VoIP call
333 virtual bool isInCall();
335 // true if given state represents a device in a telephony or VoIP call
336 virtual bool isStateInCall(int state);
338 // when a device is connected, checks if an open output can be routed
339 // to this device. If none is open, tries to open one of the available outputs.
340 // Returns an output suitable to this device or 0.
341 // when a device is disconnected, checks if an output is not used any more and
342 // returns its handle if any.
343 // transfers the audio tracks and effects from one output thread to another accordingly.
344 audio_io_handle_t checkOutputForDevice(audio_devices_t device,
345 AudioSystem::device_connection_state state);
347 // close an output and its companion duplicating output.
348 void closeOutput(audio_io_handle_t output);
350 // checks and if necessary changes outputs used for all strategies.
351 // must be called every time a condition that affects the output choice for a given strategy
352 // changes: connected device, phone state, force use...
353 // Must be called before updateDeviceForStrategy()
354 void checkOutputForStrategy(routing_strategy strategy);
356 // Same as checkOutputForStrategy() but for a all strategies in order of priority
357 void checkOutputForAllStrategies();
359 // manages A2DP output suspend/restore according to phone state and BT SCO usage
360 void checkA2dpSuspend();
362 // returns the A2DP output handle if it is open or 0 otherwise
363 audio_io_handle_t getA2dpOutput();
365 // selects the most appropriate device on output for current state
366 // must be called every time a condition that affects the device choice for a given output is
367 // changed: connected device, phone state, force use, output start, output stop..
368 // see getDeviceForStrategy() for the use of fromCache parameter
370 audio_devices_t getNewDevice(audio_io_handle_t output, bool fromCache = true);
371 // updates cache of device used by all strategies (mDeviceForStrategy[])
372 // must be called every time a condition that affects the device choice for a given strategy is
373 // changed: connected device, phone state, force use...
374 // cached values are used by getDeviceForStrategy() if parameter fromCache is true.
375 // Must be called after checkOutputForAllStrategies()
377 void updateDeviceForStrategy();
379 // true if current platform requires a specific output to be opened for this particular
380 // set of parameters. This function is called by getOutput() and is implemented by platform
381 // specific audio policy manager.
382 virtual bool needsDirectOuput(AudioSystem::stream_type stream,
383 uint32_t samplingRate,
386 AudioSystem::output_flags flags,
389 virtual uint32_t getMaxEffectsCpuLoad();
390 virtual uint32_t getMaxEffectsMemory();
391 #ifdef AUDIO_POLICY_TEST
392 virtual bool threadLoop();
394 int testOutputIndex(audio_io_handle_t output);
395 #endif //AUDIO_POLICY_TEST
397 status_t setEffectEnabled(EffectDescriptor *pDesc, bool enabled);
399 // returns the category the device belongs to with regard to volume curve management
400 static device_category getDeviceCategory(audio_devices_t device);
402 // extract one device relevant for volume control from multiple device selection
403 static audio_devices_t getDeviceForVolume(audio_devices_t device);
405 SortedVector<audio_io_handle_t> getOutputsForDevice(audio_devices_t device);
406 bool vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
407 SortedVector<audio_io_handle_t>& outputs2);
409 AudioPolicyClientInterface *mpClientInterface; // audio policy client interface
410 audio_io_handle_t mPrimaryOutput; // primary output handle
411 DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> mOutputs; // list of output descriptors
412 DefaultKeyedVector<audio_io_handle_t, AudioInputDescriptor *> mInputs; // list of input descriptors
413 audio_devices_t mAvailableOutputDevices; // bit field of all available output devices
414 uint32_t mAvailableInputDevices; // bit field of all available input devices
415 int mPhoneState; // current phone state
416 AudioSystem::forced_config mForceUse[AudioSystem::NUM_FORCE_USE]; // current forced use configuration
418 StreamDescriptor mStreams[AudioSystem::NUM_STREAM_TYPES]; // stream descriptors for volume control
419 String8 mA2dpDeviceAddress; // A2DP device MAC address
420 String8 mScoDeviceAddress; // SCO device MAC address
421 bool mLimitRingtoneVolume; // limit ringtone volume to music volume if headset connected
422 audio_devices_t mDeviceForStrategy[NUM_STRATEGIES];
423 float mLastVoiceVolume; // last voice volume value sent to audio HAL
425 // Maximum CPU load allocated to audio effects in 0.1 MIPS (ARMv5TE, 0 WS memory) units
426 static const uint32_t MAX_EFFECTS_CPU_LOAD = 1000;
427 // Maximum memory allocated to audio effects in KB
428 static const uint32_t MAX_EFFECTS_MEMORY = 512;
429 uint32_t mTotalEffectsCpuLoad; // current CPU load used by effects
430 uint32_t mTotalEffectsMemory; // current memory used by effects
431 KeyedVector<int, EffectDescriptor *> mEffects; // list of registered audio effects
432 bool mA2dpSuspended; // true if A2DP output is suspended
434 #ifdef AUDIO_POLICY_TEST
436 Condition mWaitWorkCV;
440 audio_io_handle_t mTestOutputs[NUM_TEST_OUTPUTS];
442 uint32_t mTestDevice;
443 uint32_t mTestSamplingRate;
444 uint32_t mTestFormat;
445 uint32_t mTestChannels;
446 uint32_t mTestLatencyMs;
447 #endif //AUDIO_POLICY_TEST
450 static float volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
452 // updates device caching and output for streams that can influence the
453 // routing of notifications
454 void handleNotificationRoutingForStream(AudioSystem::stream_type stream);