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