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