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 <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>
29 namespace android_audio_legacy {
30 using android::KeyedVector;
31 using android::DefaultKeyedVector;
32 using android::SortedVector;
34 // ----------------------------------------------------------------------------
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
49 #define MUTE_TIME_MS 2000
51 #define NUM_TEST_OUTPUTS 5
53 #define NUM_VOL_CURVE_KNEES 2
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 // ----------------------------------------------------------------------------
64 class AudioPolicyManagerBase: public AudioPolicyInterface
65 #ifdef AUDIO_POLICY_TEST
67 #endif //AUDIO_POLICY_TEST
71 AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface);
72 virtual ~AudioPolicyManagerBase();
74 // AudioPolicyInterface
75 virtual status_t setDeviceConnectionState(audio_devices_t device,
76 AudioSystem::device_connection_state state,
77 const char *device_address);
78 virtual AudioSystem::device_connection_state getDeviceConnectionState(audio_devices_t 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,
94 virtual status_t stopOutput(audio_io_handle_t output,
95 AudioSystem::stream_type stream,
97 virtual void releaseOutput(audio_io_handle_t output);
98 virtual audio_io_handle_t getInput(int inputSource,
99 uint32_t samplingRate,
102 AudioSystem::audio_in_acoustics acoustics);
104 // indicates to the audio policy manager that the input starts being used.
105 virtual status_t startInput(audio_io_handle_t input);
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,
113 virtual status_t setStreamVolumeIndex(AudioSystem::stream_type stream,
115 audio_devices_t device);
116 virtual status_t getStreamVolumeIndex(AudioSystem::stream_type stream,
118 audio_devices_t device);
120 // return the strategy corresponding to a given stream type
121 virtual uint32_t getStrategyForStream(AudioSystem::stream_type stream);
123 // return the enabled output devices for the given stream type
124 virtual audio_devices_t getDevicesForStream(AudioSystem::stream_type stream);
126 virtual audio_io_handle_t getOutputForEffect(const effect_descriptor_t *desc);
127 virtual status_t registerEffect(const effect_descriptor_t *desc,
128 audio_io_handle_t io,
132 virtual status_t unregisterEffect(int id);
133 virtual status_t setEffectEnabled(int id, bool enabled);
135 virtual bool isStreamActive(int stream, uint32_t inPastMs = 0) const;
136 // return whether a stream is playing remotely, override to change the definition of
137 // local/remote playback, used for instance by notification manager to not make
138 // media players lose audio focus when not playing locally
139 virtual bool isStreamActiveRemotely(int stream, uint32_t inPastMs = 0) const;
140 virtual bool isSourceActive(audio_source_t source) const;
142 virtual status_t dump(int fd);
146 enum routing_strategy {
149 STRATEGY_SONIFICATION,
150 STRATEGY_SONIFICATION_RESPECTFUL,
152 STRATEGY_ENFORCED_AUDIBLE,
156 // 4 points to define the volume attenuation curve, each characterized by the volume
157 // index (from 0 to 100) at which they apply, and the attenuation in dB at that index.
158 // we use 100 steps to avoid rounding errors when computing the volume in volIndexToAmpl()
160 enum { VOLMIN = 0, VOLKNEE1 = 1, VOLKNEE2 = 2, VOLMAX = 3, VOLCNT = 4};
162 class VolumeCurvePoint
166 float mDBAttenuation;
169 // device categories used for volume curve management.
170 enum device_category {
171 DEVICE_CATEGORY_HEADSET,
172 DEVICE_CATEGORY_SPEAKER,
173 DEVICE_CATEGORY_EARPIECE,
181 HwModule(const char *name);
186 const char *const mName; // base name of the audio HW module (primary, a2dp ...)
187 audio_module_handle_t mHandle;
188 Vector <IOProfile *> mOutputProfiles; // output profiles exposed by this module
189 Vector <IOProfile *> mInputProfiles; // input profiles exposed by this module
192 // the IOProfile class describes the capabilities of an output or input stream.
193 // It is currently assumed that all combination of listed parameters are supported.
194 // It is used by the policy manager to determine if an output or input is suitable for
195 // a given use case, open/close it accordingly and connect/disconnect audio tracks
200 IOProfile(HwModule *module);
203 bool isCompatibleProfile(audio_devices_t device,
204 uint32_t samplingRate,
206 uint32_t channelMask,
207 audio_output_flags_t flags) const;
211 // by convention, "0' in the first entry in mSamplingRates, mChannelMasks or mFormats
212 // indicates the supported parameters should be read from the output stream
213 // after it is opened for the first time
214 Vector <uint32_t> mSamplingRates; // supported sampling rates
215 Vector <audio_channel_mask_t> mChannelMasks; // supported channel masks
216 Vector <audio_format_t> mFormats; // supported audio formats
217 audio_devices_t mSupportedDevices; // supported devices (devices this output can be
219 audio_output_flags_t mFlags; // attribute flags (e.g primary output,
220 // direct output...). For outputs only.
221 HwModule *mModule; // audio HW module exposing this I/O stream
224 // default volume curve
225 static const VolumeCurvePoint sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT];
226 // default volume curve for media strategy
227 static const VolumeCurvePoint sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT];
228 // volume curve for media strategy on speakers
229 static const VolumeCurvePoint sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT];
230 // volume curve for sonification strategy on speakers
231 static const VolumeCurvePoint sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT];
232 static const VolumeCurvePoint sDefaultSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT];
233 static const VolumeCurvePoint sHeadsetSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT];
234 static const VolumeCurvePoint sDefaultVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT];
235 static const VolumeCurvePoint sSpeakerVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT];
236 // default volume curves per stream and device category. See initializeVolumeCurves()
237 static const VolumeCurvePoint *sVolumeProfiles[AUDIO_STREAM_CNT][DEVICE_CATEGORY_CNT];
239 // descriptor for audio outputs. Used to maintain current configuration of each opened audio output
240 // and keep track of the usage of this output by each audio stream type.
241 class AudioOutputDescriptor
244 AudioOutputDescriptor(const IOProfile *profile);
246 status_t dump(int fd);
248 audio_devices_t device() const;
249 void changeRefCount(AudioSystem::stream_type stream, int delta);
250 bool isDuplicated() const { return (mOutput1 != NULL && mOutput2 != NULL); }
251 audio_devices_t supportedDevices();
253 bool sharesHwModuleWith(const AudioOutputDescriptor *outputDesc);
254 bool isActive(uint32_t inPastMs = 0) const;
255 bool isStreamActive(AudioSystem::stream_type stream,
256 uint32_t inPastMs = 0,
257 nsecs_t sysTime = 0) const;
258 bool isStrategyActive(routing_strategy strategy,
259 uint32_t inPastMs = 0,
260 nsecs_t sysTime = 0) const;
262 audio_io_handle_t mId; // output handle
263 uint32_t mSamplingRate; //
264 audio_format_t mFormat; //
265 audio_channel_mask_t mChannelMask; // output configuration
266 uint32_t mLatency; //
267 audio_output_flags_t mFlags; //
268 audio_devices_t mDevice; // current device this output is routed to
269 uint32_t mRefCount[AudioSystem::NUM_STREAM_TYPES]; // number of streams of each type using this output
270 nsecs_t mStopTime[AudioSystem::NUM_STREAM_TYPES];
271 AudioOutputDescriptor *mOutput1; // used by duplicated outputs: first output
272 AudioOutputDescriptor *mOutput2; // used by duplicated outputs: second output
273 float mCurVolume[AudioSystem::NUM_STREAM_TYPES]; // current stream volume
274 int mMuteCount[AudioSystem::NUM_STREAM_TYPES]; // mute request counter
275 const IOProfile *mProfile; // I/O profile this output derives from
276 bool mStrategyMutedByDevice[NUM_STRATEGIES]; // strategies muted because of incompatible
277 // device selection. See checkDeviceMuteStrategies()
280 // descriptor for audio inputs. Used to maintain current configuration of each opened audio input
281 // and keep track of the usage of this input.
282 class AudioInputDescriptor
285 AudioInputDescriptor(const IOProfile *profile);
287 status_t dump(int fd);
289 uint32_t mSamplingRate; //
290 audio_format_t mFormat; // input configuration
291 audio_channel_mask_t mChannelMask; //
292 audio_devices_t mDevice; // current device this input is routed to
293 uint32_t mRefCount; // number of AudioRecord clients using this output
294 int mInputSource; // input source selected by application (mediarecorder.h)
295 const IOProfile *mProfile; // I/O profile this output derives from
298 // stream descriptor used for volume control
299 class StreamDescriptor
304 int getVolumeIndex(audio_devices_t device);
307 int mIndexMin; // min volume index
308 int mIndexMax; // max volume index
309 KeyedVector<audio_devices_t, int> mIndexCur; // current volume index per device
310 bool mCanBeMuted; // true is the stream can be muted
312 const VolumeCurvePoint *mVolumeCurve[DEVICE_CATEGORY_CNT];
315 // stream descriptor used for volume control
316 class EffectDescriptor
320 status_t dump(int fd);
322 int mIo; // io the effect is attached to
323 routing_strategy mStrategy; // routing strategy the effect is associated to
324 int mSession; // audio session the effect is on
325 effect_descriptor_t mDesc; // effect descriptor
326 bool mEnabled; // enabled state: CPU load being used or not
329 void addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc);
331 // return the strategy corresponding to a given stream type
332 static routing_strategy getStrategy(AudioSystem::stream_type stream);
334 // return appropriate device for streams handled by the specified strategy according to current
335 // phone state, connected devices...
336 // if fromCache is true, the device is returned from mDeviceForStrategy[],
337 // otherwise it is determine by current state
338 // (device connected,phone state, force use, a2dp output...)
340 // 1 speed up process when the state is stable (when starting or stopping an output)
341 // 2 access to either current device selection (fromCache == true) or
342 // "future" device selection (fromCache == false) when called from a context
343 // where conditions are changing (setDeviceConnectionState(), setPhoneState()...) AND
344 // before updateDevicesAndOutputs() is called.
345 virtual audio_devices_t getDeviceForStrategy(routing_strategy strategy,
348 // change the route of the specified output. Returns the number of ms we have slept to
349 // allow new routing to take effect in certain cases.
350 uint32_t setOutputDevice(audio_io_handle_t output,
351 audio_devices_t device,
355 // select input device corresponding to requested audio source
356 virtual audio_devices_t getDeviceForInputSource(int inputSource);
358 // return io handle of active input or 0 if no input is active
359 // Only considers inputs from physical devices (e.g. main mic, headset mic) when
360 // ignoreVirtualInputs is true.
361 audio_io_handle_t getActiveInput(bool ignoreVirtualInputs = true);
363 // initialize volume curves for each strategy and device category
364 void initializeVolumeCurves();
366 // compute the actual volume for a given stream according to the requested index and a particular
368 virtual float computeVolume(int stream, int index, audio_io_handle_t output, audio_devices_t device);
370 // check that volume change is permitted, compute and send new volume to audio hardware
371 status_t checkAndSetVolume(int stream, int index, audio_io_handle_t output, audio_devices_t device, int delayMs = 0, bool force = false);
373 // apply all stream volumes to the specified output and device
374 void applyStreamVolumes(audio_io_handle_t output, audio_devices_t device, int delayMs = 0, bool force = false);
376 // Mute or unmute all streams handled by the specified strategy on the specified output
377 void setStrategyMute(routing_strategy strategy,
379 audio_io_handle_t output,
381 audio_devices_t device = (audio_devices_t)0);
383 // Mute or unmute the stream on the specified output
384 void setStreamMute(int stream,
386 audio_io_handle_t output,
388 audio_devices_t device = (audio_devices_t)0);
390 // handle special cases for sonification strategy while in call: mute streams or replace by
391 // a special tone in the device used for communication
392 void handleIncallSonification(int stream, bool starting, bool stateChange);
394 // true if device is in a telephony or VoIP call
395 virtual bool isInCall();
397 // true if given state represents a device in a telephony or VoIP call
398 virtual bool isStateInCall(int state);
400 // when a device is connected, checks if an open output can be routed
401 // to this device. If none is open, tries to open one of the available outputs.
402 // Returns an output suitable to this device or 0.
403 // when a device is disconnected, checks if an output is not used any more and
404 // returns its handle if any.
405 // transfers the audio tracks and effects from one output thread to another accordingly.
406 status_t checkOutputsForDevice(audio_devices_t device,
407 AudioSystem::device_connection_state state,
408 SortedVector<audio_io_handle_t>& outputs);
410 // close an output and its companion duplicating output.
411 void closeOutput(audio_io_handle_t output);
413 // checks and if necessary changes outputs used for all strategies.
414 // must be called every time a condition that affects the output choice for a given strategy
415 // changes: connected device, phone state, force use...
416 // Must be called before updateDevicesAndOutputs()
417 void checkOutputForStrategy(routing_strategy strategy);
419 // Same as checkOutputForStrategy() but for a all strategies in order of priority
420 void checkOutputForAllStrategies();
422 // manages A2DP output suspend/restore according to phone state and BT SCO usage
423 void checkA2dpSuspend();
425 // returns the A2DP output handle if it is open or 0 otherwise
426 audio_io_handle_t getA2dpOutput();
428 // selects the most appropriate device on output for current state
429 // must be called every time a condition that affects the device choice for a given output is
430 // changed: connected device, phone state, force use, output start, output stop..
431 // see getDeviceForStrategy() for the use of fromCache parameter
433 audio_devices_t getNewDevice(audio_io_handle_t output, bool fromCache);
434 // updates cache of device used by all strategies (mDeviceForStrategy[])
435 // must be called every time a condition that affects the device choice for a given strategy is
436 // changed: connected device, phone state, force use...
437 // cached values are used by getDeviceForStrategy() if parameter fromCache is true.
438 // Must be called after checkOutputForAllStrategies()
440 void updateDevicesAndOutputs();
442 // true if current platform requires a specific output to be opened for this particular
443 // set of parameters. This function is called by getOutput() and is implemented by platform
444 // specific audio policy manager.
445 virtual bool needsDirectOuput(audio_stream_type_t stream,
446 uint32_t samplingRate,
447 audio_format_t format,
448 audio_channel_mask_t channelMask,
449 audio_output_flags_t flags,
450 audio_devices_t device);
452 virtual uint32_t getMaxEffectsCpuLoad();
453 virtual uint32_t getMaxEffectsMemory();
454 #ifdef AUDIO_POLICY_TEST
455 virtual bool threadLoop();
457 int testOutputIndex(audio_io_handle_t output);
458 #endif //AUDIO_POLICY_TEST
460 status_t setEffectEnabled(EffectDescriptor *pDesc, bool enabled);
462 // returns the category the device belongs to with regard to volume curve management
463 static device_category getDeviceCategory(audio_devices_t device);
465 // extract one device relevant for volume control from multiple device selection
466 static audio_devices_t getDeviceForVolume(audio_devices_t device);
468 SortedVector<audio_io_handle_t> getOutputsForDevice(audio_devices_t device,
469 DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> openOutputs);
470 bool vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
471 SortedVector<audio_io_handle_t>& outputs2);
473 // mute/unmute strategies using an incompatible device combination
474 // if muting, wait for the audio in pcm buffer to be drained before proceeding
475 // if unmuting, unmute only after the specified delay
476 // Returns the number of ms waited
477 uint32_t checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
478 audio_devices_t prevDevice,
481 audio_io_handle_t selectOutput(const SortedVector<audio_io_handle_t>& outputs,
482 AudioSystem::output_flags flags);
483 IOProfile *getInputProfile(audio_devices_t device,
484 uint32_t samplingRate,
486 uint32_t channelMask);
487 IOProfile *getProfileForDirectOutput(audio_devices_t device,
488 uint32_t samplingRate,
490 uint32_t channelMask,
491 audio_output_flags_t flags);
493 // Audio policy configuration file parsing (audio_policy.conf)
495 static uint32_t stringToEnum(const struct StringToEnum *table,
498 static audio_output_flags_t parseFlagNames(char *name);
499 static audio_devices_t parseDeviceNames(char *name);
500 void loadSamplingRates(char *name, IOProfile *profile);
501 void loadFormats(char *name, IOProfile *profile);
502 void loadOutChannels(char *name, IOProfile *profile);
503 void loadInChannels(char *name, IOProfile *profile);
504 status_t loadOutput(cnode *root, HwModule *module);
505 status_t loadInput(cnode *root, HwModule *module);
506 void loadHwModule(cnode *root);
507 void loadHwModules(cnode *root);
508 void loadGlobalConfig(cnode *root);
509 status_t loadAudioPolicyConfig(const char *path);
510 void defaultAudioPolicyConfig(void);
513 AudioPolicyClientInterface *mpClientInterface; // audio policy client interface
514 audio_io_handle_t mPrimaryOutput; // primary output handle
515 // list of descriptors for outputs currently opened
516 DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> mOutputs;
517 // copy of mOutputs before setDeviceConnectionState() opens new outputs
518 // reset to mOutputs when updateDevicesAndOutputs() is called.
519 DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> mPreviousOutputs;
520 DefaultKeyedVector<audio_io_handle_t, AudioInputDescriptor *> mInputs; // list of input descriptors
521 audio_devices_t mAvailableOutputDevices; // bit field of all available output devices
522 audio_devices_t mAvailableInputDevices; // bit field of all available input devices
523 // without AUDIO_DEVICE_BIT_IN to allow direct bit
525 int mPhoneState; // current phone state
526 AudioSystem::forced_config mForceUse[AudioSystem::NUM_FORCE_USE]; // current forced use configuration
528 StreamDescriptor mStreams[AudioSystem::NUM_STREAM_TYPES]; // stream descriptors for volume control
529 String8 mA2dpDeviceAddress; // A2DP device MAC address
530 String8 mScoDeviceAddress; // SCO device MAC address
531 String8 mUsbCardAndDevice; // USB audio ALSA card and device numbers:
532 // card=<card_number>;device=<><device_number>
533 bool mLimitRingtoneVolume; // limit ringtone volume to music volume if headset connected
534 audio_devices_t mDeviceForStrategy[NUM_STRATEGIES];
535 float mLastVoiceVolume; // last voice volume value sent to audio HAL
537 // Maximum CPU load allocated to audio effects in 0.1 MIPS (ARMv5TE, 0 WS memory) units
538 static const uint32_t MAX_EFFECTS_CPU_LOAD = 1000;
539 // Maximum memory allocated to audio effects in KB
540 static const uint32_t MAX_EFFECTS_MEMORY = 512;
541 uint32_t mTotalEffectsCpuLoad; // current CPU load used by effects
542 uint32_t mTotalEffectsMemory; // current memory used by effects
543 KeyedVector<int, EffectDescriptor *> mEffects; // list of registered audio effects
544 bool mA2dpSuspended; // true if A2DP output is suspended
545 bool mHasA2dp; // true on platforms with support for bluetooth A2DP
546 bool mHasUsb; // true on platforms with support for USB audio
547 bool mHasRemoteSubmix; // true on platforms with support for remote presentation of a submix
548 audio_devices_t mAttachedOutputDevices; // output devices always available on the platform
549 audio_devices_t mDefaultOutputDevice; // output device selected by default at boot time
550 // (must be in mAttachedOutputDevices)
552 Vector <HwModule *> mHwModules;
554 #ifdef AUDIO_POLICY_TEST
556 Condition mWaitWorkCV;
560 audio_io_handle_t mTestOutputs[NUM_TEST_OUTPUTS];
562 uint32_t mTestDevice;
563 uint32_t mTestSamplingRate;
564 uint32_t mTestFormat;
565 uint32_t mTestChannels;
566 uint32_t mTestLatencyMs;
567 #endif //AUDIO_POLICY_TEST
570 static float volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
572 // updates device caching and output for streams that can influence the
573 // routing of notifications
574 void handleNotificationRoutingForStream(AudioSystem::stream_type stream);
575 static bool isVirtualInputDevice(audio_devices_t device);