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 <atomic> 20 #include <functional> 21 #include <memory> 22 #include <unordered_set> 23 24 #include <stdint.h> 25 #include <sys/types.h> 26 #include <cutils/config_utils.h> 27 #include <cutils/misc.h> 28 #include <utils/Timers.h> 29 #include <utils/Errors.h> 30 #include <utils/KeyedVector.h> 31 #include <utils/SortedVector.h> 32 #include <media/AudioParameter.h> 33 #include <media/AudioPolicy.h> 34 #include <media/AudioProfile.h> 35 #include <media/PatchBuilder.h> 36 #include "AudioPolicyInterface.h" 37 38 #include <AudioPolicyManagerObserver.h> 39 #include <AudioPolicyConfig.h> 40 #include <PolicyAudioPort.h> 41 #include <AudioPatch.h> 42 #include <DeviceDescriptor.h> 43 #include <IOProfile.h> 44 #include <HwModule.h> 45 #include <AudioInputDescriptor.h> 46 #include <AudioOutputDescriptor.h> 47 #include <AudioPolicyMix.h> 48 #include <EffectDescriptor.h> 49 #include <SoundTriggerSession.h> 50 #include "EngineLibrary.h" 51 #include "TypeConverter.h" 52 53 namespace android { 54 55 // ---------------------------------------------------------------------------- 56 57 // Attenuation applied to STRATEGY_SONIFICATION streams when a headset is connected: 6dB 58 #define SONIFICATION_HEADSET_VOLUME_FACTOR_DB (-6) 59 // Min volume for STRATEGY_SONIFICATION streams when limited by music volume: -36dB 60 #define SONIFICATION_HEADSET_VOLUME_MIN_DB (-36) 61 // Max volume difference on A2DP between playing media and STRATEGY_SONIFICATION streams: 12dB 62 #define SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB (12) 63 64 // Time in milliseconds during which we consider that music is still active after a music 65 // track was stopped - see computeVolume() 66 #define SONIFICATION_HEADSET_MUSIC_DELAY 5000 67 68 // Time in milliseconds during witch some streams are muted while the audio path 69 // is switched 70 #define MUTE_TIME_MS 2000 71 72 // multiplication factor applied to output latency when calculating a safe mute delay when 73 // invalidating tracks 74 #define LATENCY_MUTE_FACTOR 4 75 76 #define NUM_TEST_OUTPUTS 5 77 78 #define NUM_VOL_CURVE_KNEES 2 79 80 // Default minimum length allowed for offloading a compressed track 81 // Can be overridden by the audio.offload.min.duration.secs property 82 #define OFFLOAD_DEFAULT_MIN_DURATION_SECS 60 83 84 // ---------------------------------------------------------------------------- 85 // AudioPolicyManager implements audio policy manager behavior common to all platforms. 86 // ---------------------------------------------------------------------------- 87 88 class AudioPolicyManager : public AudioPolicyInterface, public AudioPolicyManagerObserver 89 { 90 91 public: 92 explicit AudioPolicyManager(AudioPolicyClientInterface *clientInterface); 93 virtual ~AudioPolicyManager(); 94 95 // AudioPolicyInterface 96 virtual status_t setDeviceConnectionState(audio_devices_t device, 97 audio_policy_dev_state_t state, 98 const char *device_address, 99 const char *device_name, 100 audio_format_t encodedFormat); 101 virtual audio_policy_dev_state_t getDeviceConnectionState(audio_devices_t device, 102 const char *device_address); 103 virtual status_t handleDeviceConfigChange(audio_devices_t device, 104 const char *device_address, 105 const char *device_name, 106 audio_format_t encodedFormat); 107 virtual void setPhoneState(audio_mode_t state); 108 virtual void setForceUse(audio_policy_force_use_t usage, 109 audio_policy_forced_cfg_t config); 110 virtual audio_policy_forced_cfg_t getForceUse(audio_policy_force_use_t usage); 111 112 virtual void setSystemProperty(const char* property, const char* value); 113 virtual status_t initCheck(); 114 virtual audio_io_handle_t getOutput(audio_stream_type_t stream); 115 status_t getOutputForAttr(const audio_attributes_t *attr, 116 audio_io_handle_t *output, 117 audio_session_t session, 118 audio_stream_type_t *stream, 119 uid_t uid, 120 const audio_config_t *config, 121 audio_output_flags_t *flags, 122 audio_port_handle_t *selectedDeviceId, 123 audio_port_handle_t *portId, 124 std::vector<audio_io_handle_t> *secondaryOutputs) override; 125 virtual status_t startOutput(audio_port_handle_t portId); 126 virtual status_t stopOutput(audio_port_handle_t portId); 127 virtual void releaseOutput(audio_port_handle_t portId); 128 virtual status_t getInputForAttr(const audio_attributes_t *attr, 129 audio_io_handle_t *input, 130 audio_unique_id_t riid, 131 audio_session_t session, 132 uid_t uid, 133 const audio_config_base_t *config, 134 audio_input_flags_t flags, 135 audio_port_handle_t *selectedDeviceId, 136 input_type_t *inputType, 137 audio_port_handle_t *portId); 138 139 // indicates to the audio policy manager that the input starts being used. 140 virtual status_t startInput(audio_port_handle_t portId); 141 142 // indicates to the audio policy manager that the input stops being used. 143 virtual status_t stopInput(audio_port_handle_t portId); 144 virtual void releaseInput(audio_port_handle_t portId); 145 virtual void checkCloseInputs(); 146 /** 147 * @brief initStreamVolume: even if the engine volume files provides min and max, keep this 148 * api for compatibility reason. 149 * AudioServer will get the min and max and may overwrite them if: 150 * -using property (highest priority) 151 * -not defined (-1 by convention), case when still using apm volume tables XML files 152 * @param stream to be considered 153 * @param indexMin to set 154 * @param indexMax to set 155 */ 156 virtual void initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax); 157 virtual status_t setStreamVolumeIndex(audio_stream_type_t stream, 158 int index, 159 audio_devices_t device); 160 virtual status_t getStreamVolumeIndex(audio_stream_type_t stream, 161 int *index, 162 audio_devices_t device); 163 164 virtual status_t setVolumeIndexForAttributes(const audio_attributes_t &attr, 165 int index, 166 audio_devices_t device); 167 virtual status_t getVolumeIndexForAttributes(const audio_attributes_t &attr, 168 int &index, 169 audio_devices_t device); 170 virtual status_t getMaxVolumeIndexForAttributes(const audio_attributes_t &attr, int &index); 171 172 virtual status_t getMinVolumeIndexForAttributes(const audio_attributes_t &attr, int &index); 173 174 status_t setVolumeCurveIndex(int index, 175 audio_devices_t device, 176 IVolumeCurves &volumeCurves); 177 178 status_t getVolumeIndex(const IVolumeCurves &curves, int &index, 179 const DeviceTypeSet& deviceTypes) const; 180 181 // return the strategy corresponding to a given stream type getStrategyForStream(audio_stream_type_t stream)182 virtual uint32_t getStrategyForStream(audio_stream_type_t stream) 183 { 184 return streamToStrategy(stream); 185 } streamToStrategy(audio_stream_type_t stream)186 product_strategy_t streamToStrategy(audio_stream_type_t stream) const 187 { 188 auto attributes = mEngine->getAttributesForStreamType(stream); 189 return mEngine->getProductStrategyForAttributes(attributes); 190 } 191 192 // return the enabled output devices for the given stream type 193 virtual audio_devices_t getDevicesForStream(audio_stream_type_t stream); 194 195 virtual audio_io_handle_t getOutputForEffect(const effect_descriptor_t *desc = NULL); 196 virtual status_t registerEffect(const effect_descriptor_t *desc, 197 audio_io_handle_t io, 198 uint32_t strategy, 199 int session, 200 int id); 201 virtual status_t unregisterEffect(int id); 202 virtual status_t setEffectEnabled(int id, bool enabled); 203 status_t moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io) override; 204 205 virtual bool isStreamActive(audio_stream_type_t stream, uint32_t inPastMs = 0) const; 206 // return whether a stream is playing remotely, override to change the definition of 207 // local/remote playback, used for instance by notification manager to not make 208 // media players lose audio focus when not playing locally 209 // For the base implementation, "remotely" means playing during screen mirroring which 210 // uses an output for playback with a non-empty, non "0" address. 211 virtual bool isStreamActiveRemotely(audio_stream_type_t stream, 212 uint32_t inPastMs = 0) const; 213 214 virtual bool isSourceActive(audio_source_t source) const; 215 216 // helpers for dump(int fd) 217 void dumpManualSurroundFormats(String8 *dst) const; 218 void dump(String8 *dst) const; 219 220 status_t dump(int fd) override; 221 222 status_t setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy) override; 223 virtual bool isOffloadSupported(const audio_offload_info_t& offloadInfo); 224 225 virtual bool isDirectOutputSupported(const audio_config_base_t& config, 226 const audio_attributes_t& attributes); 227 228 virtual status_t listAudioPorts(audio_port_role_t role, 229 audio_port_type_t type, 230 unsigned int *num_ports, 231 struct audio_port *ports, 232 unsigned int *generation); 233 virtual status_t getAudioPort(struct audio_port *port); createAudioPatch(const struct audio_patch * patch,audio_patch_handle_t * handle,uid_t uid)234 virtual status_t createAudioPatch(const struct audio_patch *patch, 235 audio_patch_handle_t *handle, 236 uid_t uid) { 237 return createAudioPatchInternal(patch, handle, uid); 238 } 239 240 virtual status_t releaseAudioPatch(audio_patch_handle_t handle, 241 uid_t uid); 242 virtual status_t listAudioPatches(unsigned int *num_patches, 243 struct audio_patch *patches, 244 unsigned int *generation); 245 virtual status_t setAudioPortConfig(const struct audio_port_config *config); 246 247 virtual void releaseResourcesForUid(uid_t uid); 248 249 virtual status_t acquireSoundTriggerSession(audio_session_t *session, 250 audio_io_handle_t *ioHandle, 251 audio_devices_t *device); 252 releaseSoundTriggerSession(audio_session_t session)253 virtual status_t releaseSoundTriggerSession(audio_session_t session) 254 { 255 return mSoundTriggerSessions.releaseSession(session); 256 } 257 258 virtual status_t registerPolicyMixes(const Vector<AudioMix>& mixes); 259 virtual status_t unregisterPolicyMixes(Vector<AudioMix> mixes); 260 virtual status_t setUidDeviceAffinities(uid_t uid, 261 const Vector<AudioDeviceTypeAddr>& devices); 262 virtual status_t removeUidDeviceAffinities(uid_t uid); 263 264 virtual status_t setPreferredDeviceForStrategy(product_strategy_t strategy, 265 const AudioDeviceTypeAddr &device); 266 virtual status_t removePreferredDeviceForStrategy(product_strategy_t strategy); 267 virtual status_t getPreferredDeviceForStrategy(product_strategy_t strategy, 268 AudioDeviceTypeAddr &device); 269 270 virtual status_t startAudioSource(const struct audio_port_config *source, 271 const audio_attributes_t *attributes, 272 audio_port_handle_t *portId, 273 uid_t uid); 274 virtual status_t stopAudioSource(audio_port_handle_t portId); 275 276 virtual status_t setMasterMono(bool mono); 277 virtual status_t getMasterMono(bool *mono); 278 virtual float getStreamVolumeDB( 279 audio_stream_type_t stream, int index, audio_devices_t device); 280 281 virtual status_t getSurroundFormats(unsigned int *numSurroundFormats, 282 audio_format_t *surroundFormats, 283 bool *surroundFormatsEnabled, 284 bool reported); 285 virtual status_t setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled); 286 287 virtual status_t getHwOffloadEncodingFormatsSupportedForA2DP( 288 std::vector<audio_format_t> *formats); 289 290 virtual void setAppState(uid_t uid, app_state_t state); 291 292 virtual bool isHapticPlaybackSupported(); 293 listAudioProductStrategies(AudioProductStrategyVector & strategies)294 virtual status_t listAudioProductStrategies(AudioProductStrategyVector &strategies) 295 { 296 return mEngine->listAudioProductStrategies(strategies); 297 } 298 getProductStrategyFromAudioAttributes(const AudioAttributes & aa,product_strategy_t & productStrategy)299 virtual status_t getProductStrategyFromAudioAttributes(const AudioAttributes &aa, 300 product_strategy_t &productStrategy) 301 { 302 productStrategy = mEngine->getProductStrategyForAttributes(aa.getAttributes()); 303 return productStrategy != PRODUCT_STRATEGY_NONE ? NO_ERROR : BAD_VALUE; 304 } 305 listAudioVolumeGroups(AudioVolumeGroupVector & groups)306 virtual status_t listAudioVolumeGroups(AudioVolumeGroupVector &groups) 307 { 308 return mEngine->listAudioVolumeGroups(groups); 309 } 310 getVolumeGroupFromAudioAttributes(const AudioAttributes & aa,volume_group_t & volumeGroup)311 virtual status_t getVolumeGroupFromAudioAttributes(const AudioAttributes &aa, 312 volume_group_t &volumeGroup) 313 { 314 volumeGroup = mEngine->getVolumeGroupForAttributes(aa.getAttributes()); 315 return volumeGroup != VOLUME_GROUP_NONE ? NO_ERROR : BAD_VALUE; 316 } 317 318 void onNewAudioModulesAvailable() override; 319 320 status_t initialize(); 321 322 protected: 323 // A constructor that allows more fine-grained control over initialization process, 324 // used in automatic tests. 325 AudioPolicyManager(AudioPolicyClientInterface *clientInterface, bool forTesting); 326 327 // These methods should be used when finer control over APM initialization 328 // is needed, e.g. in tests. Must be used in conjunction with the constructor 329 // that only performs fields initialization. The public constructor comprises 330 // these steps in the following sequence: 331 // - field initializing constructor; 332 // - loadConfig; 333 // - initialize. getConfig()334 AudioPolicyConfig& getConfig() { return mConfig; } 335 void loadConfig(); 336 337 // From AudioPolicyManagerObserver getAudioPatches()338 virtual const AudioPatchCollection &getAudioPatches() const 339 { 340 return mAudioPatches; 341 } getSoundTriggerSessionCollection()342 virtual const SoundTriggerSessionCollection &getSoundTriggerSessionCollection() const 343 { 344 return mSoundTriggerSessions; 345 } getAudioPolicyMixCollection()346 virtual const AudioPolicyMixCollection &getAudioPolicyMixCollection() const 347 { 348 return mPolicyMixes; 349 } getOutputs()350 virtual const SwAudioOutputCollection &getOutputs() const 351 { 352 return mOutputs; 353 } getInputs()354 virtual const AudioInputCollection &getInputs() const 355 { 356 return mInputs; 357 } getAvailableOutputDevices()358 virtual const DeviceVector getAvailableOutputDevices() const 359 { 360 return mAvailableOutputDevices.filterForEngine(); 361 } getAvailableInputDevices()362 virtual const DeviceVector getAvailableInputDevices() const 363 { 364 // legacy and non-legacy remote-submix are managed by the engine, do not filter 365 return mAvailableInputDevices; 366 } getDefaultOutputDevice()367 virtual const sp<DeviceDescriptor> &getDefaultOutputDevice() const 368 { 369 return mDefaultOutputDevice; 370 } 371 getVolumeGroups()372 std::vector<volume_group_t> getVolumeGroups() const 373 { 374 return mEngine->getVolumeGroups(); 375 } 376 toVolumeSource(volume_group_t volumeGroup)377 VolumeSource toVolumeSource(volume_group_t volumeGroup) const 378 { 379 return static_cast<VolumeSource>(volumeGroup); 380 } toVolumeSource(const audio_attributes_t & attributes)381 VolumeSource toVolumeSource(const audio_attributes_t &attributes) const 382 { 383 return toVolumeSource(mEngine->getVolumeGroupForAttributes(attributes)); 384 } toVolumeSource(audio_stream_type_t stream)385 VolumeSource toVolumeSource(audio_stream_type_t stream) const 386 { 387 return toVolumeSource(mEngine->getVolumeGroupForStreamType(stream)); 388 } getVolumeCurves(VolumeSource volumeSource)389 IVolumeCurves &getVolumeCurves(VolumeSource volumeSource) 390 { 391 auto *curves = mEngine->getVolumeCurvesForVolumeGroup( 392 static_cast<volume_group_t>(volumeSource)); 393 ALOG_ASSERT(curves != nullptr, "No curves for volume source %d", volumeSource); 394 return *curves; 395 } getVolumeCurves(const audio_attributes_t & attr)396 IVolumeCurves &getVolumeCurves(const audio_attributes_t &attr) 397 { 398 auto *curves = mEngine->getVolumeCurvesForAttributes(attr); 399 ALOG_ASSERT(curves != nullptr, "No curves for attributes %s", toString(attr).c_str()); 400 return *curves; 401 } getVolumeCurves(audio_stream_type_t stream)402 IVolumeCurves &getVolumeCurves(audio_stream_type_t stream) 403 { 404 auto *curves = mEngine->getVolumeCurvesForStreamType(stream); 405 ALOG_ASSERT(curves != nullptr, "No curves for stream %s", toString(stream).c_str()); 406 return *curves; 407 } 408 409 void addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc); 410 void removeOutput(audio_io_handle_t output); 411 void addInput(audio_io_handle_t input, const sp<AudioInputDescriptor>& inputDesc); 412 413 // change the route of the specified output. Returns the number of ms we have slept to 414 // allow new routing to take effect in certain cases. 415 uint32_t setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc, 416 const DeviceVector &device, 417 bool force = false, 418 int delayMs = 0, 419 audio_patch_handle_t *patchHandle = NULL, 420 bool requiresMuteCheck = true); 421 status_t resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc, 422 int delayMs = 0, 423 audio_patch_handle_t *patchHandle = NULL); 424 status_t setInputDevice(audio_io_handle_t input, 425 const sp<DeviceDescriptor> &device, 426 bool force = false, 427 audio_patch_handle_t *patchHandle = NULL); 428 status_t resetInputDevice(audio_io_handle_t input, 429 audio_patch_handle_t *patchHandle = NULL); 430 431 // compute the actual volume for a given stream according to the requested index and a particular 432 // device 433 virtual float computeVolume(IVolumeCurves &curves, 434 VolumeSource volumeSource, 435 int index, 436 const DeviceTypeSet& deviceTypes); 437 438 // rescale volume index from srcStream within range of dstStream 439 int rescaleVolumeIndex(int srcIndex, 440 VolumeSource fromVolumeSource, 441 VolumeSource toVolumeSource); 442 // check that volume change is permitted, compute and send new volume to audio hardware 443 virtual status_t checkAndSetVolume(IVolumeCurves &curves, 444 VolumeSource volumeSource, int index, 445 const sp<AudioOutputDescriptor>& outputDesc, 446 DeviceTypeSet deviceTypes, 447 int delayMs = 0, bool force = false); 448 449 // apply all stream volumes to the specified output and device 450 void applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc, 451 const DeviceTypeSet& deviceTypes, 452 int delayMs = 0, bool force = false); 453 454 /** 455 * @brief setStrategyMute Mute or unmute all active clients on the considered output 456 * following the given strategy. 457 * @param strategy to be considered 458 * @param on true for mute, false for unmute 459 * @param outputDesc to be considered 460 * @param delayMs 461 * @param device 462 */ 463 void setStrategyMute(product_strategy_t strategy, 464 bool on, 465 const sp<AudioOutputDescriptor>& outputDesc, 466 int delayMs = 0, 467 DeviceTypeSet deviceTypes = DeviceTypeSet()); 468 469 /** 470 * @brief setVolumeSourceMute Mute or unmute the volume source on the specified output 471 * @param volumeSource to be muted/unmute (may host legacy streams or by extension set of 472 * audio attributes) 473 * @param on true to mute, false to umute 474 * @param outputDesc on which the client following the volume group shall be muted/umuted 475 * @param delayMs 476 * @param device 477 */ 478 void setVolumeSourceMute(VolumeSource volumeSource, 479 bool on, 480 const sp<AudioOutputDescriptor>& outputDesc, 481 int delayMs = 0, 482 DeviceTypeSet deviceTypes = DeviceTypeSet()); 483 484 audio_mode_t getPhoneState(); 485 486 // true if device is in a telephony or VoIP call 487 virtual bool isInCall(); 488 // true if given state represents a device in a telephony or VoIP call 489 virtual bool isStateInCall(int state); 490 491 // when a device is connected, checks if an open output can be routed 492 // to this device. If none is open, tries to open one of the available outputs. 493 // Returns an output suitable to this device or 0. 494 // when a device is disconnected, checks if an output is not used any more and 495 // returns its handle if any. 496 // transfers the audio tracks and effects from one output thread to another accordingly. 497 status_t checkOutputsForDevice(const sp<DeviceDescriptor>& device, 498 audio_policy_dev_state_t state, 499 SortedVector<audio_io_handle_t>& outputs); 500 501 status_t checkInputsForDevice(const sp<DeviceDescriptor>& device, 502 audio_policy_dev_state_t state); 503 504 // close an output and its companion duplicating output. 505 void closeOutput(audio_io_handle_t output); 506 507 // close an input. 508 void closeInput(audio_io_handle_t input); 509 510 // runs all the checks required for accommodating changes in devices and outputs 511 // if 'onOutputsChecked' callback is provided, it is executed after the outputs 512 // check via 'checkOutputForAllStrategies'. If the callback returns 'true', 513 // A2DP suspend status is rechecked. 514 void checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked = nullptr); 515 516 /** 517 * @brief updates routing for all outputs (including call if call in progress). 518 * @param delayMs delay for unmuting if required 519 */ 520 void updateCallAndOutputRouting(bool forceVolumeReeval = true, uint32_t delayMs = 0); 521 522 /** 523 * @brief checkOutputForAttributes checks and if necessary changes outputs used for the 524 * given audio attributes. 525 * must be called every time a condition that affects the output choice for a given 526 * attributes changes: connected device, phone state, force use... 527 * Must be called before updateDevicesAndOutputs() 528 * @param attr to be considered 529 */ 530 void checkOutputForAttributes(const audio_attributes_t &attr); 531 532 bool followsSameRouting(const audio_attributes_t &lAttr, 533 const audio_attributes_t &rAttr) const; 534 535 /** 536 * @brief checkOutputForAllStrategies Same as @see checkOutputForAttributes() 537 * but for a all product strategies in order of priority 538 */ 539 void checkOutputForAllStrategies(); 540 541 // Same as checkOutputForStrategy but for secondary outputs. Make sure if a secondary 542 // output condition changes, the track is properly rerouted 543 void checkSecondaryOutputs(); 544 545 // manages A2DP output suspend/restore according to phone state and BT SCO usage 546 void checkA2dpSuspend(); 547 548 // selects the most appropriate device on output for current state 549 // must be called every time a condition that affects the device choice for a given output is 550 // changed: connected device, phone state, force use, output start, output stop.. 551 // see getDeviceForStrategy() for the use of fromCache parameter 552 DeviceVector getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc, 553 bool fromCache); 554 555 /** 556 * @brief updateDevicesAndOutputs: updates cache of devices of the engine 557 * must be called every time a condition that affects the device choice is changed: 558 * connected device, phone state, force use... 559 * cached values are used by getOutputDevicesForStream()/getDevicesForAttributes if 560 * parameter fromCache is true. 561 * Must be called after checkOutputForAllStrategies() 562 */ 563 void updateDevicesAndOutputs(); 564 565 // selects the most appropriate device on input for current state 566 sp<DeviceDescriptor> getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc); 567 getMaxEffectsCpuLoad()568 virtual uint32_t getMaxEffectsCpuLoad() 569 { 570 return mEffects.getMaxEffectsCpuLoad(); 571 } 572 getMaxEffectsMemory()573 virtual uint32_t getMaxEffectsMemory() 574 { 575 return mEffects.getMaxEffectsMemory(); 576 } 577 578 SortedVector<audio_io_handle_t> getOutputsForDevices( 579 const DeviceVector &devices, const SwAudioOutputCollection& openOutputs); 580 581 /** 582 * @brief checkDeviceMuteStrategies mute/unmute strategies 583 * using an incompatible device combination. 584 * if muting, wait for the audio in pcm buffer to be drained before proceeding 585 * if unmuting, unmute only after the specified delay 586 * @param outputDesc 587 * @param prevDevice 588 * @param delayMs 589 * @return the number of ms waited 590 */ 591 virtual uint32_t checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc, 592 const DeviceVector &prevDevices, 593 uint32_t delayMs); 594 595 audio_io_handle_t selectOutput(const SortedVector<audio_io_handle_t>& outputs, 596 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE, 597 audio_format_t format = AUDIO_FORMAT_INVALID, 598 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE, 599 uint32_t samplingRate = 0); 600 // samplingRate, format, channelMask are in/out and so may be modified 601 sp<IOProfile> getInputProfile(const sp<DeviceDescriptor> & device, 602 uint32_t& samplingRate, 603 audio_format_t& format, 604 audio_channel_mask_t& channelMask, 605 audio_input_flags_t flags); 606 /** 607 * @brief getProfileForOutput 608 * @param devices vector of descriptors, may be empty if ignoring the device is required 609 * @param samplingRate 610 * @param format 611 * @param channelMask 612 * @param flags 613 * @param directOnly 614 * @return IOProfile to be used if found, nullptr otherwise 615 */ 616 sp<IOProfile> getProfileForOutput(const DeviceVector &devices, 617 uint32_t samplingRate, 618 audio_format_t format, 619 audio_channel_mask_t channelMask, 620 audio_output_flags_t flags, 621 bool directOnly); 622 623 audio_io_handle_t selectOutputForMusicEffects(); 624 addAudioPatch(audio_patch_handle_t handle,const sp<AudioPatch> & patch)625 virtual status_t addAudioPatch(audio_patch_handle_t handle, const sp<AudioPatch>& patch) 626 { 627 return mAudioPatches.addAudioPatch(handle, patch); 628 } removeAudioPatch(audio_patch_handle_t handle)629 virtual status_t removeAudioPatch(audio_patch_handle_t handle) 630 { 631 return mAudioPatches.removeAudioPatch(handle); 632 } 633 isPrimaryModule(const sp<HwModule> & module)634 bool isPrimaryModule(const sp<HwModule> &module) const 635 { 636 if (module == 0 || !hasPrimaryOutput()) { 637 return false; 638 } 639 return module->getHandle() == mPrimaryOutput->getModuleHandle(); 640 } availablePrimaryOutputDevices()641 DeviceVector availablePrimaryOutputDevices() const 642 { 643 if (!hasPrimaryOutput()) { 644 return DeviceVector(); 645 } 646 return mAvailableOutputDevices.filter(mPrimaryOutput->supportedDevices()); 647 } availablePrimaryModuleInputDevices()648 DeviceVector availablePrimaryModuleInputDevices() const 649 { 650 if (!hasPrimaryOutput()) { 651 return DeviceVector(); 652 } 653 return mAvailableInputDevices.getDevicesFromHwModule( 654 mPrimaryOutput->getModuleHandle()); 655 } 656 /** 657 * @brief getFirstDeviceId of the Device Vector 658 * @return if the collection is not empty, it returns the first device Id, 659 * otherwise AUDIO_PORT_HANDLE_NONE 660 */ getFirstDeviceId(const DeviceVector & devices)661 audio_port_handle_t getFirstDeviceId(const DeviceVector &devices) const 662 { 663 return (devices.size() > 0) ? devices.itemAt(0)->getId() : AUDIO_PORT_HANDLE_NONE; 664 } getFirstDeviceAddress(const DeviceVector & devices)665 String8 getFirstDeviceAddress(const DeviceVector &devices) const 666 { 667 return (devices.size() > 0) ? 668 String8(devices.itemAt(0)->address().c_str()) : String8(""); 669 } 670 671 uint32_t updateCallRouting(const DeviceVector &rxDevices, uint32_t delayMs = 0); 672 sp<AudioPatch> createTelephonyPatch(bool isRx, const sp<DeviceDescriptor> &device, 673 uint32_t delayMs); 674 bool isDeviceOfModule(const sp<DeviceDescriptor>& devDesc, const char *moduleId) const; 675 676 status_t startSource(const sp<SwAudioOutputDescriptor>& outputDesc, 677 const sp<TrackClientDescriptor>& client, 678 uint32_t *delayMs); 679 status_t stopSource(const sp<SwAudioOutputDescriptor>& outputDesc, 680 const sp<TrackClientDescriptor>& client); 681 682 void clearAudioPatches(uid_t uid); 683 void clearSessionRoutes(uid_t uid); 684 685 /** 686 * @brief checkStrategyRoute: when an output is beeing rerouted, reconsider each output 687 * that may host a strategy playing on the considered output. 688 * @param ps product strategy that initiated the rerouting 689 * @param ouptutToSkip output that initiated the rerouting 690 */ 691 void checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip); 692 hasPrimaryOutput()693 status_t hasPrimaryOutput() const { return mPrimaryOutput != 0; } 694 695 status_t connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc); 696 status_t disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc); 697 698 sp<SourceClientDescriptor> getSourceForAttributesOnOutput(audio_io_handle_t output, 699 const audio_attributes_t &attr); 700 701 void cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc); 702 703 void clearAudioSources(uid_t uid); 704 705 static bool streamsMatchForvolume(audio_stream_type_t stream1, 706 audio_stream_type_t stream2); 707 708 void closeActiveClients(const sp<AudioInputDescriptor>& input); 709 void closeClient(audio_port_handle_t portId); 710 711 const uid_t mUidCached; // AID_AUDIOSERVER 712 AudioPolicyClientInterface *mpClientInterface; // audio policy client interface 713 sp<SwAudioOutputDescriptor> mPrimaryOutput; // primary output descriptor 714 // list of descriptors for outputs currently opened 715 716 SwAudioOutputCollection mOutputs; 717 // copy of mOutputs before setDeviceConnectionState() opens new outputs 718 // reset to mOutputs when updateDevicesAndOutputs() is called. 719 SwAudioOutputCollection mPreviousOutputs; 720 AudioInputCollection mInputs; // list of input descriptors 721 722 DeviceVector mOutputDevicesAll; // all output devices from the config 723 DeviceVector mInputDevicesAll; // all input devices from the config 724 DeviceVector mAvailableOutputDevices; // all available output devices 725 DeviceVector mAvailableInputDevices; // all available input devices 726 727 bool mLimitRingtoneVolume; // limit ringtone volume to music volume if headset connected 728 729 float mLastVoiceVolume; // last voice volume value sent to audio HAL 730 bool mA2dpSuspended; // true if A2DP output is suspended 731 732 EffectDescriptorCollection mEffects; // list of registered audio effects 733 sp<DeviceDescriptor> mDefaultOutputDevice; // output device selected by default at boot time 734 HwModuleCollection mHwModules; // contains modules that have been loaded successfully 735 HwModuleCollection mHwModulesAll; // contains all modules declared in the config 736 737 AudioPolicyConfig mConfig; 738 739 std::atomic<uint32_t> mAudioPortGeneration; 740 741 AudioPatchCollection mAudioPatches; 742 743 SoundTriggerSessionCollection mSoundTriggerSessions; 744 745 sp<AudioPatch> mCallTxPatch; 746 sp<AudioPatch> mCallRxPatch; 747 748 HwAudioOutputCollection mHwOutputs; 749 SourceClientCollection mAudioSources; 750 751 // for supporting "beacon" streams, i.e. streams that only play on speaker, and never 752 // when something other than STREAM_TTS (a.k.a. "Transmitted Through Speaker") is playing 753 enum { 754 STARTING_OUTPUT, 755 STARTING_BEACON, 756 STOPPING_OUTPUT, 757 STOPPING_BEACON 758 }; 759 uint32_t mBeaconMuteRefCount; // ref count for stream that would mute beacon 760 uint32_t mBeaconPlayingRefCount;// ref count for the playing beacon streams 761 bool mBeaconMuted; // has STREAM_TTS been muted 762 bool mTtsOutputAvailable; // true if a dedicated output for TTS stream is available 763 764 bool mMasterMono; // true if we wish to force all outputs to mono 765 AudioPolicyMixCollection mPolicyMixes; // list of registered mixes 766 audio_io_handle_t mMusicEffectOutput; // output selected for music effects 767 768 uint32_t nextAudioPortGeneration(); 769 770 // Audio Policy Engine Interface. 771 EngineInstance mEngine; 772 773 // Surround formats that are enabled manually. Taken into account when 774 // "encoded surround" is forced into "manual" mode. 775 std::unordered_set<audio_format_t> mManualSurroundFormats; 776 777 std::unordered_map<uid_t, audio_flags_mask_t> mAllowedCapturePolicies; 778 private: 779 void onNewAudioModulesAvailableInt(DeviceVector *newDevices); 780 781 // Add or remove AC3 DTS encodings based on user preferences. 782 void modifySurroundFormats(const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr); 783 void modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr); 784 785 // Support for Multi-Stream Decoder (MSD) module 786 sp<DeviceDescriptor> getMsdAudioInDevice() const; 787 DeviceVector getMsdAudioOutDevices() const; 788 const AudioPatchCollection getMsdPatches() const; 789 status_t getBestMsdAudioProfileFor(const sp<DeviceDescriptor> &outputDevice, 790 bool hwAvSync, 791 audio_port_config *sourceConfig, 792 audio_port_config *sinkConfig) const; 793 PatchBuilder buildMsdPatch(const sp<DeviceDescriptor> &outputDevice) const; 794 status_t setMsdPatch(const sp<DeviceDescriptor> &outputDevice = nullptr); 795 796 // If any, resolve any "dynamic" fields of an Audio Profiles collection 797 void updateAudioProfiles(const sp<DeviceDescriptor>& devDesc, audio_io_handle_t ioHandle, 798 AudioProfileVector &profiles); 799 800 // Notify the policy client of any change of device state with AUDIO_IO_HANDLE_NONE, 801 // so that the client interprets it as global to audio hardware interfaces. 802 // It can give a chance to HAL implementer to retrieve dynamic capabilities associated 803 // to this device for example. 804 // TODO avoid opening stream to retrieve capabilities of a profile. 805 void broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device, 806 audio_policy_dev_state_t state); 807 808 // updates device caching and output for streams that can influence the 809 // routing of notifications 810 void handleNotificationRoutingForStream(audio_stream_type_t stream); curAudioPortGeneration()811 uint32_t curAudioPortGeneration() const { return mAudioPortGeneration; } 812 // internal method, get audio_attributes_t from either a source audio_attributes_t 813 // or audio_stream_type_t, respectively. 814 status_t getAudioAttributes(audio_attributes_t *dstAttr, 815 const audio_attributes_t *srcAttr, 816 audio_stream_type_t srcStream); 817 // internal method, called by getOutputForAttr() and connectAudioSource. 818 status_t getOutputForAttrInt(audio_attributes_t *resultAttr, 819 audio_io_handle_t *output, 820 audio_session_t session, 821 const audio_attributes_t *attr, 822 audio_stream_type_t *stream, 823 uid_t uid, 824 const audio_config_t *config, 825 audio_output_flags_t *flags, 826 audio_port_handle_t *selectedDeviceId, 827 bool *isRequestedDeviceForExclusiveUse, 828 std::vector<sp<SwAudioOutputDescriptor>> *secondaryDescs); 829 // internal method to return the output handle for the given device and format 830 audio_io_handle_t getOutputForDevices( 831 const DeviceVector &devices, 832 audio_session_t session, 833 audio_stream_type_t stream, 834 const audio_config_t *config, 835 audio_output_flags_t *flags, 836 bool forceMutingHaptic = false); 837 838 /** 839 * @brief getInputForDevice selects an input handle for a given input device and 840 * requester context 841 * @param device to be used by requester, selected by policy mix rules or engine 842 * @param session requester session id 843 * @param uid requester uid 844 * @param attributes requester audio attributes (e.g. input source and tags matter) 845 * @param config requester audio configuration (e.g. sample rate, format, channel mask). 846 * @param flags requester input flags 847 * @param policyMix may be null, policy rules to be followed by the requester 848 * @return input io handle aka unique input identifier selected for this device. 849 */ 850 audio_io_handle_t getInputForDevice(const sp<DeviceDescriptor> &device, 851 audio_session_t session, 852 const audio_attributes_t &attributes, 853 const audio_config_base_t *config, 854 audio_input_flags_t flags, 855 const sp<AudioPolicyMix> &policyMix); 856 857 // event is one of STARTING_OUTPUT, STARTING_BEACON, STOPPING_OUTPUT, STOPPING_BEACON 858 // returns 0 if no mute/unmute event happened, the largest latency of the device where 859 // the mute/unmute happened 860 uint32_t handleEventForBeacon(int event); 861 uint32_t setBeaconMute(bool mute); 862 bool isValidAttributes(const audio_attributes_t *paa); 863 864 // Called by setDeviceConnectionState(). 865 status_t setDeviceConnectionStateInt(audio_devices_t deviceType, 866 audio_policy_dev_state_t state, 867 const char *device_address, 868 const char *device_name, 869 audio_format_t encodedFormat); 870 status_t setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device, 871 audio_policy_dev_state_t state); 872 873 void setEngineDeviceConnectionState(const sp<DeviceDescriptor> device, 874 audio_policy_dev_state_t state); 875 updateMono(audio_io_handle_t output)876 void updateMono(audio_io_handle_t output) { 877 AudioParameter param; 878 param.addInt(String8(AudioParameter::keyMonoOutput), (int)mMasterMono); 879 mpClientInterface->setParameters(output, param.toString()); 880 } 881 882 /** 883 * @brief createAudioPatchInternal internal function to manage audio patch creation 884 * @param[in] patch structure containing sink and source ports configuration 885 * @param[out] handle patch handle to be provided if patch installed correctly 886 * @param[in] uid of the client 887 * @param[in] delayMs if required 888 * @param[in] sourceDesc [optional] in case of external source, source client to be 889 * configured by the patch, i.e. assigning an Output (HW or SW) 890 * @return NO_ERROR if patch installed correclty, error code otherwise. 891 */ 892 status_t createAudioPatchInternal(const struct audio_patch *patch, 893 audio_patch_handle_t *handle, 894 uid_t uid, uint32_t delayMs = 0, 895 const sp<SourceClientDescriptor>& sourceDesc = nullptr); 896 /** 897 * @brief releaseAudioPatchInternal internal function to remove an audio patch 898 * @param[in] handle of the patch to be removed 899 * @param[in] delayMs if required 900 * @return NO_ERROR if patch removed correclty, error code otherwise. 901 */ 902 status_t releaseAudioPatchInternal(audio_patch_handle_t handle, uint32_t delayMs = 0); 903 904 status_t installPatch(const char *caller, 905 audio_patch_handle_t *patchHandle, 906 AudioIODescriptorInterface *ioDescriptor, 907 const struct audio_patch *patch, 908 int delayMs); 909 status_t installPatch(const char *caller, 910 ssize_t index, 911 audio_patch_handle_t *patchHandle, 912 const struct audio_patch *patch, 913 int delayMs, 914 uid_t uid, 915 sp<AudioPatch> *patchDescPtr); 916 917 void cleanUpEffectsForIo(audio_io_handle_t io); 918 }; 919 920 }; 921