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 <android/media/DeviceConnectedState.h> 39 #include <android/media/audio/common/AudioPort.h> 40 #include <AudioPolicyManagerObserver.h> 41 #include <AudioPolicyConfig.h> 42 #include <PolicyAudioPort.h> 43 #include <AudioPatch.h> 44 #include <DeviceDescriptor.h> 45 #include <IOProfile.h> 46 #include <HwModule.h> 47 #include <AudioInputDescriptor.h> 48 #include <AudioOutputDescriptor.h> 49 #include <AudioPolicyMix.h> 50 #include <EffectDescriptor.h> 51 #include <PreferredMixerAttributesInfo.h> 52 #include <SoundTriggerSession.h> 53 #include "EngineLibrary.h" 54 #include "TypeConverter.h" 55 56 namespace android { 57 58 using content::AttributionSourceState; 59 60 // ---------------------------------------------------------------------------- 61 62 // Attenuation applied to STRATEGY_SONIFICATION streams when a headset is connected: 6dB 63 #define SONIFICATION_HEADSET_VOLUME_FACTOR_DB (-6) 64 // Min volume for STRATEGY_SONIFICATION streams when limited by music volume: -36dB 65 #define SONIFICATION_HEADSET_VOLUME_MIN_DB (-36) 66 // Max volume difference on A2DP between playing media and STRATEGY_SONIFICATION streams: 12dB 67 #define SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB (12) 68 69 // Time in milliseconds during which we consider that music is still active after a music 70 // track was stopped - see computeVolume() 71 #define SONIFICATION_HEADSET_MUSIC_DELAY 5000 72 73 // Time in milliseconds during witch some streams are muted while the audio path 74 // is switched 75 #define MUTE_TIME_MS 2000 76 77 // multiplication factor applied to output latency when calculating a safe mute delay when 78 // invalidating tracks 79 #define LATENCY_MUTE_FACTOR 4 80 81 #define NUM_TEST_OUTPUTS 5 82 83 #define NUM_VOL_CURVE_KNEES 2 84 85 // Default minimum length allowed for offloading a compressed track 86 // Can be overridden by the audio.offload.min.duration.secs property 87 #define OFFLOAD_DEFAULT_MIN_DURATION_SECS 60 88 89 // ---------------------------------------------------------------------------- 90 // AudioPolicyManager implements audio policy manager behavior common to all platforms. 91 // ---------------------------------------------------------------------------- 92 93 class AudioPolicyManager : public AudioPolicyInterface, public AudioPolicyManagerObserver 94 { 95 96 public: 97 AudioPolicyManager(const sp<const AudioPolicyConfig>& config, 98 EngineInstance&& engine, 99 AudioPolicyClientInterface *clientInterface); 100 virtual ~AudioPolicyManager(); 101 102 // AudioPolicyInterface 103 virtual status_t setDeviceConnectionState(audio_policy_dev_state_t state, 104 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat); 105 virtual audio_policy_dev_state_t getDeviceConnectionState(audio_devices_t device, 106 const char *device_address); 107 virtual status_t handleDeviceConfigChange(audio_devices_t device, 108 const char *device_address, 109 const char *device_name, 110 audio_format_t encodedFormat); 111 virtual void setPhoneState(audio_mode_t state); 112 virtual void setForceUse(audio_policy_force_use_t usage, 113 audio_policy_forced_cfg_t config); 114 virtual audio_policy_forced_cfg_t getForceUse(audio_policy_force_use_t usage); 115 116 virtual void setSystemProperty(const char* property, const char* value); 117 virtual status_t initCheck(); 118 virtual audio_io_handle_t getOutput(audio_stream_type_t stream); 119 status_t getOutputForAttr(const audio_attributes_t *attr, 120 audio_io_handle_t *output, 121 audio_session_t session, 122 audio_stream_type_t *stream, 123 const AttributionSourceState& attributionSource, 124 audio_config_t *config, 125 audio_output_flags_t *flags, 126 DeviceIdVector *selectedDeviceIds, 127 audio_port_handle_t *portId, 128 std::vector<audio_io_handle_t> *secondaryOutputs, 129 output_type_t *outputType, 130 bool *isSpatialized, 131 bool *isBitPerfect, 132 float *volume, 133 bool *muted) override; 134 virtual status_t startOutput(audio_port_handle_t portId); 135 virtual status_t stopOutput(audio_port_handle_t portId); 136 virtual bool releaseOutput(audio_port_handle_t portId); 137 138 base::expected<media::GetInputForAttrResponse, std::variant<binder::Status, 139 media::audio::common::AudioConfigBase>> 140 getInputForAttr(audio_attributes_t attributes, 141 audio_io_handle_t requestedInput, 142 audio_port_handle_t requestedDeviceId, 143 audio_config_base_t config, 144 audio_input_flags_t flags, 145 audio_unique_id_t riid, 146 audio_session_t session, 147 const AttributionSourceState& attributionSource) override; 148 149 // indicates to the audio policy manager that the input starts being used. 150 virtual status_t startInput(audio_port_handle_t portId); 151 152 // indicates to the audio policy manager that the input stops being used. 153 virtual status_t stopInput(audio_port_handle_t portId); 154 virtual void releaseInput(audio_port_handle_t portId); 155 virtual void checkCloseInputs(); 156 virtual status_t setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType, 157 const char *address, 158 bool enabled, 159 audio_stream_type_t streamToDriveAbs); 160 /** 161 * @brief initStreamVolume: even if the engine volume files provides min and max, keep this 162 * api for compatibility reason. 163 * AudioServer will get the min and max and may overwrite them if: 164 * -using property (highest priority) 165 * -not defined (-1 by convention), case when still using apm volume tables XML files 166 * @param stream to be considered 167 * @param indexMin to set 168 * @param indexMax to set 169 */ 170 virtual void initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax); 171 virtual status_t setStreamVolumeIndex(audio_stream_type_t stream, 172 int index, 173 bool muted, 174 audio_devices_t device); 175 virtual status_t getStreamVolumeIndex(audio_stream_type_t stream, 176 int *index, 177 audio_devices_t device); 178 179 virtual status_t setVolumeIndexForAttributes(const audio_attributes_t &attr, 180 int index, 181 bool muted, 182 audio_devices_t device); 183 virtual status_t getVolumeIndexForAttributes(const audio_attributes_t &attr, 184 int &index, 185 audio_devices_t device); 186 virtual status_t getMaxVolumeIndexForAttributes(const audio_attributes_t &attr, int &index); 187 188 virtual status_t getMinVolumeIndexForAttributes(const audio_attributes_t &attr, int &index); 189 190 status_t setVolumeCurveIndex(int index, 191 bool muted, 192 audio_devices_t device, 193 IVolumeCurves &volumeCurves); 194 195 status_t getVolumeIndex(const IVolumeCurves &curves, int &index, 196 const DeviceTypeSet& deviceTypes) const; 197 198 // return the strategy corresponding to a given stream type getStrategyForStream(audio_stream_type_t stream)199 virtual product_strategy_t getStrategyForStream(audio_stream_type_t stream) 200 { 201 return streamToStrategy(stream); 202 } streamToStrategy(audio_stream_type_t stream)203 product_strategy_t streamToStrategy(audio_stream_type_t stream) const 204 { 205 auto attributes = mEngine->getAttributesForStreamType(stream); 206 return mEngine->getProductStrategyForAttributes(attributes); 207 } 208 209 /** 210 * Returns a vector of devices associated with attributes. 211 * 212 * An AudioTrack opened with specified attributes should play on the returned devices. 213 * If forVolume is set to true, the caller is AudioService, determining the proper 214 * device volume to adjust. 215 * 216 * Devices are determined in the following precedence: 217 * 1) Devices associated with a dynamic policy matching the attributes. This is often 218 * a remote submix from MIX_ROUTE_FLAG_LOOP_BACK. Secondary mixes from a 219 * dynamic policy are not included. 220 * 221 * If no such dynamic policy then 222 * 2) Devices containing an active client using setPreferredDevice 223 * with same strategy as the attributes. 224 * (from the default Engine::getOutputDevicesForAttributes() implementation). 225 * 226 * If no corresponding active client with setPreferredDevice then 227 * 3) Devices associated with the strategy determined by the attributes 228 * (from the default Engine::getOutputDevicesForAttributes() implementation). 229 * 230 * @param attributes to be considered 231 * @param devices an AudioDeviceTypeAddrVector container passed in that 232 * will be filled on success. 233 * @param forVolume true if the devices are to be associated with current device volume. 234 * @return NO_ERROR on success. 235 */ 236 virtual status_t getDevicesForAttributes( 237 const audio_attributes_t &attributes, 238 AudioDeviceTypeAddrVector *devices, 239 bool forVolume); 240 241 virtual audio_io_handle_t getOutputForEffect(const effect_descriptor_t *desc = NULL); 242 virtual status_t registerEffect(const effect_descriptor_t *desc, 243 audio_io_handle_t io, 244 product_strategy_t strategy, 245 int session, 246 int id); 247 virtual status_t unregisterEffect(int id); 248 virtual status_t setEffectEnabled(int id, bool enabled); 249 status_t moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io) override; 250 251 virtual bool isStreamActive(audio_stream_type_t stream, uint32_t inPastMs = 0) const; 252 // return whether a stream is playing remotely, override to change the definition of 253 // local/remote playback, used for instance by notification manager to not make 254 // media players lose audio focus when not playing locally 255 // For the base implementation, "remotely" means playing during screen mirroring which 256 // uses an output for playback with a non-empty, non "0" address. 257 virtual bool isStreamActiveRemotely(audio_stream_type_t stream, 258 uint32_t inPastMs = 0) const; 259 260 virtual bool isSourceActive(audio_source_t source) const; 261 262 // helpers for dump(int fd) 263 void dumpManualSurroundFormats(String8 *dst) const; 264 void dump(String8 *dst) const; 265 266 status_t dump(int fd) override; 267 268 status_t setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy) override; 269 virtual audio_offload_mode_t getOffloadSupport(const audio_offload_info_t& offloadInfo); 270 271 virtual bool isDirectOutputSupported(const audio_config_base_t& config, 272 const audio_attributes_t& attributes); 273 274 virtual status_t listAudioPorts(audio_port_role_t role, 275 audio_port_type_t type, 276 unsigned int *num_ports, 277 struct audio_port_v7 *ports, 278 unsigned int *generation); 279 status_t listDeclaredDevicePorts(media::AudioPortRole role, 280 std::vector<media::AudioPortFw>* result) override; 281 virtual status_t getAudioPort(struct audio_port_v7 *port); 282 virtual status_t createAudioPatch(const struct audio_patch *patch, 283 audio_patch_handle_t *handle, 284 uid_t uid); 285 virtual status_t releaseAudioPatch(audio_patch_handle_t handle, 286 uid_t uid); 287 virtual status_t listAudioPatches(unsigned int *num_patches, 288 struct audio_patch *patches, 289 unsigned int *generation); 290 virtual status_t setAudioPortConfig(const struct audio_port_config *config); 291 292 virtual void releaseResourcesForUid(uid_t uid); 293 294 virtual status_t acquireSoundTriggerSession(audio_session_t *session, 295 audio_io_handle_t *ioHandle, 296 audio_devices_t *device); 297 releaseSoundTriggerSession(audio_session_t session)298 virtual status_t releaseSoundTriggerSession(audio_session_t session) 299 { 300 return mSoundTriggerSessions.releaseSession(session); 301 } 302 303 virtual status_t registerPolicyMixes(const Vector<AudioMix>& mixes); 304 virtual status_t unregisterPolicyMixes(Vector<AudioMix> mixes); 305 virtual status_t getRegisteredPolicyMixes(std::vector<AudioMix>& mixes) override; 306 virtual status_t updatePolicyMix( 307 const AudioMix& mix, 308 const std::vector<AudioMixMatchCriterion>& updatedCriteria) override; 309 virtual status_t setUidDeviceAffinities(uid_t uid, 310 const AudioDeviceTypeAddrVector& devices); 311 virtual status_t removeUidDeviceAffinities(uid_t uid); 312 virtual status_t setUserIdDeviceAffinities(int userId, 313 const AudioDeviceTypeAddrVector& devices); 314 virtual status_t removeUserIdDeviceAffinities(int userId); 315 316 virtual status_t setDevicesRoleForStrategy(product_strategy_t strategy, 317 device_role_t role, 318 const AudioDeviceTypeAddrVector &devices); 319 320 virtual status_t removeDevicesRoleForStrategy(product_strategy_t strategy, 321 device_role_t role, 322 const AudioDeviceTypeAddrVector &devices); 323 324 virtual status_t clearDevicesRoleForStrategy(product_strategy_t strategy, 325 device_role_t role); 326 327 virtual status_t getDevicesForRoleAndStrategy(product_strategy_t strategy, 328 device_role_t role, 329 AudioDeviceTypeAddrVector &devices); 330 331 virtual status_t setDevicesRoleForCapturePreset(audio_source_t audioSource, 332 device_role_t role, 333 const AudioDeviceTypeAddrVector &devices); 334 335 virtual status_t addDevicesRoleForCapturePreset(audio_source_t audioSource, 336 device_role_t role, 337 const AudioDeviceTypeAddrVector &devices); 338 339 virtual status_t removeDevicesRoleForCapturePreset( 340 audio_source_t audioSource, device_role_t role, 341 const AudioDeviceTypeAddrVector& devices); 342 343 virtual status_t clearDevicesRoleForCapturePreset(audio_source_t audioSource, 344 device_role_t role); 345 346 virtual status_t getDevicesForRoleAndCapturePreset(audio_source_t audioSource, 347 device_role_t role, 348 AudioDeviceTypeAddrVector &devices); 349 350 virtual status_t startAudioSource(const struct audio_port_config *source, 351 const audio_attributes_t *attributes, 352 audio_port_handle_t *portId, 353 uid_t uid); 354 virtual status_t stopAudioSource(audio_port_handle_t portId); 355 356 virtual status_t setMasterMono(bool mono); 357 virtual status_t getMasterMono(bool *mono); 358 virtual float getStreamVolumeDB( 359 audio_stream_type_t stream, int index, audio_devices_t device); 360 361 virtual status_t getSurroundFormats(unsigned int *numSurroundFormats, 362 audio_format_t *surroundFormats, 363 bool *surroundFormatsEnabled); 364 virtual status_t getReportedSurroundFormats(unsigned int *numSurroundFormats, 365 audio_format_t *surroundFormats); 366 virtual status_t setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled); 367 368 virtual status_t getHwOffloadFormatsSupportedForBluetoothMedia( 369 audio_devices_t device, std::vector<audio_format_t> *formats); 370 371 virtual void setAppState(audio_port_handle_t portId, app_state_t state); 372 373 virtual bool isHapticPlaybackSupported(); 374 375 virtual bool isUltrasoundSupported(); 376 377 bool isHotwordStreamSupported(bool lookbackAudio) override; 378 listAudioProductStrategies(AudioProductStrategyVector & strategies)379 virtual status_t listAudioProductStrategies(AudioProductStrategyVector &strategies) 380 { 381 return mEngine->listAudioProductStrategies(strategies); 382 } 383 getProductStrategyFromAudioAttributes(const audio_attributes_t & aa,product_strategy_t & productStrategy,bool fallbackOnDefault)384 virtual status_t getProductStrategyFromAudioAttributes( 385 const audio_attributes_t &aa, product_strategy_t &productStrategy, 386 bool fallbackOnDefault) 387 { 388 productStrategy = mEngine->getProductStrategyForAttributes(aa, fallbackOnDefault); 389 return (fallbackOnDefault && productStrategy == PRODUCT_STRATEGY_NONE) ? 390 BAD_VALUE : NO_ERROR; 391 } 392 listAudioVolumeGroups(AudioVolumeGroupVector & groups)393 virtual status_t listAudioVolumeGroups(AudioVolumeGroupVector &groups) 394 { 395 return mEngine->listAudioVolumeGroups(groups); 396 } 397 getVolumeGroupFromAudioAttributes(const audio_attributes_t & aa,volume_group_t & volumeGroup,bool fallbackOnDefault)398 virtual status_t getVolumeGroupFromAudioAttributes( 399 const audio_attributes_t &aa, volume_group_t &volumeGroup, bool fallbackOnDefault) 400 { 401 volumeGroup = mEngine->getVolumeGroupForAttributes(aa, fallbackOnDefault); 402 return (fallbackOnDefault && volumeGroup == VOLUME_GROUP_NONE) ? 403 BAD_VALUE : NO_ERROR; 404 } 405 canBeSpatialized(const audio_attributes_t * attr,const audio_config_t * config,const AudioDeviceTypeAddrVector & devices)406 virtual bool canBeSpatialized(const audio_attributes_t *attr, 407 const audio_config_t *config, 408 const AudioDeviceTypeAddrVector &devices) const { 409 return canBeSpatializedInt(attr, config, devices); 410 } 411 412 virtual status_t getSpatializerOutput(const audio_config_base_t *config, 413 const audio_attributes_t *attr, 414 audio_io_handle_t *output); 415 416 virtual status_t releaseSpatializerOutput(audio_io_handle_t output); 417 418 virtual audio_direct_mode_t getDirectPlaybackSupport(const audio_attributes_t *attr, 419 const audio_config_t *config); 420 421 virtual status_t getDirectProfilesForAttributes(const audio_attributes_t* attr, 422 AudioProfileVector& audioProfiles); 423 424 status_t getSupportedMixerAttributes( 425 audio_port_handle_t portId, 426 std::vector<audio_mixer_attributes_t>& mixerAttrs) override; 427 status_t setPreferredMixerAttributes( 428 const audio_attributes_t* attr, 429 audio_port_handle_t portId, 430 uid_t uid, 431 const audio_mixer_attributes_t* mixerAttributes) override; 432 status_t getPreferredMixerAttributes(const audio_attributes_t* attr, 433 audio_port_handle_t portId, 434 audio_mixer_attributes_t* mixerAttributes) override; 435 status_t clearPreferredMixerAttributes(const audio_attributes_t* attr, 436 audio_port_handle_t portId, 437 uid_t uid) override; 438 439 bool isCallScreenModeSupported() override; 440 441 void onNewAudioModulesAvailable() override; 442 443 status_t getMmapPolicyInfos( 444 media::audio::common::AudioMMapPolicyType policyType, 445 std::vector<media::audio::common::AudioMMapPolicyInfo> *policyInfos) override; 446 status_t getMmapPolicyForDevice( 447 media::audio::common::AudioMMapPolicyType policyType, 448 media::audio::common::AudioMMapPolicyInfo *policyInfo) override; 449 450 status_t initialize(); 451 452 protected: getConfig()453 const AudioPolicyConfig& getConfig() const { return *(mConfig.get()); } 454 455 // From AudioPolicyManagerObserver getAudioPatches()456 virtual const AudioPatchCollection &getAudioPatches() const 457 { 458 return mAudioPatches; 459 } getSoundTriggerSessionCollection()460 virtual const SoundTriggerSessionCollection &getSoundTriggerSessionCollection() const 461 { 462 return mSoundTriggerSessions; 463 } getAudioPolicyMixCollection()464 virtual const AudioPolicyMixCollection &getAudioPolicyMixCollection() const 465 { 466 return mPolicyMixes; 467 } getOutputs()468 virtual const SwAudioOutputCollection &getOutputs() const 469 { 470 return mOutputs; 471 } getInputs()472 virtual const AudioInputCollection &getInputs() const 473 { 474 return mInputs; 475 } getAvailableOutputDevices()476 virtual const DeviceVector getAvailableOutputDevices() const 477 { 478 return mAvailableOutputDevices.filterForEngine(); 479 } getAvailableInputDevices()480 virtual const DeviceVector getAvailableInputDevices() const 481 { 482 // legacy and non-legacy remote-submix are managed by the engine, do not filter 483 return mAvailableInputDevices; 484 } getDefaultOutputDevice()485 virtual const sp<DeviceDescriptor> &getDefaultOutputDevice() const 486 { 487 return mConfig->getDefaultOutputDevice(); 488 } 489 getVolumeGroups()490 std::vector<volume_group_t> getVolumeGroups() const 491 { 492 return mEngine->getVolumeGroups(); 493 } 494 toVolumeSource(volume_group_t volumeGroup)495 VolumeSource toVolumeSource(volume_group_t volumeGroup) const 496 { 497 return static_cast<VolumeSource>(volumeGroup); 498 } 499 /** 500 * @brief toVolumeSource converts an audio attributes into a volume source 501 * (either a legacy stream or a volume group). If fallback on default is allowed, and if 502 * the audio attributes do not follow any specific product strategy's rule, it will be 503 * associated to default volume source, e.g. music. Thus, any of call of volume API 504 * using this translation function may affect the default volume source. 505 * If fallback is not allowed and no matching rule is identified for the given attributes, 506 * the volume source will be undefined, thus, no volume will be altered/modified. 507 * @param attributes to be considered 508 * @param fallbackOnDefault 509 * @return volume source associated with given attributes, otherwise either music if 510 * fallbackOnDefault is set or none. 511 */ 512 VolumeSource toVolumeSource( 513 const audio_attributes_t &attributes, bool fallbackOnDefault = true) const 514 { 515 return toVolumeSource(mEngine->getVolumeGroupForAttributes( 516 attributes, fallbackOnDefault)); 517 } 518 VolumeSource toVolumeSource( 519 audio_stream_type_t stream, bool fallbackOnDefault = true) const 520 { 521 return toVolumeSource(mEngine->getVolumeGroupForStreamType( 522 stream, fallbackOnDefault)); 523 } getVolumeCurves(VolumeSource volumeSource)524 IVolumeCurves &getVolumeCurves(VolumeSource volumeSource) 525 { 526 auto *curves = mEngine->getVolumeCurvesForVolumeGroup( 527 static_cast<volume_group_t>(volumeSource)); 528 ALOG_ASSERT(curves != nullptr, "No curves for volume source %d", volumeSource); 529 return *curves; 530 } getVolumeCurves(const audio_attributes_t & attr)531 IVolumeCurves &getVolumeCurves(const audio_attributes_t &attr) 532 { 533 auto *curves = mEngine->getVolumeCurvesForAttributes(attr); 534 ALOG_ASSERT(curves != nullptr, "No curves for attributes %s", toString(attr).c_str()); 535 return *curves; 536 } getVolumeCurves(audio_stream_type_t stream)537 IVolumeCurves &getVolumeCurves(audio_stream_type_t stream) 538 { 539 auto *curves = mEngine->getVolumeCurvesForStreamType(stream); 540 ALOG_ASSERT(curves != nullptr, "No curves for stream %s", toString(stream).c_str()); 541 return *curves; 542 } 543 544 void addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc); 545 void removeOutput(audio_io_handle_t output); 546 void addInput(audio_io_handle_t input, const sp<AudioInputDescriptor>& inputDesc); 547 bool checkCloseInput(const sp<AudioInputDescriptor>& input); 548 549 /** 550 * @brief setOutputDevices change the route of the specified output. 551 * @param caller of the method 552 * @param outputDesc to be considered 553 * @param device to be considered to route the output 554 * @param force if true, force the routing even if no change. 555 * @param delayMs if specified, delay to apply for mute/volume op when changing device 556 * @param patchHandle if specified, the patch handle this output is connected through. 557 * @param requiresMuteCheck if specified, for e.g. when another output is on a shared device 558 * and currently active, allow to have proper drain and avoid pops 559 * @param requiresVolumeCheck true if called requires to reapply volume if the routing did 560 * not change (but the output is still routed). 561 * @param skipMuteDelay if true will skip mute delay when installing audio patch 562 * @return the number of ms we have slept to allow new routing to take effect in certain 563 * cases. 564 */ 565 uint32_t setOutputDevices(const char *caller, 566 const sp<SwAudioOutputDescriptor>& outputDesc, 567 const DeviceVector &device, 568 bool force = false, 569 int delayMs = 0, 570 audio_patch_handle_t *patchHandle = NULL, 571 bool requiresMuteCheck = true, 572 bool requiresVolumeCheck = false, 573 bool skipMuteDelay = false); 574 status_t resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc, 575 int delayMs = 0, 576 audio_patch_handle_t *patchHandle = NULL); 577 status_t setInputDevice(audio_io_handle_t input, 578 const sp<DeviceDescriptor> &device, 579 bool force = false, 580 audio_patch_handle_t *patchHandle = NULL); 581 status_t resetInputDevice(audio_io_handle_t input, 582 audio_patch_handle_t *patchHandle = NULL); 583 584 /** 585 * Compute volume in DB that should be applied for a volume source and device types for a 586 * particular volume index. 587 * 588 * <p><b>Note:</b>Internally the compute method recursively calls itself to accurately 589 * determine the volume given the currently active sources and devices. Some of the 590 * interaction that require recursive computation are: 591 * <ul> 592 * <li>Match accessibility volume if ringtone volume is much louder</li> 593 * <li>If voice call is active cap other volumes (except ringtone and accessibility)</li> 594 * <li>Attenuate notification if headset is connected to prevent burst in user's ear</li> 595 * <li>Attenuate ringtone if headset is connected and music is not playing and speaker is 596 * part of the devices to prevent burst in user's ear</li> 597 * <li>Limit music volume if headset is connected and notification is also active</li> 598 * </ul> 599 * 600 * @param curves volume curves to use for calculating volume value given the index 601 * @param volumeSource source (use case) of the volume 602 * @param index index to match in the volume curves for the calculation 603 * @param deviceTypes devices that should be considered in the volume curves for the 604 * calculation 605 * @param adjustAttenuation boolean indicating whether we should adjust the value to 606 * avoid double attenuation when controlling an avrcp device 607 * @param computeInternalInteraction boolean indicating whether recursive volume computation 608 * should continue within the volume computation. Defaults to {@code true} so the 609 * volume interactions can be computed. Calls within the method should always set the 610 * the value to {@code false} to prevent infinite recursion. 611 * @return computed volume in DB 612 */ 613 virtual float computeVolume(IVolumeCurves &curves, VolumeSource volumeSource, 614 int index, const DeviceTypeSet& deviceTypes, 615 bool adjustAttenuation = true, 616 bool computeInternalInteraction = true); 617 618 // rescale volume index from srcStream within range of dstStream 619 int rescaleVolumeIndex(int srcIndex, 620 VolumeSource fromVolumeSource, 621 VolumeSource toVolumeSource); 622 // check that volume change is permitted, compute and send new volume to audio hardware 623 virtual status_t checkAndSetVolume(IVolumeCurves &curves, 624 VolumeSource volumeSource, int index, 625 const sp<AudioOutputDescriptor>& outputDesc, 626 DeviceTypeSet deviceTypes, 627 int delayMs = 0, bool force = false); 628 629 void setVoiceVolume(int index, IVolumeCurves &curves, bool isVoiceVolSrc, int delayMs); 630 631 // returns true if the supplied set of volume source and devices are consistent with 632 // call volume rules: 633 // if Bluetooth SCO and voice call use different volume curves: 634 // - do not apply voice call volume if Bluetooth SCO is used for call 635 // - do not apply Bluetooth SCO volume if SCO or Hearing Aid is not used for call. 636 // Also updates the booleans isVoiceVolSrc and isBtScoVolSrc according to the 637 // volume source supplied. 638 bool isVolumeConsistentForCalls(VolumeSource volumeSource, 639 const DeviceTypeSet& deviceTypes, 640 bool& isVoiceVolSrc, 641 bool& isBtScoVolSrc, 642 const char* caller); 643 // apply all stream volumes to the specified output and device 644 void applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc, 645 const DeviceTypeSet& deviceTypes, 646 int delayMs = 0, bool force = false); 647 648 /** 649 * @brief setStrategyMute Mute or unmute all active clients on the considered output 650 * following the given strategy. 651 * @param strategy to be considered 652 * @param on true for mute, false for unmute 653 * @param outputDesc to be considered 654 * @param delayMs 655 * @param device 656 */ 657 void setStrategyMute(product_strategy_t strategy, 658 bool on, 659 const sp<AudioOutputDescriptor>& outputDesc, 660 int delayMs = 0, 661 DeviceTypeSet deviceTypes = DeviceTypeSet()); 662 663 /** 664 * @brief setVolumeSourceMutedInternally Mute or unmute the volume source on the specified 665 * output 666 * @param volumeSource to be muted/unmute (may host legacy streams or by extension set of 667 * audio attributes) 668 * @param on true to mute, false to umute 669 * @param outputDesc on which the client following the volume group shall be muted/umuted 670 * @param delayMs 671 * @param device 672 */ 673 void setVolumeSourceMutedInternally(VolumeSource volumeSource, 674 bool on, 675 const sp<AudioOutputDescriptor>& outputDesc, 676 int delayMs = 0, 677 DeviceTypeSet deviceTypes = DeviceTypeSet()); 678 679 audio_mode_t getPhoneState(); 680 681 // true if device is in a telephony or VoIP call 682 virtual bool isInCall() const; 683 // true if given state represents a device in a telephony or VoIP call 684 virtual bool isStateInCall(int state) const; 685 // true if playback to call TX or capture from call RX is possible 686 bool isCallAudioAccessible() const; 687 // true if device is in a telephony or VoIP call or call screening is active 688 bool isInCallOrScreening() const; 689 690 // when a device is connected, checks if an open output can be routed 691 // to this device. If none is open, tries to open one of the available outputs. 692 // Returns an output suitable to this device or 0. 693 // when a device is disconnected, checks if an output is not used any more and 694 // returns its handle if any. 695 // transfers the audio tracks and effects from one output thread to another accordingly. 696 status_t checkOutputsForDevice(const sp<DeviceDescriptor>& device, 697 audio_policy_dev_state_t state, 698 SortedVector<audio_io_handle_t>& outputs); 699 700 status_t checkInputsForDevice(const sp<DeviceDescriptor>& device, 701 audio_policy_dev_state_t state); 702 703 // close an output and its companion duplicating output. 704 void closeOutput(audio_io_handle_t output); 705 706 // close an input. 707 void closeInput(audio_io_handle_t input); 708 709 // runs all the checks required for accommodating changes in devices and outputs 710 // if 'onOutputsChecked' callback is provided, it is executed after the outputs 711 // check via 'checkOutputForAllStrategies'. If the callback returns 'true', 712 // A2DP suspend status is rechecked. 713 void checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked = nullptr); 714 715 /** 716 * @brief updates routing for all outputs (including call if call in progress). 717 * @param delayMs delay for unmuting if required 718 * @param skipDelays if true all the delays will be skip while updating routing 719 */ 720 void updateCallAndOutputRouting(bool forceVolumeReeval = true, uint32_t delayMs = 0, 721 bool skipDelays = false); 722 723 void connectTelephonyRxAudioSource(uint32_t delayMs); 724 725 void disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc); 726 727 void connectTelephonyTxAudioSource(const sp<DeviceDescriptor> &srcdevice, 728 const sp<DeviceDescriptor> &sinkDevice, 729 uint32_t delayMs); 730 isTelephonyRxOrTx(const sp<SwAudioOutputDescriptor> & desc)731 bool isTelephonyRxOrTx(const sp<SwAudioOutputDescriptor>& desc) const { 732 return (mCallRxSourceClient != nullptr && mCallRxSourceClient->belongsToOutput(desc)) 733 || (mCallTxSourceClient != nullptr 734 && mCallTxSourceClient->belongsToOutput(desc)); 735 } 736 737 /** 738 * @brief updates routing for all inputs. 739 */ 740 void updateInputRouting(); 741 742 /** 743 * @brief checkOutputForAttributes checks and if necessary changes outputs used for the 744 * given audio attributes. 745 * must be called every time a condition that affects the output choice for a given 746 * attributes changes: connected device, phone state, force use... 747 * Must be called before updateDevicesAndOutputs() 748 * @param attr to be considered 749 */ 750 void checkOutputForAttributes(const audio_attributes_t &attr); 751 752 /** 753 * @brief checkAudioSourceForAttributes checks if any AudioSource following the same routing 754 * as the given audio attributes is not routed and try to connect it. 755 * It must be called once checkOutputForAttributes has been called for orphans AudioSource, 756 * aka AudioSource not attached to any Audio Output (e.g. AudioSource connected to direct 757 * Output which has been disconnected (and output closed) due to sink device unavailable). 758 * @param attr to be considered 759 */ 760 void checkAudioSourceForAttributes(const audio_attributes_t &attr); 761 762 bool followsSameRouting(const audio_attributes_t &lAttr, 763 const audio_attributes_t &rAttr) const; 764 765 /** 766 * @brief checkOutputForAllStrategies Same as @see checkOutputForAttributes() 767 * but for a all product strategies in order of priority 768 */ 769 void checkOutputForAllStrategies(); 770 771 // Same as checkOutputForStrategy but for secondary outputs. Make sure if a secondary 772 // output condition changes, the track is properly rerouted 773 void checkSecondaryOutputs(); 774 775 // manages A2DP output suspend/restore according to phone state and BT SCO usage 776 void checkA2dpSuspend(); 777 778 // selects the most appropriate device on output for current state 779 // must be called every time a condition that affects the device choice for a given output is 780 // changed: connected device, phone state, force use, output start, output stop.. 781 // see getDeviceForStrategy() for the use of fromCache parameter 782 DeviceVector getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc, 783 bool fromCache); 784 785 /** 786 * @brief updateDevicesAndOutputs: updates cache of devices of the engine 787 * must be called every time a condition that affects the device choice is changed: 788 * connected device, phone state, force use... 789 * cached values are used by getOutputDevicesForStream()/getDevicesForAttributes if 790 * parameter fromCache is true. 791 * Must be called after checkOutputForAllStrategies() 792 */ 793 void updateDevicesAndOutputs(); 794 795 // selects the most appropriate device on input for current state 796 sp<DeviceDescriptor> getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc); 797 getMaxEffectsCpuLoad()798 virtual uint32_t getMaxEffectsCpuLoad() 799 { 800 return mEffects.getMaxEffectsCpuLoad(); 801 } 802 getMaxEffectsMemory()803 virtual uint32_t getMaxEffectsMemory() 804 { 805 return mEffects.getMaxEffectsMemory(); 806 } 807 808 SortedVector<audio_io_handle_t> getOutputsForDevices( 809 const DeviceVector &devices, const SwAudioOutputCollection& openOutputs); 810 811 /** 812 * @brief checkDeviceMuteStrategies mute/unmute strategies 813 * using an incompatible device combination. 814 * if muting, wait for the audio in pcm buffer to be drained before proceeding 815 * if unmuting, unmute only after the specified delay 816 * @param outputDesc 817 * @param prevDevice 818 * @param delayMs 819 * @return the number of ms waited 820 */ 821 virtual uint32_t checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc, 822 const DeviceVector &prevDevices, 823 uint32_t delayMs); 824 825 audio_io_handle_t selectOutput(const SortedVector<audio_io_handle_t>& outputs, 826 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE, 827 audio_format_t format = AUDIO_FORMAT_INVALID, 828 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE, 829 uint32_t samplingRate = 0, 830 audio_session_t sessionId = AUDIO_SESSION_NONE); 831 // samplingRate, format, channelMask are in/out and so may be modified 832 sp<IOProfile> getInputProfile(const sp<DeviceDescriptor> & device, 833 uint32_t& samplingRate, 834 audio_format_t& format, 835 audio_channel_mask_t& channelMask, 836 audio_input_flags_t flags); 837 /** 838 * @brief getProfileForOutput 839 * @param devices vector of descriptors, may be empty if ignoring the device is required 840 * @param samplingRate 841 * @param format 842 * @param channelMask 843 * @param flags 844 * @param directOnly 845 * @return IOProfile to be used if found, nullptr otherwise 846 */ 847 sp<IOProfile> getProfileForOutput(const DeviceVector &devices, 848 uint32_t samplingRate, 849 audio_format_t format, 850 audio_channel_mask_t channelMask, 851 audio_output_flags_t flags, 852 bool directOnly); 853 /** 854 * Same as getProfileForOutput, but it looks for an MSD profile 855 */ 856 sp<IOProfile> getMsdProfileForOutput(const DeviceVector &devices, 857 uint32_t samplingRate, 858 audio_format_t format, 859 audio_channel_mask_t channelMask, 860 audio_output_flags_t flags, 861 bool directOnly); 862 863 audio_io_handle_t selectOutputForMusicEffects(); 864 addAudioPatch(audio_patch_handle_t handle,const sp<AudioPatch> & patch)865 virtual status_t addAudioPatch(audio_patch_handle_t handle, const sp<AudioPatch>& patch) 866 { 867 return mAudioPatches.addAudioPatch(handle, patch); 868 } removeAudioPatch(audio_patch_handle_t handle)869 virtual status_t removeAudioPatch(audio_patch_handle_t handle) 870 { 871 return mAudioPatches.removeAudioPatch(handle); 872 } 873 isPrimaryModule(const sp<HwModule> & module)874 bool isPrimaryModule(const sp<HwModule> &module) const 875 { 876 if (module == nullptr || mPrimaryModuleHandle == AUDIO_MODULE_HANDLE_NONE) { 877 return false; 878 } 879 return module->getHandle() == mPrimaryModuleHandle; 880 } availablePrimaryOutputDevices()881 DeviceVector availablePrimaryOutputDevices() const 882 { 883 if (!hasPrimaryOutput()) { 884 return DeviceVector(); 885 } 886 return mAvailableOutputDevices.filter(mPrimaryOutput->supportedDevices()); 887 } availablePrimaryModuleInputDevices()888 DeviceVector availablePrimaryModuleInputDevices() const 889 { 890 if (!hasPrimaryOutput()) { 891 return DeviceVector(); 892 } 893 return mAvailableInputDevices.getDevicesFromHwModule( 894 mPrimaryOutput->getModuleHandle()); 895 } 896 getFirstDeviceAddress(const DeviceVector & devices)897 String8 getFirstDeviceAddress(const DeviceVector &devices) const 898 { 899 return (devices.size() > 0) ? 900 String8(devices.itemAt(0)->address().c_str()) : String8(""); 901 } 902 903 status_t updateCallRouting( 904 bool fromCache, uint32_t delayMs = 0, uint32_t *waitMs = nullptr); 905 status_t updateCallRoutingInternal( 906 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs); 907 sp<AudioPatch> createTelephonyPatch(bool isRx, const sp<DeviceDescriptor> &device, 908 uint32_t delayMs); 909 /** 910 * @brief selectBestRxSinkDevicesForCall: if the primary module host both Telephony Rx/Tx 911 * devices, and it declares also supporting a HW bridge between the Telephony Rx and the 912 * given sink device for Voice Call audio attributes, select this device in prio. 913 * Otherwise, getNewOutputDevices() is called on the primary output to select sink device. 914 * @param fromCache true to prevent engine reconsidering all product strategies and retrieve 915 * from engine cache. 916 * @return vector of devices, empty if none is found. 917 */ 918 DeviceVector selectBestRxSinkDevicesForCall(bool fromCache); 919 bool isDeviceOfModule(const sp<DeviceDescriptor>& devDesc, const char *moduleId) const; 920 921 status_t startSource(const sp<SwAudioOutputDescriptor>& outputDesc, 922 const sp<TrackClientDescriptor>& client, 923 uint32_t *delayMs); 924 status_t stopSource(const sp<SwAudioOutputDescriptor>& outputDesc, 925 const sp<TrackClientDescriptor>& client); 926 927 void clearAudioPatches(uid_t uid); 928 void clearSessionRoutes(uid_t uid); 929 930 /** 931 * @brief checkStrategyRoute: when an output is beeing rerouted, reconsider each output 932 * that may host a strategy playing on the considered output. 933 * @param ps product strategy that initiated the rerouting 934 * @param ouptutToSkip output that initiated the rerouting 935 */ 936 void checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip); 937 hasPrimaryOutput()938 status_t hasPrimaryOutput() const { return mPrimaryOutput != 0; } 939 940 status_t connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc, 941 uint32_t delayMs); 942 status_t disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc); 943 944 status_t connectAudioSourceToSink(const sp<SourceClientDescriptor>& sourceDesc, 945 const sp<DeviceDescriptor> &sinkDevice, 946 const struct audio_patch *patch, 947 audio_patch_handle_t &handle, 948 uid_t uid, uint32_t delayMs); 949 950 sp<SourceClientDescriptor> getSourceForAttributesOnOutput(audio_io_handle_t output, 951 const audio_attributes_t &attr); 952 void clearAudioSourcesForOutput(audio_io_handle_t output); 953 954 void cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc); 955 956 void clearAudioSources(uid_t uid); 957 958 static bool streamsMatchForvolume(audio_stream_type_t stream1, 959 audio_stream_type_t stream2); 960 961 void closeActiveClients(const sp<AudioInputDescriptor>& input); 962 void closeClient(audio_port_handle_t portId); 963 964 /** 965 * @brief isAnyDeviceTypeActive: returns true if at least one active client is routed to 966 * one of the specified devices 967 * @param deviceTypes list of devices to consider 968 */ 969 bool isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const; 970 /** 971 * @brief isLeUnicastActive: returns true if a call is active or at least one active client 972 * is routed to a LE unicast device 973 */ 974 bool isLeUnicastActive() const; 975 976 void checkLeBroadcastRoutes(bool wasUnicastActive, 977 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs); 978 979 status_t startAudioSourceInternal(const struct audio_port_config *source, 980 const audio_attributes_t *attributes, 981 audio_port_handle_t *portId, 982 uid_t uid, 983 bool internal, 984 bool isCallRx, 985 uint32_t delayMs); 986 const uid_t mUidCached; // AID_AUDIOSERVER 987 sp<const AudioPolicyConfig> mConfig; 988 EngineInstance mEngine; // Audio Policy Engine instance 989 AudioPolicyClientInterface *mpClientInterface; // audio policy client interface 990 sp<SwAudioOutputDescriptor> mPrimaryOutput; // primary output descriptor 991 // mPrimaryModuleHandle is cached mPrimaryOutput->getModuleHandle(); 992 audio_module_handle_t mPrimaryModuleHandle = AUDIO_MODULE_HANDLE_NONE; 993 // list of descriptors for outputs currently opened 994 995 sp<SwAudioOutputDescriptor> mSpatializerOutput; 996 997 SwAudioOutputCollection mOutputs; 998 // copy of mOutputs before setDeviceConnectionState() opens new outputs 999 // reset to mOutputs when updateDevicesAndOutputs() is called. 1000 SwAudioOutputCollection mPreviousOutputs; 1001 AudioInputCollection mInputs; // list of input descriptors 1002 1003 DeviceVector mAvailableOutputDevices; // all available output devices 1004 DeviceVector mAvailableInputDevices; // all available input devices 1005 1006 bool mLimitRingtoneVolume; // limit ringtone volume to music volume if headset connected 1007 1008 float mLastVoiceVolume; // last voice volume value sent to audio HAL 1009 bool mA2dpSuspended; // true if A2DP output is suspended 1010 1011 EffectDescriptorCollection mEffects; // list of registered audio effects 1012 HwModuleCollection mHwModules; // contains modules that have been loaded successfully 1013 1014 std::atomic<uint32_t> mAudioPortGeneration; 1015 1016 AudioPatchCollection mAudioPatches; 1017 1018 SoundTriggerSessionCollection mSoundTriggerSessions; 1019 1020 HwAudioOutputCollection mHwOutputs; 1021 SourceClientCollection mAudioSources; 1022 1023 // for supporting "beacon" streams, i.e. streams that only play on speaker, and never 1024 // when something other than STREAM_TTS (a.k.a. "Transmitted Through Speaker") is playing 1025 enum { 1026 STARTING_OUTPUT, 1027 STARTING_BEACON, 1028 STOPPING_OUTPUT, 1029 STOPPING_BEACON 1030 }; 1031 uint32_t mBeaconMuteRefCount; // ref count for stream that would mute beacon 1032 uint32_t mBeaconPlayingRefCount;// ref count for the playing beacon streams 1033 bool mBeaconMuted; // has STREAM_TTS been muted 1034 // true if a dedicated output for TTS stream or Ultrasound is available 1035 bool mTtsOutputAvailable; 1036 1037 bool mMasterMono; // true if we wish to force all outputs to mono 1038 AudioPolicyMixCollection mPolicyMixes; // list of registered mixes 1039 audio_io_handle_t mMusicEffectOutput; // output selected for music effects 1040 1041 uint32_t nextAudioPortGeneration(); 1042 1043 // Surround formats that are enabled manually. Taken into account when 1044 // "encoded surround" is forced into "manual" mode. 1045 std::unordered_set<audio_format_t> mManualSurroundFormats; 1046 1047 std::unordered_map<uid_t, audio_flags_mask_t> mAllowedCapturePolicies; 1048 1049 // The map of device descriptor and formats reported by the device. 1050 std::map<wp<DeviceDescriptor>, FormatVector> mReportedFormatsMap; 1051 1052 // Cached product strategy ID corresponding to legacy strategy STRATEGY_PHONE 1053 product_strategy_t mCommunnicationStrategy; 1054 1055 // The port handle of the hardware audio source created internally for the Call RX audio 1056 // end point. 1057 sp<SourceClientDescriptor> mCallRxSourceClient; 1058 sp<SourceClientDescriptor> mCallTxSourceClient; 1059 1060 std::map<audio_port_handle_t, 1061 std::map<product_strategy_t, 1062 sp<PreferredMixerAttributesInfo>>> mPreferredMixerAttrInfos; 1063 1064 // Support for Multi-Stream Decoder (MSD) module 1065 sp<DeviceDescriptor> getMsdAudioInDevice() const; 1066 DeviceVector getMsdAudioOutDevices() const; 1067 const AudioPatchCollection getMsdOutputPatches() const; 1068 status_t getMsdProfiles(bool hwAvSync, 1069 const InputProfileCollection &inputProfiles, 1070 const OutputProfileCollection &outputProfiles, 1071 const sp<DeviceDescriptor> &sourceDevice, 1072 const sp<DeviceDescriptor> &sinkDevice, 1073 AudioProfileVector &sourceProfiles, 1074 AudioProfileVector &sinkProfiles) const; 1075 status_t getBestMsdConfig(bool hwAvSync, 1076 const AudioProfileVector &sourceProfiles, 1077 const AudioProfileVector &sinkProfiles, 1078 audio_port_config *sourceConfig, 1079 audio_port_config *sinkConfig) const; 1080 PatchBuilder buildMsdPatch(bool msdIsSource, const sp<DeviceDescriptor> &device) const; 1081 status_t setMsdOutputPatches(const DeviceVector *outputDevices = nullptr); 1082 void releaseMsdOutputPatches(const DeviceVector& devices); 1083 bool msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices); 1084 1085 // Overload of setDeviceConnectionState() 1086 status_t setDeviceConnectionState(audio_devices_t deviceType, 1087 audio_policy_dev_state_t state, 1088 const char* device_address, const char* device_name, 1089 audio_format_t encodedFormat); 1090 1091 // Called by setDeviceConnectionState() 1092 status_t deviceToAudioPort(audio_devices_t deviceType, const char* device_address, 1093 const char* device_name, media::AudioPortFw* aidPort); 1094 bool isMsdPatch(const audio_patch_handle_t &handle) const; 1095 1096 private: 1097 1098 void onNewAudioModulesAvailableInt(DeviceVector *newDevices); 1099 1100 // Add or remove AC3 DTS encodings based on user preferences. 1101 void modifySurroundFormats(const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr); 1102 void modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr); 1103 1104 // If any, resolve any "dynamic" fields of the Audio Profiles collection of and IOProfile 1105 void updateAudioProfiles(const sp<DeviceDescriptor>& devDesc, audio_io_handle_t ioHandle, 1106 const sp<IOProfile> &profiles); 1107 1108 // Notify the policy client to prepare for disconnecting external device. 1109 void prepareToDisconnectExternalDevice(const sp<DeviceDescriptor> &device); 1110 1111 // Notify the policy client of any change of device state with AUDIO_IO_HANDLE_NONE, 1112 // so that the client interprets it as global to audio hardware interfaces. 1113 // It can give a chance to HAL implementer to retrieve dynamic capabilities associated 1114 // to this device for example. 1115 // TODO avoid opening stream to retrieve capabilities of a profile. 1116 status_t broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device, 1117 media::DeviceConnectedState state); 1118 1119 // updates device caching and output for streams that can influence the 1120 // routing of notifications 1121 void handleNotificationRoutingForStream(audio_stream_type_t stream); curAudioPortGeneration()1122 uint32_t curAudioPortGeneration() const { return mAudioPortGeneration; } 1123 // internal method, get audio_attributes_t from either a source audio_attributes_t 1124 // or audio_stream_type_t, respectively. 1125 status_t getAudioAttributes(audio_attributes_t *dstAttr, 1126 const audio_attributes_t *srcAttr, 1127 audio_stream_type_t srcStream); 1128 // internal method, called by getOutputForAttr() and connectAudioSource. 1129 status_t getOutputForAttrInt(audio_attributes_t *resultAttr, 1130 audio_io_handle_t *output, 1131 audio_session_t session, 1132 const audio_attributes_t *attr, 1133 audio_stream_type_t *stream, 1134 uid_t uid, 1135 audio_config_t *config, 1136 audio_output_flags_t *flags, 1137 DeviceIdVector *selectedDeviceIds, 1138 bool *isRequestedDeviceForExclusiveUse, 1139 std::vector<sp<AudioPolicyMix>> *secondaryMixes, 1140 output_type_t *outputType, 1141 bool *isSpatialized, 1142 bool *isBitPerfect); 1143 // internal method to return the output handle for the given device and format 1144 audio_io_handle_t getOutputForDevices( 1145 const DeviceVector &devices, 1146 audio_session_t session, 1147 const audio_attributes_t *attr, 1148 const audio_config_t *config, 1149 audio_output_flags_t *flags, 1150 bool *isSpatialized, 1151 sp<PreferredMixerAttributesInfo> prefMixerAttrInfo = nullptr, 1152 bool forceMutingHaptic = false); 1153 1154 // Internal method checking if a direct output can be opened matching the requested 1155 // attributes, flags, config and devices. 1156 // If NAME_NOT_FOUND is returned, an attempt can be made to open a mixed output. 1157 status_t openDirectOutput( 1158 audio_stream_type_t stream, 1159 audio_session_t session, 1160 const audio_config_t *config, 1161 audio_output_flags_t flags, 1162 const DeviceVector &devices, 1163 audio_io_handle_t *output, 1164 audio_attributes_t attributes); 1165 1166 /** 1167 * @brief Queries if some kind of spatialization will be performed if the audio playback 1168 * context described by the provided arguments is present. 1169 * The context is made of: 1170 * - The audio attributes describing the playback use case. 1171 * - The audio configuration describing the audio format, channels, sampling rate ... 1172 * - The devices describing the sink audio device selected for playback. 1173 * All arguments are optional and only the specified arguments are used to match against 1174 * supported criteria. For instance, supplying no argument will tell if spatialization is 1175 * supported or not in general. 1176 * @param attr audio attributes describing the playback use case 1177 * @param config audio configuration describing the audio format, channels, sample rate... 1178 * @param devices the sink audio device selected for playback 1179 * @return true if spatialization is possible for this context, false otherwise. 1180 */ 1181 virtual bool canBeSpatializedInt(const audio_attributes_t *attr, 1182 const audio_config_t *config, 1183 const AudioDeviceTypeAddrVector &devices) const; 1184 1185 1186 /** 1187 * @brief Gets an IOProfile for a spatializer output with the best match with 1188 * provided arguments. 1189 * The caller can have the devices criteria ignored by passing and empty vector, and 1190 * getSpatializerOutputProfile() will ignore the devices when looking for a match. 1191 * Otherwise an output profile supporting a spatializer effect that can be routed 1192 * to the specified devices must exist. 1193 * @param config audio configuration describing the audio format, channels, sample rate... 1194 * @param devices the sink audio device selected for playback 1195 * @return an IOProfile that canbe used to open a spatializer output. 1196 */ 1197 sp<IOProfile> getSpatializerOutputProfile(const audio_config_t *config, 1198 const AudioDeviceTypeAddrVector &devices) const; 1199 1200 void checkVirtualizerClientRoutes(); 1201 1202 /** 1203 * @brief Returns true if at least one device can only be reached via the output passed 1204 * as argument. Always returns false for duplicated outputs. 1205 * This can be used to decide if an output can be closed without forbidding 1206 * playback to any given device. 1207 * @param outputDesc the output to consider 1208 * @return true if at least one device can only be reached via the output. 1209 */ 1210 bool isOutputOnlyAvailableRouteToSomeDevice(const sp<SwAudioOutputDescriptor>& outputDesc); 1211 1212 /** 1213 * @brief getInputForDevice selects an input handle for a given input device and 1214 * requester context 1215 * @param device to be used by requester, selected by policy mix rules or engine 1216 * @param session requester session id 1217 * @param uid requester uid 1218 * @param attributes requester audio attributes (e.g. input source and tags matter) 1219 * @param config requested audio configuration (e.g. sample rate, format, channel mask), 1220 * will be updated if current configuration doesn't support but another 1221 * one does 1222 * @param flags requester input flags 1223 * @param policyMix may be null, policy rules to be followed by the requester 1224 * @return input io handle aka unique input identifier selected for this device. 1225 */ 1226 audio_io_handle_t getInputForDevice(const sp<DeviceDescriptor> &device, 1227 audio_session_t session, 1228 const audio_attributes_t &attributes, 1229 const audio_config_base_t &config, 1230 audio_input_flags_t flags, 1231 const sp<AudioPolicyMix> &policyMix); 1232 1233 // event is one of STARTING_OUTPUT, STARTING_BEACON, STOPPING_OUTPUT, STOPPING_BEACON 1234 // returns 0 if no mute/unmute event happened, the largest latency of the device where 1235 // the mute/unmute happened 1236 uint32_t handleEventForBeacon(int event); 1237 uint32_t setBeaconMute(bool mute); 1238 bool isValidAttributes(const audio_attributes_t *paa); 1239 1240 // Called by setDeviceConnectionState(). 1241 status_t setDeviceConnectionStateInt(audio_policy_dev_state_t state, 1242 const android::media::audio::common::AudioPort& port, 1243 audio_format_t encodedFormat); 1244 status_t setDeviceConnectionStateInt(audio_devices_t deviceType, 1245 audio_policy_dev_state_t state, 1246 const char *device_address, 1247 const char *device_name, 1248 audio_format_t encodedFormat); 1249 status_t setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device, 1250 audio_policy_dev_state_t state); 1251 1252 void setEngineDeviceConnectionState(const sp<DeviceDescriptor> device, 1253 audio_policy_dev_state_t state); 1254 updateMono(audio_io_handle_t output)1255 void updateMono(audio_io_handle_t output) { 1256 AudioParameter param; 1257 param.addInt(String8(AudioParameter::keyMonoOutput), (int)mMasterMono); 1258 mpClientInterface->setParameters(output, param.toString()); 1259 } 1260 1261 /** 1262 * @brief createAudioPatchInternal internal function to manage audio patch creation 1263 * @param[in] patch structure containing sink and source ports configuration 1264 * @param[out] handle patch handle to be provided if patch installed correctly 1265 * @param[in] uid of the client 1266 * @param[in] delayMs if required 1267 * @param[in] sourceDesc source client to be configured when creating the patch, i.e. 1268 * assigning an Output (HW or SW) used for volume control. 1269 * @return NO_ERROR if patch installed correctly, error code otherwise. 1270 */ 1271 status_t createAudioPatchInternal(const struct audio_patch *patch, 1272 audio_patch_handle_t *handle, 1273 uid_t uid, uint32_t delayMs, 1274 const sp<SourceClientDescriptor>& sourceDesc); 1275 /** 1276 * @brief releaseAudioPatchInternal internal function to remove an audio patch 1277 * @param[in] handle of the patch to be removed 1278 * @param[in] delayMs if required 1279 * @param[in] sourceDesc [optional] in case of external source, source client to be 1280 * unrouted from the patch, i.e. assigning an Output (HW or SW) 1281 * @return NO_ERROR if patch removed correctly, error code otherwise. 1282 */ 1283 status_t releaseAudioPatchInternal(audio_patch_handle_t handle, 1284 uint32_t delayMs = 0, 1285 const sp<SourceClientDescriptor>& sourceDesc = nullptr); 1286 1287 status_t installPatch(const char *caller, 1288 audio_patch_handle_t *patchHandle, 1289 AudioIODescriptorInterface *ioDescriptor, 1290 const struct audio_patch *patch, 1291 int delayMs); 1292 status_t installPatch(const char *caller, 1293 ssize_t index, 1294 audio_patch_handle_t *patchHandle, 1295 const struct audio_patch *patch, 1296 int delayMs, 1297 uid_t uid, 1298 sp<AudioPatch> *patchDescPtr); 1299 1300 bool areAllDevicesSupported( 1301 const AudioDeviceTypeAddrVector& devices, 1302 std::function<bool(audio_devices_t)> predicate, 1303 const char* context, 1304 bool matchAddress = true); 1305 1306 /** 1307 * @brief changeOutputDevicesMuteState mute/unmute devices using checkDeviceMuteStrategies 1308 * @param devices devices to mute/unmute 1309 */ 1310 void changeOutputDevicesMuteState(const AudioDeviceTypeAddrVector& devices); 1311 1312 /** 1313 * @brief Returns a vector of software output descriptor that support the queried devices 1314 * @param devices devices to query 1315 * @param openOutputs open outputs where the devices are supported as determined by 1316 * SwAudioOutputDescriptor::supportsAtLeastOne 1317 */ 1318 std::vector<sp<SwAudioOutputDescriptor>> getSoftwareOutputsForDevices( 1319 const AudioDeviceTypeAddrVector& devices) const; 1320 1321 bool isScoRequestedForComm() const; 1322 1323 bool isHearingAidUsedForComm() const; 1324 1325 bool areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output); 1326 1327 /** 1328 * @brief Opens an output stream from the supplied IOProfile and route it to the 1329 * supplied audio devices. If a mixer config is specified, it is forwarded to audio 1330 * flinger. If not, a default config is derived from the output stream config. 1331 * Also opens a duplicating output if needed and queries the audio HAL for supported 1332 * audio profiles if the IOProfile is dynamic. 1333 * @param[in] profile IOProfile to use as template 1334 * @param[in] devices initial route to apply to this output stream 1335 * @param[in] mixerConfig if not null, use this to configure the mixer 1336 * @param[in] halConfig if not null, use this to configure the HAL 1337 * @param[in] flags the flags to be used to open the output 1338 * @return an output descriptor for the newly opened stream or null in case of error. 1339 */ 1340 sp<SwAudioOutputDescriptor> openOutputWithProfileAndDevice( 1341 const sp<IOProfile>& profile, const DeviceVector& devices, 1342 const audio_config_base_t *mixerConfig = nullptr, 1343 const audio_config_t *halConfig = nullptr, 1344 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE); 1345 1346 bool isOffloadPossible(const audio_offload_info_t& offloadInfo, 1347 bool durationIgnored = false); 1348 1349 // adds the profiles from the outputProfile to the passed audioProfilesVector 1350 // without duplicating them if already present 1351 void addPortProfilesToVector(sp<IOProfile> outputProfile, 1352 AudioProfileVector& audioProfilesVector); 1353 1354 // Searches for a compatible profile with the sample rate, audio format and channel mask 1355 // in the list of passed HwModule(s). 1356 // returns a compatible profile if found, nullptr otherwise 1357 sp<IOProfile> searchCompatibleProfileHwModules ( 1358 const HwModuleCollection& hwModules, 1359 const DeviceVector& devices, 1360 uint32_t samplingRate, 1361 audio_format_t format, 1362 audio_channel_mask_t channelMask, 1363 audio_output_flags_t flags, 1364 bool directOnly); 1365 1366 // Filters only the relevant flags for getProfileForOutput 1367 audio_output_flags_t getRelevantFlags (audio_output_flags_t flags, bool directOnly); 1368 1369 status_t getDevicesForAttributes(const audio_attributes_t &attr, 1370 DeviceVector &devices, 1371 bool forVolume); 1372 1373 // A helper method used by getDevicesForAttributes to retrieve input devices when 1374 // capture preset is available in the given audio attributes parameter. 1375 status_t getInputDevicesForAttributes(const audio_attributes_t &attr, 1376 DeviceVector &devices); 1377 1378 status_t getProfilesForDevices(const DeviceVector& devices, 1379 AudioProfileVector& audioProfiles, 1380 uint32_t flags, 1381 bool isInput); 1382 1383 /** 1384 * Returns the preferred mixer attributes info for the given device port id and strategy. 1385 * Bit-perfect mixer attributes will be returned if it is active and 1386 * `activeBitPerfectPreferred` is true. 1387 */ 1388 sp<PreferredMixerAttributesInfo> getPreferredMixerAttributesInfo( 1389 audio_port_handle_t devicePortId, 1390 product_strategy_t strategy, 1391 bool activeBitPerfectPreferred = false); 1392 1393 sp<SwAudioOutputDescriptor> reopenOutput( 1394 sp<SwAudioOutputDescriptor> outputDesc, 1395 const audio_config_t *config, 1396 audio_output_flags_t flags, 1397 const char* caller); 1398 1399 void reopenOutputsWithDevices( 1400 const std::map<audio_io_handle_t, DeviceVector>& outputsToReopen); 1401 1402 PortHandleVector getClientsForStream(audio_stream_type_t streamType) const; 1403 void invalidateStreams(StreamTypeVector streams) const; 1404 1405 bool checkHapticCompatibilityOnSpatializerOutput(const audio_config_t* config, 1406 audio_session_t sessionId) const; 1407 1408 void updateClientsInternalMute(const sp<SwAudioOutputDescriptor>& desc); 1409 1410 float adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves, 1411 VolumeSource volumeSource, 1412 int index, 1413 const DeviceTypeSet &deviceTypes); 1414 1415 status_t updateMmapPolicyInfos(media::audio::common::AudioMMapPolicyType policyType); 1416 1417 // Contains for devices that support absolute volume the audio attributes 1418 // corresponding to the streams that are driving the volume changes 1419 std::unordered_map<audio_devices_t, audio_attributes_t> mAbsoluteVolumeDrivingStreams; 1420 1421 std::map<media::audio::common::AudioMMapPolicyType, 1422 const std::vector<media::audio::common::AudioMMapPolicyInfo>> mMmapPolicyInfos; 1423 std::map<media::audio::common::AudioMMapPolicyType, 1424 const std::map<media::audio::common::AudioDeviceDescription, 1425 media::audio::common::AudioMMapPolicy>> mMmapPolicyByDeviceType; 1426 }; 1427 1428 }; 1429