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