AudioPolicyManager.h revision 1767df778e20c1395afc63b3a0479bd903e7b9f0
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 18#include <stdint.h> 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 <media/AudioPolicy.h> 27#include "AudioPolicyInterface.h" 28 29 30namespace android { 31 32// ---------------------------------------------------------------------------- 33 34// Attenuation applied to STRATEGY_SONIFICATION streams when a headset is connected: 6dB 35#define SONIFICATION_HEADSET_VOLUME_FACTOR 0.5 36// Min volume for STRATEGY_SONIFICATION streams when limited by music volume: -36dB 37#define SONIFICATION_HEADSET_VOLUME_MIN 0.016 38// Time in milliseconds during which we consider that music is still active after a music 39// track was stopped - see computeVolume() 40#define SONIFICATION_HEADSET_MUSIC_DELAY 5000 41// Time in milliseconds after media stopped playing during which we consider that the 42// sonification should be as unobtrusive as during the time media was playing. 43#define SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY 5000 44// Time in milliseconds during witch some streams are muted while the audio path 45// is switched 46#define MUTE_TIME_MS 2000 47 48#define NUM_TEST_OUTPUTS 5 49 50#define NUM_VOL_CURVE_KNEES 2 51 52// Default minimum length allowed for offloading a compressed track 53// Can be overridden by the audio.offload.min.duration.secs property 54#define OFFLOAD_DEFAULT_MIN_DURATION_SECS 60 55 56#define MAX_MIXER_SAMPLING_RATE 48000 57#define MAX_MIXER_CHANNEL_COUNT 8 58 59// ---------------------------------------------------------------------------- 60// AudioPolicyManager implements audio policy manager behavior common to all platforms. 61// ---------------------------------------------------------------------------- 62 63class AudioPolicyManager: public AudioPolicyInterface 64#ifdef AUDIO_POLICY_TEST 65 , public Thread 66#endif //AUDIO_POLICY_TEST 67{ 68 69public: 70 AudioPolicyManager(AudioPolicyClientInterface *clientInterface); 71 virtual ~AudioPolicyManager(); 72 73 // AudioPolicyInterface 74 virtual status_t setDeviceConnectionState(audio_devices_t device, 75 audio_policy_dev_state_t state, 76 const char *device_address); 77 virtual audio_policy_dev_state_t getDeviceConnectionState(audio_devices_t device, 78 const char *device_address); 79 virtual void setPhoneState(audio_mode_t state); 80 virtual void setForceUse(audio_policy_force_use_t usage, 81 audio_policy_forced_cfg_t config); 82 virtual audio_policy_forced_cfg_t getForceUse(audio_policy_force_use_t usage); 83 virtual void setSystemProperty(const char* property, const char* value); 84 virtual status_t initCheck(); 85 virtual audio_io_handle_t getOutput(audio_stream_type_t stream, 86 uint32_t samplingRate, 87 audio_format_t format, 88 audio_channel_mask_t channelMask, 89 audio_output_flags_t flags, 90 const audio_offload_info_t *offloadInfo); 91 virtual status_t getOutputForAttr(const audio_attributes_t *attr, 92 audio_io_handle_t *output, 93 audio_session_t session, 94 audio_stream_type_t *stream, 95 uint32_t samplingRate, 96 audio_format_t format, 97 audio_channel_mask_t channelMask, 98 audio_output_flags_t flags, 99 const audio_offload_info_t *offloadInfo); 100 virtual status_t startOutput(audio_io_handle_t output, 101 audio_stream_type_t stream, 102 audio_session_t session); 103 virtual status_t stopOutput(audio_io_handle_t output, 104 audio_stream_type_t stream, 105 audio_session_t session); 106 virtual void releaseOutput(audio_io_handle_t output, 107 audio_stream_type_t stream, 108 audio_session_t session); 109 virtual status_t getInputForAttr(const audio_attributes_t *attr, 110 audio_io_handle_t *input, 111 audio_session_t session, 112 uint32_t samplingRate, 113 audio_format_t format, 114 audio_channel_mask_t channelMask, 115 audio_input_flags_t flags); 116 117 // indicates to the audio policy manager that the input starts being used. 118 virtual status_t startInput(audio_io_handle_t input, 119 audio_session_t session); 120 121 // indicates to the audio policy manager that the input stops being used. 122 virtual status_t stopInput(audio_io_handle_t input, 123 audio_session_t session); 124 virtual void releaseInput(audio_io_handle_t input, 125 audio_session_t session); 126 virtual void closeAllInputs(); 127 virtual void initStreamVolume(audio_stream_type_t stream, 128 int indexMin, 129 int indexMax); 130 virtual status_t setStreamVolumeIndex(audio_stream_type_t stream, 131 int index, 132 audio_devices_t device); 133 virtual status_t getStreamVolumeIndex(audio_stream_type_t stream, 134 int *index, 135 audio_devices_t device); 136 137 // return the strategy corresponding to a given stream type 138 virtual uint32_t getStrategyForStream(audio_stream_type_t stream); 139 // return the strategy corresponding to the given audio attributes 140 virtual uint32_t getStrategyForAttr(const audio_attributes_t *attr); 141 142 // return the enabled output devices for the given stream type 143 virtual audio_devices_t getDevicesForStream(audio_stream_type_t stream); 144 145 virtual audio_io_handle_t getOutputForEffect(const effect_descriptor_t *desc = NULL); 146 virtual status_t registerEffect(const effect_descriptor_t *desc, 147 audio_io_handle_t io, 148 uint32_t strategy, 149 int session, 150 int id); 151 virtual status_t unregisterEffect(int id); 152 virtual status_t setEffectEnabled(int id, bool enabled); 153 154 virtual bool isStreamActive(audio_stream_type_t stream, uint32_t inPastMs = 0) const; 155 // return whether a stream is playing remotely, override to change the definition of 156 // local/remote playback, used for instance by notification manager to not make 157 // media players lose audio focus when not playing locally 158 // For the base implementation, "remotely" means playing during screen mirroring which 159 // uses an output for playback with a non-empty, non "0" address. 160 virtual bool isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs = 0) const; 161 virtual bool isSourceActive(audio_source_t source) const; 162 163 virtual status_t dump(int fd); 164 165 virtual bool isOffloadSupported(const audio_offload_info_t& offloadInfo); 166 167 virtual status_t listAudioPorts(audio_port_role_t role, 168 audio_port_type_t type, 169 unsigned int *num_ports, 170 struct audio_port *ports, 171 unsigned int *generation); 172 virtual status_t getAudioPort(struct audio_port *port); 173 virtual status_t createAudioPatch(const struct audio_patch *patch, 174 audio_patch_handle_t *handle, 175 uid_t uid); 176 virtual status_t releaseAudioPatch(audio_patch_handle_t handle, 177 uid_t uid); 178 virtual status_t listAudioPatches(unsigned int *num_patches, 179 struct audio_patch *patches, 180 unsigned int *generation); 181 virtual status_t setAudioPortConfig(const struct audio_port_config *config); 182 virtual void clearAudioPatches(uid_t uid); 183 184 virtual status_t acquireSoundTriggerSession(audio_session_t *session, 185 audio_io_handle_t *ioHandle, 186 audio_devices_t *device); 187 188 virtual status_t releaseSoundTriggerSession(audio_session_t session); 189 190 virtual status_t registerPolicyMixes(Vector<AudioMix> mixes); 191 virtual status_t unregisterPolicyMixes(Vector<AudioMix> mixes); 192 193protected: 194 195 enum routing_strategy { 196 STRATEGY_MEDIA, 197 STRATEGY_PHONE, 198 STRATEGY_SONIFICATION, 199 STRATEGY_SONIFICATION_RESPECTFUL, 200 STRATEGY_DTMF, 201 STRATEGY_ENFORCED_AUDIBLE, 202 STRATEGY_TRANSMITTED_THROUGH_SPEAKER, 203 STRATEGY_ACCESSIBILITY, 204 STRATEGY_REROUTING, 205 NUM_STRATEGIES 206 }; 207 208 // 4 points to define the volume attenuation curve, each characterized by the volume 209 // index (from 0 to 100) at which they apply, and the attenuation in dB at that index. 210 // we use 100 steps to avoid rounding errors when computing the volume in volIndexToAmpl() 211 212 enum { VOLMIN = 0, VOLKNEE1 = 1, VOLKNEE2 = 2, VOLMAX = 3, VOLCNT = 4}; 213 214 class VolumeCurvePoint 215 { 216 public: 217 int mIndex; 218 float mDBAttenuation; 219 }; 220 221 // device categories used for volume curve management. 222 enum device_category { 223 DEVICE_CATEGORY_HEADSET, 224 DEVICE_CATEGORY_SPEAKER, 225 DEVICE_CATEGORY_EARPIECE, 226 DEVICE_CATEGORY_EXT_MEDIA, 227 DEVICE_CATEGORY_CNT 228 }; 229 230 class HwModule; 231 232 class AudioGain: public RefBase 233 { 234 public: 235 AudioGain(int index, bool useInChannelMask); 236 virtual ~AudioGain() {} 237 238 void dump(int fd, int spaces, int index) const; 239 240 void getDefaultConfig(struct audio_gain_config *config); 241 status_t checkConfig(const struct audio_gain_config *config); 242 int mIndex; 243 struct audio_gain mGain; 244 bool mUseInChannelMask; 245 }; 246 247 class AudioPort: public virtual RefBase 248 { 249 public: 250 AudioPort(const String8& name, audio_port_type_t type, 251 audio_port_role_t role, const sp<HwModule>& module); 252 virtual ~AudioPort() {} 253 254 virtual void toAudioPort(struct audio_port *port) const; 255 256 void importAudioPort(const sp<AudioPort> port); 257 void clearCapabilities(); 258 259 void loadSamplingRates(char *name); 260 void loadFormats(char *name); 261 void loadOutChannels(char *name); 262 void loadInChannels(char *name); 263 264 audio_gain_mode_t loadGainMode(char *name); 265 void loadGain(cnode *root, int index); 266 void loadGains(cnode *root); 267 268 // searches for an exact match 269 status_t checkExactSamplingRate(uint32_t samplingRate) const; 270 // searches for a compatible match, and returns the best match via updatedSamplingRate 271 status_t checkCompatibleSamplingRate(uint32_t samplingRate, 272 uint32_t *updatedSamplingRate) const; 273 // searches for an exact match 274 status_t checkExactChannelMask(audio_channel_mask_t channelMask) const; 275 // searches for a compatible match, currently implemented for input channel masks only 276 status_t checkCompatibleChannelMask(audio_channel_mask_t channelMask) const; 277 status_t checkFormat(audio_format_t format) const; 278 status_t checkGain(const struct audio_gain_config *gainConfig, int index) const; 279 280 uint32_t pickSamplingRate() const; 281 audio_channel_mask_t pickChannelMask() const; 282 audio_format_t pickFormat() const; 283 284 static const audio_format_t sPcmFormatCompareTable[]; 285 static int compareFormats(audio_format_t format1, audio_format_t format2); 286 287 void dump(int fd, int spaces) const; 288 289 String8 mName; 290 audio_port_type_t mType; 291 audio_port_role_t mRole; 292 bool mUseInChannelMask; 293 // by convention, "0' in the first entry in mSamplingRates, mChannelMasks or mFormats 294 // indicates the supported parameters should be read from the output stream 295 // after it is opened for the first time 296 Vector <uint32_t> mSamplingRates; // supported sampling rates 297 Vector <audio_channel_mask_t> mChannelMasks; // supported channel masks 298 Vector <audio_format_t> mFormats; // supported audio formats 299 Vector < sp<AudioGain> > mGains; // gain controllers 300 sp<HwModule> mModule; // audio HW module exposing this I/O stream 301 uint32_t mFlags; // attribute flags (e.g primary output, 302 // direct output...). 303 }; 304 305 class AudioPortConfig: public virtual RefBase 306 { 307 public: 308 AudioPortConfig(); 309 virtual ~AudioPortConfig() {} 310 311 status_t applyAudioPortConfig(const struct audio_port_config *config, 312 struct audio_port_config *backupConfig = NULL); 313 virtual void toAudioPortConfig(struct audio_port_config *dstConfig, 314 const struct audio_port_config *srcConfig = NULL) const = 0; 315 virtual sp<AudioPort> getAudioPort() const = 0; 316 uint32_t mSamplingRate; 317 audio_format_t mFormat; 318 audio_channel_mask_t mChannelMask; 319 struct audio_gain_config mGain; 320 }; 321 322 323 class AudioPatch: public RefBase 324 { 325 public: 326 AudioPatch(audio_patch_handle_t handle, 327 const struct audio_patch *patch, uid_t uid) : 328 mHandle(handle), mPatch(*patch), mUid(uid), mAfPatchHandle(0) {} 329 330 status_t dump(int fd, int spaces, int index) const; 331 332 audio_patch_handle_t mHandle; 333 struct audio_patch mPatch; 334 uid_t mUid; 335 audio_patch_handle_t mAfPatchHandle; 336 }; 337 338 class DeviceDescriptor: public AudioPort, public AudioPortConfig 339 { 340 public: 341 DeviceDescriptor(const String8& name, audio_devices_t type); 342 343 virtual ~DeviceDescriptor() {} 344 345 bool equals(const sp<DeviceDescriptor>& other) const; 346 virtual void toAudioPortConfig(struct audio_port_config *dstConfig, 347 const struct audio_port_config *srcConfig = NULL) const; 348 virtual sp<AudioPort> getAudioPort() const { return (AudioPort*) this; } 349 350 virtual void toAudioPort(struct audio_port *port) const; 351 352 status_t dump(int fd, int spaces, int index) const; 353 354 audio_devices_t mDeviceType; 355 String8 mAddress; 356 audio_port_handle_t mId; 357 }; 358 359 class DeviceVector : public SortedVector< sp<DeviceDescriptor> > 360 { 361 public: 362 DeviceVector() : SortedVector(), mDeviceTypes(AUDIO_DEVICE_NONE) {} 363 364 ssize_t add(const sp<DeviceDescriptor>& item); 365 ssize_t remove(const sp<DeviceDescriptor>& item); 366 ssize_t indexOf(const sp<DeviceDescriptor>& item) const; 367 368 audio_devices_t types() const { return mDeviceTypes; } 369 370 void loadDevicesFromType(audio_devices_t types); 371 void loadDevicesFromName(char *name, const DeviceVector& declaredDevices); 372 373 sp<DeviceDescriptor> getDevice(audio_devices_t type, String8 address) const; 374 DeviceVector getDevicesFromType(audio_devices_t types) const; 375 sp<DeviceDescriptor> getDeviceFromId(audio_port_handle_t id) const; 376 sp<DeviceDescriptor> getDeviceFromName(const String8& name) const; 377 DeviceVector getDevicesFromTypeAddr(audio_devices_t type, String8 address) 378 const; 379 380 private: 381 void refreshTypes(); 382 audio_devices_t mDeviceTypes; 383 }; 384 385 // the IOProfile class describes the capabilities of an output or input stream. 386 // It is currently assumed that all combination of listed parameters are supported. 387 // It is used by the policy manager to determine if an output or input is suitable for 388 // a given use case, open/close it accordingly and connect/disconnect audio tracks 389 // to/from it. 390 class IOProfile : public AudioPort 391 { 392 public: 393 IOProfile(const String8& name, audio_port_role_t role, const sp<HwModule>& module); 394 virtual ~IOProfile(); 395 396 // This method is used for both output and input. 397 // If parameter updatedSamplingRate is non-NULL, it is assigned the actual sample rate. 398 // For input, flags is interpreted as audio_input_flags_t. 399 // TODO: merge audio_output_flags_t and audio_input_flags_t. 400 bool isCompatibleProfile(audio_devices_t device, 401 String8 address, 402 uint32_t samplingRate, 403 uint32_t *updatedSamplingRate, 404 audio_format_t format, 405 audio_channel_mask_t channelMask, 406 uint32_t flags) const; 407 408 void dump(int fd); 409 void log(); 410 411 DeviceVector mSupportedDevices; // supported devices 412 // (devices this output can be routed to) 413 }; 414 415 class HwModule : public RefBase 416 { 417 public: 418 HwModule(const char *name); 419 ~HwModule(); 420 421 status_t loadOutput(cnode *root); 422 status_t loadInput(cnode *root); 423 status_t loadDevice(cnode *root); 424 425 status_t addOutputProfile(String8 name, const audio_config_t *config, 426 audio_devices_t device, String8 address); 427 status_t removeOutputProfile(String8 name); 428 status_t addInputProfile(String8 name, const audio_config_t *config, 429 audio_devices_t device, String8 address); 430 status_t removeInputProfile(String8 name); 431 432 void dump(int fd); 433 434 const char *const mName; // base name of the audio HW module (primary, a2dp ...) 435 uint32_t mHalVersion; // audio HAL API version 436 audio_module_handle_t mHandle; 437 Vector < sp<IOProfile> > mOutputProfiles; // output profiles exposed by this module 438 Vector < sp<IOProfile> > mInputProfiles; // input profiles exposed by this module 439 DeviceVector mDeclaredDevices; // devices declared in audio_policy.conf 440 441 }; 442 443 // default volume curve 444 static const VolumeCurvePoint sDefaultVolumeCurve[AudioPolicyManager::VOLCNT]; 445 // default volume curve for media strategy 446 static const VolumeCurvePoint sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT]; 447 // volume curve for non-media audio on ext media outputs (HDMI, Line, etc) 448 static const VolumeCurvePoint sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT]; 449 // volume curve for media strategy on speakers 450 static const VolumeCurvePoint sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT]; 451 static const VolumeCurvePoint sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT]; 452 // volume curve for sonification strategy on speakers 453 static const VolumeCurvePoint sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT]; 454 static const VolumeCurvePoint sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT]; 455 static const VolumeCurvePoint sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT]; 456 static const VolumeCurvePoint sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT]; 457 static const VolumeCurvePoint sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT]; 458 static const VolumeCurvePoint sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT]; 459 static const VolumeCurvePoint sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT]; 460 static const VolumeCurvePoint sLinearVolumeCurve[AudioPolicyManager::VOLCNT]; 461 static const VolumeCurvePoint sSilentVolumeCurve[AudioPolicyManager::VOLCNT]; 462 static const VolumeCurvePoint sFullScaleVolumeCurve[AudioPolicyManager::VOLCNT]; 463 // default volume curves per stream and device category. See initializeVolumeCurves() 464 static const VolumeCurvePoint *sVolumeProfiles[AUDIO_STREAM_CNT][DEVICE_CATEGORY_CNT]; 465 466 // descriptor for audio outputs. Used to maintain current configuration of each opened audio output 467 // and keep track of the usage of this output by each audio stream type. 468 class AudioOutputDescriptor: public AudioPortConfig 469 { 470 public: 471 AudioOutputDescriptor(const sp<IOProfile>& profile); 472 473 status_t dump(int fd); 474 475 audio_devices_t device() const; 476 void changeRefCount(audio_stream_type_t stream, int delta); 477 478 bool isDuplicated() const { return (mOutput1 != NULL && mOutput2 != NULL); } 479 audio_devices_t supportedDevices(); 480 uint32_t latency(); 481 bool sharesHwModuleWith(const sp<AudioOutputDescriptor> outputDesc); 482 bool isActive(uint32_t inPastMs = 0) const; 483 bool isStreamActive(audio_stream_type_t stream, 484 uint32_t inPastMs = 0, 485 nsecs_t sysTime = 0) const; 486 bool isStrategyActive(routing_strategy strategy, 487 uint32_t inPastMs = 0, 488 nsecs_t sysTime = 0) const; 489 490 virtual void toAudioPortConfig(struct audio_port_config *dstConfig, 491 const struct audio_port_config *srcConfig = NULL) const; 492 virtual sp<AudioPort> getAudioPort() const { return mProfile; } 493 void toAudioPort(struct audio_port *port) const; 494 495 audio_port_handle_t mId; 496 audio_io_handle_t mIoHandle; // output handle 497 uint32_t mLatency; // 498 audio_output_flags_t mFlags; // 499 audio_devices_t mDevice; // current device this output is routed to 500 String8 mPolicyMixAddress; // non empty or "0" when used by a dynamic policy 501 audio_patch_handle_t mPatchHandle; 502 uint32_t mRefCount[AUDIO_STREAM_CNT]; // number of streams of each type using this output 503 nsecs_t mStopTime[AUDIO_STREAM_CNT]; 504 sp<AudioOutputDescriptor> mOutput1; // used by duplicated outputs: first output 505 sp<AudioOutputDescriptor> mOutput2; // used by duplicated outputs: second output 506 float mCurVolume[AUDIO_STREAM_CNT]; // current stream volume 507 int mMuteCount[AUDIO_STREAM_CNT]; // mute request counter 508 const sp<IOProfile> mProfile; // I/O profile this output derives from 509 bool mStrategyMutedByDevice[NUM_STRATEGIES]; // strategies muted because of incompatible 510 // device selection. See checkDeviceMuteStrategies() 511 uint32_t mDirectOpenCount; // number of clients using this output (direct outputs only) 512 }; 513 514 // descriptor for audio inputs. Used to maintain current configuration of each opened audio input 515 // and keep track of the usage of this input. 516 class AudioInputDescriptor: public AudioPortConfig 517 { 518 public: 519 AudioInputDescriptor(const sp<IOProfile>& profile); 520 521 status_t dump(int fd); 522 523 audio_port_handle_t mId; 524 audio_io_handle_t mIoHandle; // input handle 525 audio_devices_t mDevice; // current device this input is routed to 526 audio_patch_handle_t mPatchHandle; 527 uint32_t mRefCount; // number of AudioRecord clients using 528 // this input 529 uint32_t mOpenRefCount; 530 audio_source_t mInputSource; // input source selected by application 531 //(mediarecorder.h) 532 const sp<IOProfile> mProfile; // I/O profile this output derives from 533 // audio sessions attached to this input and the 534 // corresponding device address 535 DefaultKeyedVector<audio_session_t, String8> mSessions; 536 bool mIsSoundTrigger; // used by a soundtrigger capture 537 538 virtual void toAudioPortConfig(struct audio_port_config *dstConfig, 539 const struct audio_port_config *srcConfig = NULL) const; 540 virtual sp<AudioPort> getAudioPort() const { return mProfile; } 541 void toAudioPort(struct audio_port *port) const; 542 }; 543 544 // stream descriptor used for volume control 545 class StreamDescriptor 546 { 547 public: 548 StreamDescriptor(); 549 550 int getVolumeIndex(audio_devices_t device); 551 void dump(int fd); 552 553 int mIndexMin; // min volume index 554 int mIndexMax; // max volume index 555 KeyedVector<audio_devices_t, int> mIndexCur; // current volume index per device 556 bool mCanBeMuted; // true is the stream can be muted 557 558 const VolumeCurvePoint *mVolumeCurve[DEVICE_CATEGORY_CNT]; 559 }; 560 561 // stream descriptor used for volume control 562 class EffectDescriptor : public RefBase 563 { 564 public: 565 566 status_t dump(int fd); 567 568 int mIo; // io the effect is attached to 569 routing_strategy mStrategy; // routing strategy the effect is associated to 570 int mSession; // audio session the effect is on 571 effect_descriptor_t mDesc; // effect descriptor 572 bool mEnabled; // enabled state: CPU load being used or not 573 }; 574 575 void addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc); 576 void addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc); 577 578 // return the strategy corresponding to a given stream type 579 static routing_strategy getStrategy(audio_stream_type_t stream); 580 581 // return appropriate device for streams handled by the specified strategy according to current 582 // phone state, connected devices... 583 // if fromCache is true, the device is returned from mDeviceForStrategy[], 584 // otherwise it is determine by current state 585 // (device connected,phone state, force use, a2dp output...) 586 // This allows to: 587 // 1 speed up process when the state is stable (when starting or stopping an output) 588 // 2 access to either current device selection (fromCache == true) or 589 // "future" device selection (fromCache == false) when called from a context 590 // where conditions are changing (setDeviceConnectionState(), setPhoneState()...) AND 591 // before updateDevicesAndOutputs() is called. 592 virtual audio_devices_t getDeviceForStrategy(routing_strategy strategy, 593 bool fromCache); 594 595 // change the route of the specified output. Returns the number of ms we have slept to 596 // allow new routing to take effect in certain cases. 597 uint32_t setOutputDevice(audio_io_handle_t output, 598 audio_devices_t device, 599 bool force = false, 600 int delayMs = 0, 601 audio_patch_handle_t *patchHandle = NULL, 602 const char* address = NULL); 603 status_t resetOutputDevice(audio_io_handle_t output, 604 int delayMs = 0, 605 audio_patch_handle_t *patchHandle = NULL); 606 status_t setInputDevice(audio_io_handle_t input, 607 audio_devices_t device, 608 bool force = false, 609 audio_patch_handle_t *patchHandle = NULL); 610 status_t resetInputDevice(audio_io_handle_t input, 611 audio_patch_handle_t *patchHandle = NULL); 612 613 // select input device corresponding to requested audio source 614 virtual audio_devices_t getDeviceForInputSource(audio_source_t inputSource, 615 String8 *address = NULL); 616 617 // return io handle of active input or 0 if no input is active 618 // Only considers inputs from physical devices (e.g. main mic, headset mic) when 619 // ignoreVirtualInputs is true. 620 audio_io_handle_t getActiveInput(bool ignoreVirtualInputs = true); 621 622 uint32_t activeInputsCount() const; 623 624 // initialize volume curves for each strategy and device category 625 void initializeVolumeCurves(); 626 627 // compute the actual volume for a given stream according to the requested index and a particular 628 // device 629 virtual float computeVolume(audio_stream_type_t stream, int index, 630 audio_io_handle_t output, audio_devices_t device); 631 632 // check that volume change is permitted, compute and send new volume to audio hardware 633 virtual status_t checkAndSetVolume(audio_stream_type_t stream, int index, 634 audio_io_handle_t output, 635 audio_devices_t device, 636 int delayMs = 0, bool force = false); 637 638 // apply all stream volumes to the specified output and device 639 void applyStreamVolumes(audio_io_handle_t output, audio_devices_t device, int delayMs = 0, bool force = false); 640 641 // Mute or unmute all streams handled by the specified strategy on the specified output 642 void setStrategyMute(routing_strategy strategy, 643 bool on, 644 audio_io_handle_t output, 645 int delayMs = 0, 646 audio_devices_t device = (audio_devices_t)0); 647 648 // Mute or unmute the stream on the specified output 649 void setStreamMute(audio_stream_type_t stream, 650 bool on, 651 audio_io_handle_t output, 652 int delayMs = 0, 653 audio_devices_t device = (audio_devices_t)0); 654 655 // handle special cases for sonification strategy while in call: mute streams or replace by 656 // a special tone in the device used for communication 657 void handleIncallSonification(audio_stream_type_t stream, bool starting, bool stateChange); 658 659 // true if device is in a telephony or VoIP call 660 virtual bool isInCall(); 661 662 // true if given state represents a device in a telephony or VoIP call 663 virtual bool isStateInCall(int state); 664 665 // when a device is connected, checks if an open output can be routed 666 // to this device. If none is open, tries to open one of the available outputs. 667 // Returns an output suitable to this device or 0. 668 // when a device is disconnected, checks if an output is not used any more and 669 // returns its handle if any. 670 // transfers the audio tracks and effects from one output thread to another accordingly. 671 status_t checkOutputsForDevice(const sp<DeviceDescriptor> devDesc, 672 audio_policy_dev_state_t state, 673 SortedVector<audio_io_handle_t>& outputs, 674 const String8 address); 675 676 status_t checkInputsForDevice(audio_devices_t device, 677 audio_policy_dev_state_t state, 678 SortedVector<audio_io_handle_t>& inputs, 679 const String8 address); 680 681 // close an output and its companion duplicating output. 682 void closeOutput(audio_io_handle_t output); 683 684 // close an input. 685 void closeInput(audio_io_handle_t input); 686 687 // checks and if necessary changes outputs used for all strategies. 688 // must be called every time a condition that affects the output choice for a given strategy 689 // changes: connected device, phone state, force use... 690 // Must be called before updateDevicesAndOutputs() 691 void checkOutputForStrategy(routing_strategy strategy); 692 693 // Same as checkOutputForStrategy() but for a all strategies in order of priority 694 void checkOutputForAllStrategies(); 695 696 // manages A2DP output suspend/restore according to phone state and BT SCO usage 697 void checkA2dpSuspend(); 698 699 // returns the A2DP output handle if it is open or 0 otherwise 700 audio_io_handle_t getA2dpOutput(); 701 702 // selects the most appropriate device on output for current state 703 // must be called every time a condition that affects the device choice for a given output is 704 // changed: connected device, phone state, force use, output start, output stop.. 705 // see getDeviceForStrategy() for the use of fromCache parameter 706 audio_devices_t getNewOutputDevice(audio_io_handle_t output, bool fromCache); 707 708 // updates cache of device used by all strategies (mDeviceForStrategy[]) 709 // must be called every time a condition that affects the device choice for a given strategy is 710 // changed: connected device, phone state, force use... 711 // cached values are used by getDeviceForStrategy() if parameter fromCache is true. 712 // Must be called after checkOutputForAllStrategies() 713 void updateDevicesAndOutputs(); 714 715 // selects the most appropriate device on input for current state 716 audio_devices_t getNewInputDevice(audio_io_handle_t input); 717 718 virtual uint32_t getMaxEffectsCpuLoad(); 719 virtual uint32_t getMaxEffectsMemory(); 720#ifdef AUDIO_POLICY_TEST 721 virtual bool threadLoop(); 722 void exit(); 723 int testOutputIndex(audio_io_handle_t output); 724#endif //AUDIO_POLICY_TEST 725 726 status_t setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled); 727 728 // returns the category the device belongs to with regard to volume curve management 729 static device_category getDeviceCategory(audio_devices_t device); 730 731 // extract one device relevant for volume control from multiple device selection 732 static audio_devices_t getDeviceForVolume(audio_devices_t device); 733 734 SortedVector<audio_io_handle_t> getOutputsForDevice(audio_devices_t device, 735 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs); 736 bool vectorsEqual(SortedVector<audio_io_handle_t>& outputs1, 737 SortedVector<audio_io_handle_t>& outputs2); 738 739 // mute/unmute strategies using an incompatible device combination 740 // if muting, wait for the audio in pcm buffer to be drained before proceeding 741 // if unmuting, unmute only after the specified delay 742 // Returns the number of ms waited 743 virtual uint32_t checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc, 744 audio_devices_t prevDevice, 745 uint32_t delayMs); 746 747 audio_io_handle_t selectOutput(const SortedVector<audio_io_handle_t>& outputs, 748 audio_output_flags_t flags, 749 audio_format_t format); 750 // samplingRate parameter is an in/out and so may be modified 751 sp<IOProfile> getInputProfile(audio_devices_t device, 752 String8 address, 753 uint32_t& samplingRate, 754 audio_format_t format, 755 audio_channel_mask_t channelMask, 756 audio_input_flags_t flags); 757 sp<IOProfile> getProfileForDirectOutput(audio_devices_t device, 758 uint32_t samplingRate, 759 audio_format_t format, 760 audio_channel_mask_t channelMask, 761 audio_output_flags_t flags); 762 763 audio_io_handle_t selectOutputForEffects(const SortedVector<audio_io_handle_t>& outputs); 764 765 bool isNonOffloadableEffectEnabled(); 766 767 status_t addAudioPatch(audio_patch_handle_t handle, 768 const sp<AudioPatch>& patch); 769 status_t removeAudioPatch(audio_patch_handle_t handle); 770 771 sp<AudioOutputDescriptor> getOutputFromId(audio_port_handle_t id) const; 772 sp<AudioInputDescriptor> getInputFromId(audio_port_handle_t id) const; 773 sp<HwModule> getModuleForDevice(audio_devices_t device) const; 774 sp<HwModule> getModuleFromName(const char *name) const; 775 audio_devices_t availablePrimaryOutputDevices(); 776 audio_devices_t availablePrimaryInputDevices(); 777 778 void updateCallRouting(audio_devices_t rxDevice, int delayMs = 0); 779 780 // 781 // Audio policy configuration file parsing (audio_policy.conf) 782 // 783 static uint32_t stringToEnum(const struct StringToEnum *table, 784 size_t size, 785 const char *name); 786 static const char *enumToString(const struct StringToEnum *table, 787 size_t size, 788 uint32_t value); 789 static bool stringToBool(const char *value); 790 static uint32_t parseOutputFlagNames(char *name); 791 static uint32_t parseInputFlagNames(char *name); 792 static audio_devices_t parseDeviceNames(char *name); 793 void loadHwModule(cnode *root); 794 void loadHwModules(cnode *root); 795 void loadGlobalConfig(cnode *root, const sp<HwModule>& module); 796 status_t loadAudioPolicyConfig(const char *path); 797 void defaultAudioPolicyConfig(void); 798 799 800 uid_t mUidCached; 801 AudioPolicyClientInterface *mpClientInterface; // audio policy client interface 802 audio_io_handle_t mPrimaryOutput; // primary output handle 803 // list of descriptors for outputs currently opened 804 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > mOutputs; 805 // copy of mOutputs before setDeviceConnectionState() opens new outputs 806 // reset to mOutputs when updateDevicesAndOutputs() is called. 807 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > mPreviousOutputs; 808 DefaultKeyedVector<audio_io_handle_t, sp<AudioInputDescriptor> > mInputs; // list of input descriptors 809 DeviceVector mAvailableOutputDevices; // all available output devices 810 DeviceVector mAvailableInputDevices; // all available input devices 811 int mPhoneState; // current phone state 812 audio_policy_forced_cfg_t mForceUse[AUDIO_POLICY_FORCE_USE_CNT]; // current forced use configuration 813 814 StreamDescriptor mStreams[AUDIO_STREAM_CNT]; // stream descriptors for volume control 815 bool mLimitRingtoneVolume; // limit ringtone volume to music volume if headset connected 816 audio_devices_t mDeviceForStrategy[NUM_STRATEGIES]; 817 float mLastVoiceVolume; // last voice volume value sent to audio HAL 818 819 // Maximum CPU load allocated to audio effects in 0.1 MIPS (ARMv5TE, 0 WS memory) units 820 static const uint32_t MAX_EFFECTS_CPU_LOAD = 1000; 821 // Maximum memory allocated to audio effects in KB 822 static const uint32_t MAX_EFFECTS_MEMORY = 512; 823 uint32_t mTotalEffectsCpuLoad; // current CPU load used by effects 824 uint32_t mTotalEffectsMemory; // current memory used by effects 825 KeyedVector<int, sp<EffectDescriptor> > mEffects; // list of registered audio effects 826 bool mA2dpSuspended; // true if A2DP output is suspended 827 sp<DeviceDescriptor> mDefaultOutputDevice; // output device selected by default at boot time 828 bool mSpeakerDrcEnabled;// true on devices that use DRC on the DEVICE_CATEGORY_SPEAKER path 829 // to boost soft sounds, used to adjust volume curves accordingly 830 831 Vector < sp<HwModule> > mHwModules; 832 volatile int32_t mNextUniqueId; 833 volatile int32_t mAudioPortGeneration; 834 835 DefaultKeyedVector<audio_patch_handle_t, sp<AudioPatch> > mAudioPatches; 836 837 DefaultKeyedVector<audio_session_t, audio_io_handle_t> mSoundTriggerSessions; 838 839 sp<AudioPatch> mCallTxPatch; 840 sp<AudioPatch> mCallRxPatch; 841 842 // for supporting "beacon" streams, i.e. streams that only play on speaker, and never 843 // when something other than STREAM_TTS (a.k.a. "Transmitted Through Speaker") is playing 844 enum { 845 STARTING_OUTPUT, 846 STARTING_BEACON, 847 STOPPING_OUTPUT, 848 STOPPING_BEACON 849 }; 850 uint32_t mBeaconMuteRefCount; // ref count for stream that would mute beacon 851 uint32_t mBeaconPlayingRefCount;// ref count for the playing beacon streams 852 bool mBeaconMuted; // has STREAM_TTS been muted 853 854 // custom mix entry in mPolicyMixes 855 class AudioPolicyMix : public RefBase { 856 public: 857 AudioPolicyMix() {} 858 859 AudioMix mMix; // Audio policy mix descriptor 860 sp<AudioOutputDescriptor> mOutput; // Corresponding output stream 861 }; 862 DefaultKeyedVector<String8, sp<AudioPolicyMix> > mPolicyMixes; // list of registered mixes 863 864 865#ifdef AUDIO_POLICY_TEST 866 Mutex mLock; 867 Condition mWaitWorkCV; 868 869 int mCurOutput; 870 bool mDirectOutput; 871 audio_io_handle_t mTestOutputs[NUM_TEST_OUTPUTS]; 872 int mTestInput; 873 uint32_t mTestDevice; 874 uint32_t mTestSamplingRate; 875 uint32_t mTestFormat; 876 uint32_t mTestChannels; 877 uint32_t mTestLatencyMs; 878#endif //AUDIO_POLICY_TEST 879 static float volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc, 880 int indexInUi); 881private: 882 // updates device caching and output for streams that can influence the 883 // routing of notifications 884 void handleNotificationRoutingForStream(audio_stream_type_t stream); 885 static bool isVirtualInputDevice(audio_devices_t device); 886 static bool deviceDistinguishesOnAddress(audio_devices_t device); 887 // find the outputs on a given output descriptor that have the given address. 888 // to be called on an AudioOutputDescriptor whose supported devices (as defined 889 // in mProfile->mSupportedDevices) matches the device whose address is to be matched. 890 // see deviceDistinguishesOnAddress(audio_devices_t) for whether the device type is one 891 // where addresses are used to distinguish between one connected device and another. 892 void findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/, 893 const String8 address /*in*/, 894 SortedVector<audio_io_handle_t>& outputs /*out*/); 895 uint32_t nextUniqueId(); 896 uint32_t nextAudioPortGeneration(); 897 uint32_t curAudioPortGeneration() const { return mAudioPortGeneration; } 898 // internal method to return the output handle for the given device and format 899 audio_io_handle_t getOutputForDevice( 900 audio_devices_t device, 901 audio_session_t session, 902 audio_stream_type_t stream, 903 uint32_t samplingRate, 904 audio_format_t format, 905 audio_channel_mask_t channelMask, 906 audio_output_flags_t flags, 907 const audio_offload_info_t *offloadInfo); 908 // internal function to derive a stream type value from audio attributes 909 audio_stream_type_t streamTypefromAttributesInt(const audio_attributes_t *attr); 910 // return true if any output is playing anything besides the stream to ignore 911 bool isAnyOutputActive(audio_stream_type_t streamToIgnore); 912 // event is one of STARTING_OUTPUT, STARTING_BEACON, STOPPING_OUTPUT, STOPPING_BEACON 913 // returns 0 if no mute/unmute event happened, the largest latency of the device where 914 // the mute/unmute happened 915 uint32_t handleEventForBeacon(int event); 916 uint32_t setBeaconMute(bool mute); 917 bool isValidAttributes(const audio_attributes_t *paa); 918}; 919 920}; 921