AudioPolicyManager.h revision 45ed3b053d9af2250f5ece9ee4e826905c3763a7
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#pragma once 18 19#include <stdint.h> 20#include <sys/types.h> 21#include <cutils/config_utils.h> 22#include <cutils/misc.h> 23#include <utils/Timers.h> 24#include <utils/Errors.h> 25#include <utils/KeyedVector.h> 26#include <utils/SortedVector.h> 27#include <media/AudioPolicy.h> 28#include "AudioPolicyInterface.h" 29 30#include <AudioGain.h> 31#include <AudioPort.h> 32#include <AudioPatch.h> 33#include <ConfigParsingUtils.h> 34#include <DeviceDescriptor.h> 35#include <IOProfile.h> 36#include <HwModule.h> 37#include <AudioInputDescriptor.h> 38#include <AudioOutputDescriptor.h> 39#include <AudioPolicyMix.h> 40#include <EffectDescriptor.h> 41 42namespace android { 43 44// ---------------------------------------------------------------------------- 45 46// Attenuation applied to STRATEGY_SONIFICATION streams when a headset is connected: 6dB 47#define SONIFICATION_HEADSET_VOLUME_FACTOR 0.5 48// Min volume for STRATEGY_SONIFICATION streams when limited by music volume: -36dB 49#define SONIFICATION_HEADSET_VOLUME_MIN 0.016 50// Time in milliseconds during which we consider that music is still active after a music 51// track was stopped - see computeVolume() 52#define SONIFICATION_HEADSET_MUSIC_DELAY 5000 53// Time in milliseconds after media stopped playing during which we consider that the 54// sonification should be as unobtrusive as during the time media was playing. 55#define SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY 5000 56// Time in milliseconds during witch some streams are muted while the audio path 57// is switched 58#define MUTE_TIME_MS 2000 59 60#define NUM_TEST_OUTPUTS 5 61 62#define NUM_VOL_CURVE_KNEES 2 63 64// Default minimum length allowed for offloading a compressed track 65// Can be overridden by the audio.offload.min.duration.secs property 66#define OFFLOAD_DEFAULT_MIN_DURATION_SECS 60 67 68// ---------------------------------------------------------------------------- 69// AudioPolicyManager implements audio policy manager behavior common to all platforms. 70// ---------------------------------------------------------------------------- 71 72class AudioPolicyManager: public AudioPolicyInterface 73#ifdef AUDIO_POLICY_TEST 74 , public Thread 75#endif //AUDIO_POLICY_TEST 76{ 77 78public: 79 AudioPolicyManager(AudioPolicyClientInterface *clientInterface); 80 virtual ~AudioPolicyManager(); 81 82 // AudioPolicyInterface 83 virtual status_t setDeviceConnectionState(audio_devices_t device, 84 audio_policy_dev_state_t state, 85 const char *device_address, 86 const char *device_name); 87 virtual audio_policy_dev_state_t getDeviceConnectionState(audio_devices_t device, 88 const char *device_address); 89 virtual void setPhoneState(audio_mode_t state); 90 virtual void setForceUse(audio_policy_force_use_t usage, 91 audio_policy_forced_cfg_t config); 92 virtual audio_policy_forced_cfg_t getForceUse(audio_policy_force_use_t usage); 93 virtual void setSystemProperty(const char* property, const char* value); 94 virtual status_t initCheck(); 95 virtual audio_io_handle_t getOutput(audio_stream_type_t stream, 96 uint32_t samplingRate, 97 audio_format_t format, 98 audio_channel_mask_t channelMask, 99 audio_output_flags_t flags, 100 const audio_offload_info_t *offloadInfo); 101 virtual status_t getOutputForAttr(const audio_attributes_t *attr, 102 audio_io_handle_t *output, 103 audio_session_t session, 104 audio_stream_type_t *stream, 105 uint32_t samplingRate, 106 audio_format_t format, 107 audio_channel_mask_t channelMask, 108 audio_output_flags_t flags, 109 const audio_offload_info_t *offloadInfo); 110 virtual status_t startOutput(audio_io_handle_t output, 111 audio_stream_type_t stream, 112 audio_session_t session); 113 virtual status_t stopOutput(audio_io_handle_t output, 114 audio_stream_type_t stream, 115 audio_session_t session); 116 virtual void releaseOutput(audio_io_handle_t output, 117 audio_stream_type_t stream, 118 audio_session_t session); 119 virtual status_t getInputForAttr(const audio_attributes_t *attr, 120 audio_io_handle_t *input, 121 audio_session_t session, 122 uint32_t samplingRate, 123 audio_format_t format, 124 audio_channel_mask_t channelMask, 125 audio_input_flags_t flags, 126 input_type_t *inputType); 127 128 // indicates to the audio policy manager that the input starts being used. 129 virtual status_t startInput(audio_io_handle_t input, 130 audio_session_t session); 131 132 // indicates to the audio policy manager that the input stops being used. 133 virtual status_t stopInput(audio_io_handle_t input, 134 audio_session_t session); 135 virtual void releaseInput(audio_io_handle_t input, 136 audio_session_t session); 137 virtual void closeAllInputs(); 138 virtual void initStreamVolume(audio_stream_type_t stream, 139 int indexMin, 140 int indexMax); 141 virtual status_t setStreamVolumeIndex(audio_stream_type_t stream, 142 int index, 143 audio_devices_t device); 144 virtual status_t getStreamVolumeIndex(audio_stream_type_t stream, 145 int *index, 146 audio_devices_t device); 147 148 // return the strategy corresponding to a given stream type 149 virtual uint32_t getStrategyForStream(audio_stream_type_t stream); 150 // return the strategy corresponding to the given audio attributes 151 virtual uint32_t getStrategyForAttr(const audio_attributes_t *attr); 152 153 // return the enabled output devices for the given stream type 154 virtual audio_devices_t getDevicesForStream(audio_stream_type_t stream); 155 156 virtual audio_io_handle_t getOutputForEffect(const effect_descriptor_t *desc = NULL); 157 virtual status_t registerEffect(const effect_descriptor_t *desc, 158 audio_io_handle_t io, 159 uint32_t strategy, 160 int session, 161 int id); 162 virtual status_t unregisterEffect(int id) 163 { 164 return mEffects.unregisterEffect(id); 165 } 166 virtual status_t setEffectEnabled(int id, bool enabled) 167 { 168 return mEffects.setEffectEnabled(id, enabled); 169 } 170 171 virtual bool isStreamActive(audio_stream_type_t stream, uint32_t inPastMs = 0) const 172 { 173 return mOutputs.isStreamActive(stream, inPastMs); 174 } 175 // return whether a stream is playing remotely, override to change the definition of 176 // local/remote playback, used for instance by notification manager to not make 177 // media players lose audio focus when not playing locally 178 // For the base implementation, "remotely" means playing during screen mirroring which 179 // uses an output for playback with a non-empty, non "0" address. 180 virtual bool isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs = 0) const 181 { 182 return mOutputs.isStreamActiveRemotely(stream, inPastMs); 183 } 184 virtual bool isSourceActive(audio_source_t source) const; 185 186 virtual status_t dump(int fd); 187 188 virtual bool isOffloadSupported(const audio_offload_info_t& offloadInfo); 189 190 virtual status_t listAudioPorts(audio_port_role_t role, 191 audio_port_type_t type, 192 unsigned int *num_ports, 193 struct audio_port *ports, 194 unsigned int *generation); 195 virtual status_t getAudioPort(struct audio_port *port); 196 virtual status_t createAudioPatch(const struct audio_patch *patch, 197 audio_patch_handle_t *handle, 198 uid_t uid); 199 virtual status_t releaseAudioPatch(audio_patch_handle_t handle, 200 uid_t uid); 201 virtual status_t listAudioPatches(unsigned int *num_patches, 202 struct audio_patch *patches, 203 unsigned int *generation); 204 virtual status_t setAudioPortConfig(const struct audio_port_config *config); 205 virtual void clearAudioPatches(uid_t uid); 206 207 virtual status_t acquireSoundTriggerSession(audio_session_t *session, 208 audio_io_handle_t *ioHandle, 209 audio_devices_t *device); 210 211 virtual status_t releaseSoundTriggerSession(audio_session_t session); 212 213 virtual status_t registerPolicyMixes(Vector<AudioMix> mixes); 214 virtual status_t unregisterPolicyMixes(Vector<AudioMix> mixes); 215 216 // Audio policy configuration file parsing (audio_policy.conf) 217 // TODO candidates to be moved to ConfigParsingUtils 218 void defaultAudioPolicyConfig(void); 219 220 // return the strategy corresponding to a given stream type 221 static routing_strategy getStrategy(audio_stream_type_t stream); 222protected: 223 void addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc); 224 void removeOutput(audio_io_handle_t output); 225 void addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc); 226 227 // return appropriate device for streams handled by the specified strategy according to current 228 // phone state, connected devices... 229 // if fromCache is true, the device is returned from mDeviceForStrategy[], 230 // otherwise it is determine by current state 231 // (device connected,phone state, force use, a2dp output...) 232 // This allows to: 233 // 1 speed up process when the state is stable (when starting or stopping an output) 234 // 2 access to either current device selection (fromCache == true) or 235 // "future" device selection (fromCache == false) when called from a context 236 // where conditions are changing (setDeviceConnectionState(), setPhoneState()...) AND 237 // before updateDevicesAndOutputs() is called. 238 virtual audio_devices_t getDeviceForStrategy(routing_strategy strategy, 239 bool fromCache); 240 241 // change the route of the specified output. Returns the number of ms we have slept to 242 // allow new routing to take effect in certain cases. 243 virtual uint32_t setOutputDevice(audio_io_handle_t output, 244 audio_devices_t device, 245 bool force = false, 246 int delayMs = 0, 247 audio_patch_handle_t *patchHandle = NULL, 248 const char* address = NULL); 249 status_t resetOutputDevice(audio_io_handle_t output, 250 int delayMs = 0, 251 audio_patch_handle_t *patchHandle = NULL); 252 status_t setInputDevice(audio_io_handle_t input, 253 audio_devices_t device, 254 bool force = false, 255 audio_patch_handle_t *patchHandle = NULL); 256 status_t resetInputDevice(audio_io_handle_t input, 257 audio_patch_handle_t *patchHandle = NULL); 258 259 // select input device corresponding to requested audio source 260 virtual audio_devices_t getDeviceForInputSource(audio_source_t inputSource); 261 262 // initialize volume curves for each strategy and device category 263 void initializeVolumeCurves(); 264 265 // compute the actual volume for a given stream according to the requested index and a particular 266 // device 267 virtual float computeVolume(audio_stream_type_t stream, int index, 268 audio_io_handle_t output, audio_devices_t device); 269 270 // check that volume change is permitted, compute and send new volume to audio hardware 271 virtual status_t checkAndSetVolume(audio_stream_type_t stream, int index, 272 audio_io_handle_t output, 273 audio_devices_t device, 274 int delayMs = 0, bool force = false); 275 276 // apply all stream volumes to the specified output and device 277 void applyStreamVolumes(audio_io_handle_t output, audio_devices_t device, int delayMs = 0, bool force = false); 278 279 // Mute or unmute all streams handled by the specified strategy on the specified output 280 void setStrategyMute(routing_strategy strategy, 281 bool on, 282 audio_io_handle_t output, 283 int delayMs = 0, 284 audio_devices_t device = (audio_devices_t)0); 285 286 // Mute or unmute the stream on the specified output 287 void setStreamMute(audio_stream_type_t stream, 288 bool on, 289 audio_io_handle_t output, 290 int delayMs = 0, 291 audio_devices_t device = (audio_devices_t)0); 292 293 // handle special cases for sonification strategy while in call: mute streams or replace by 294 // a special tone in the device used for communication 295 void handleIncallSonification(audio_stream_type_t stream, bool starting, bool stateChange); 296 297 // true if device is in a telephony or VoIP call 298 virtual bool isInCall(); 299 300 // true if given state represents a device in a telephony or VoIP call 301 virtual bool isStateInCall(int state); 302 303 // when a device is connected, checks if an open output can be routed 304 // to this device. If none is open, tries to open one of the available outputs. 305 // Returns an output suitable to this device or 0. 306 // when a device is disconnected, checks if an output is not used any more and 307 // returns its handle if any. 308 // transfers the audio tracks and effects from one output thread to another accordingly. 309 status_t checkOutputsForDevice(const sp<DeviceDescriptor> devDesc, 310 audio_policy_dev_state_t state, 311 SortedVector<audio_io_handle_t>& outputs, 312 const String8 address); 313 314 status_t checkInputsForDevice(audio_devices_t device, 315 audio_policy_dev_state_t state, 316 SortedVector<audio_io_handle_t>& inputs, 317 const String8 address); 318 319 // close an output and its companion duplicating output. 320 void closeOutput(audio_io_handle_t output); 321 322 // close an input. 323 void closeInput(audio_io_handle_t input); 324 325 // checks and if necessary changes outputs used for all strategies. 326 // must be called every time a condition that affects the output choice for a given strategy 327 // changes: connected device, phone state, force use... 328 // Must be called before updateDevicesAndOutputs() 329 void checkOutputForStrategy(routing_strategy strategy); 330 331 // Same as checkOutputForStrategy() but for a all strategies in order of priority 332 void checkOutputForAllStrategies(); 333 334 // manages A2DP output suspend/restore according to phone state and BT SCO usage 335 void checkA2dpSuspend(); 336 337 // selects the most appropriate device on output for current state 338 // must be called every time a condition that affects the device choice for a given output is 339 // changed: connected device, phone state, force use, output start, output stop.. 340 // see getDeviceForStrategy() for the use of fromCache parameter 341 audio_devices_t getNewOutputDevice(audio_io_handle_t output, bool fromCache); 342 343 // updates cache of device used by all strategies (mDeviceForStrategy[]) 344 // must be called every time a condition that affects the device choice for a given strategy is 345 // changed: connected device, phone state, force use... 346 // cached values are used by getDeviceForStrategy() if parameter fromCache is true. 347 // Must be called after checkOutputForAllStrategies() 348 void updateDevicesAndOutputs(); 349 350 // selects the most appropriate device on input for current state 351 audio_devices_t getNewInputDevice(audio_io_handle_t input); 352 353 virtual uint32_t getMaxEffectsCpuLoad() 354 { 355 return mEffects.getMaxEffectsCpuLoad(); 356 } 357 358 virtual uint32_t getMaxEffectsMemory() 359 { 360 return mEffects.getMaxEffectsMemory(); 361 } 362#ifdef AUDIO_POLICY_TEST 363 virtual bool threadLoop(); 364 void exit(); 365 int testOutputIndex(audio_io_handle_t output); 366#endif //AUDIO_POLICY_TEST 367 368 SortedVector<audio_io_handle_t> getOutputsForDevice(audio_devices_t device, 369 AudioOutputCollection openOutputs); 370 bool vectorsEqual(SortedVector<audio_io_handle_t>& outputs1, 371 SortedVector<audio_io_handle_t>& outputs2); 372 373 // mute/unmute strategies using an incompatible device combination 374 // if muting, wait for the audio in pcm buffer to be drained before proceeding 375 // if unmuting, unmute only after the specified delay 376 // Returns the number of ms waited 377 virtual uint32_t checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc, 378 audio_devices_t prevDevice, 379 uint32_t delayMs); 380 381 audio_io_handle_t selectOutput(const SortedVector<audio_io_handle_t>& outputs, 382 audio_output_flags_t flags, 383 audio_format_t format); 384 // samplingRate parameter is an in/out and so may be modified 385 sp<IOProfile> getInputProfile(audio_devices_t device, 386 String8 address, 387 uint32_t& samplingRate, 388 audio_format_t format, 389 audio_channel_mask_t channelMask, 390 audio_input_flags_t flags); 391 sp<IOProfile> getProfileForDirectOutput(audio_devices_t device, 392 uint32_t samplingRate, 393 audio_format_t format, 394 audio_channel_mask_t channelMask, 395 audio_output_flags_t flags); 396 397 audio_io_handle_t selectOutputForEffects(const SortedVector<audio_io_handle_t>& outputs); 398 399 virtual status_t addAudioPatch(audio_patch_handle_t handle, const sp<AudioPatch>& patch) 400 { 401 return mAudioPatches.addAudioPatch(handle, patch); 402 } 403 virtual status_t removeAudioPatch(audio_patch_handle_t handle) 404 { 405 return mAudioPatches.removeAudioPatch(handle); 406 } 407 408 audio_devices_t availablePrimaryOutputDevices() const 409 { 410 return mOutputs.getSupportedDevices(mPrimaryOutput) & mAvailableOutputDevices.types(); 411 } 412 audio_devices_t availablePrimaryInputDevices() const 413 { 414 return mAvailableInputDevices.getDevicesFromHwModule( 415 mOutputs.valueFor(mPrimaryOutput)->getModuleHandle()); 416 } 417 418 void updateCallRouting(audio_devices_t rxDevice, int delayMs = 0); 419 420 uid_t mUidCached; 421 AudioPolicyClientInterface *mpClientInterface; // audio policy client interface 422 audio_io_handle_t mPrimaryOutput; // primary output handle 423 // list of descriptors for outputs currently opened 424 AudioOutputCollection mOutputs; 425 // copy of mOutputs before setDeviceConnectionState() opens new outputs 426 // reset to mOutputs when updateDevicesAndOutputs() is called. 427 AudioOutputCollection mPreviousOutputs; 428 AudioInputCollection mInputs; // list of input descriptors 429 DeviceVector mAvailableOutputDevices; // all available output devices 430 DeviceVector mAvailableInputDevices; // all available input devices 431 int mPhoneState; // current phone state 432 audio_policy_forced_cfg_t mForceUse[AUDIO_POLICY_FORCE_USE_CNT]; // current forced use configuration 433 434 StreamDescriptor mStreams[AUDIO_STREAM_CNT]; // stream descriptors for volume control 435 bool mLimitRingtoneVolume; // limit ringtone volume to music volume if headset connected 436 audio_devices_t mDeviceForStrategy[NUM_STRATEGIES]; 437 float mLastVoiceVolume; // last voice volume value sent to audio HAL 438 439 EffectDescriptorCollection mEffects; // list of registered audio effects 440 bool mA2dpSuspended; // true if A2DP output is suspended 441 sp<DeviceDescriptor> mDefaultOutputDevice; // output device selected by default at boot time 442 bool mSpeakerDrcEnabled;// true on devices that use DRC on the DEVICE_CATEGORY_SPEAKER path 443 // to boost soft sounds, used to adjust volume curves accordingly 444 445 HwModuleCollection mHwModules; 446 447 volatile int32_t mAudioPortGeneration; 448 449 AudioPatchCollection mAudioPatches; 450 451 DefaultKeyedVector<audio_session_t, audio_io_handle_t> mSoundTriggerSessions; 452 453 sp<AudioPatch> mCallTxPatch; 454 sp<AudioPatch> mCallRxPatch; 455 456 // for supporting "beacon" streams, i.e. streams that only play on speaker, and never 457 // when something other than STREAM_TTS (a.k.a. "Transmitted Through Speaker") is playing 458 enum { 459 STARTING_OUTPUT, 460 STARTING_BEACON, 461 STOPPING_OUTPUT, 462 STOPPING_BEACON 463 }; 464 uint32_t mBeaconMuteRefCount; // ref count for stream that would mute beacon 465 uint32_t mBeaconPlayingRefCount;// ref count for the playing beacon streams 466 bool mBeaconMuted; // has STREAM_TTS been muted 467 468 AudioPolicyMixCollection mPolicyMixes; // list of registered mixes 469 470#ifdef AUDIO_POLICY_TEST 471 Mutex mLock; 472 Condition mWaitWorkCV; 473 474 int mCurOutput; 475 bool mDirectOutput; 476 audio_io_handle_t mTestOutputs[NUM_TEST_OUTPUTS]; 477 int mTestInput; 478 uint32_t mTestDevice; 479 uint32_t mTestSamplingRate; 480 uint32_t mTestFormat; 481 uint32_t mTestChannels; 482 uint32_t mTestLatencyMs; 483#endif //AUDIO_POLICY_TEST 484 485 uint32_t nextAudioPortGeneration(); 486private: 487 // updates device caching and output for streams that can influence the 488 // routing of notifications 489 void handleNotificationRoutingForStream(audio_stream_type_t stream); 490 // find the outputs on a given output descriptor that have the given address. 491 // to be called on an AudioOutputDescriptor whose supported devices (as defined 492 // in mProfile->mSupportedDevices) matches the device whose address is to be matched. 493 // see deviceDistinguishesOnAddress(audio_devices_t) for whether the device type is one 494 // where addresses are used to distinguish between one connected device and another. 495 void findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/, 496 const audio_devices_t device /*in*/, 497 const String8 address /*in*/, 498 SortedVector<audio_io_handle_t>& outputs /*out*/); 499 uint32_t curAudioPortGeneration() const { return mAudioPortGeneration; } 500 // internal method to return the output handle for the given device and format 501 audio_io_handle_t getOutputForDevice( 502 audio_devices_t device, 503 audio_session_t session, 504 audio_stream_type_t stream, 505 uint32_t samplingRate, 506 audio_format_t format, 507 audio_channel_mask_t channelMask, 508 audio_output_flags_t flags, 509 const audio_offload_info_t *offloadInfo); 510 // internal function to derive a stream type value from audio attributes 511 audio_stream_type_t streamTypefromAttributesInt(const audio_attributes_t *attr); 512 // event is one of STARTING_OUTPUT, STARTING_BEACON, STOPPING_OUTPUT, STOPPING_BEACON 513 // returns 0 if no mute/unmute event happened, the largest latency of the device where 514 // the mute/unmute happened 515 uint32_t handleEventForBeacon(int event); 516 uint32_t setBeaconMute(bool mute); 517 bool isValidAttributes(const audio_attributes_t *paa); 518 519 // select input device corresponding to requested audio source and return associated policy 520 // mix if any. Calls getDeviceForInputSource(). 521 audio_devices_t getDeviceAndMixForInputSource(audio_source_t inputSource, 522 AudioMix **policyMix = NULL); 523 524 // Called by setDeviceConnectionState(). 525 status_t setDeviceConnectionStateInt(audio_devices_t device, 526 audio_policy_dev_state_t state, 527 const char *device_address, 528 const char *device_name); 529 530 bool isStrategyActive(const sp<AudioOutputDescriptor> outputDesc, routing_strategy strategy, 531 uint32_t inPastMs = 0, nsecs_t sysTime = 0) const; 532}; 533 534}; 535