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