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