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