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 virtual bool canBeSpatialized(const audio_attributes_t *attr, 360 const audio_config_t *config, 361 const AudioDeviceTypeAddrVector &devices) const; 362 363 virtual status_t getSpatializerOutput(const audio_config_base_t *config, 364 const audio_attributes_t *attr, 365 audio_io_handle_t *output); 366 367 virtual status_t releaseSpatializerOutput(audio_io_handle_t output); 368 369 bool isCallScreenModeSupported() override; 370 371 void onNewAudioModulesAvailable() override; 372 373 status_t initialize(); 374 375 protected: 376 // A constructor that allows more fine-grained control over initialization process, 377 // used in automatic tests. 378 AudioPolicyManager(AudioPolicyClientInterface *clientInterface, bool forTesting); 379 380 // These methods should be used when finer control over APM initialization 381 // is needed, e.g. in tests. Must be used in conjunction with the constructor 382 // that only performs fields initialization. The public constructor comprises 383 // these steps in the following sequence: 384 // - field initializing constructor; 385 // - loadConfig; 386 // - initialize. getConfig()387 AudioPolicyConfig& getConfig() { return mConfig; } 388 void loadConfig(); 389 390 // From AudioPolicyManagerObserver getAudioPatches()391 virtual const AudioPatchCollection &getAudioPatches() const 392 { 393 return mAudioPatches; 394 } getSoundTriggerSessionCollection()395 virtual const SoundTriggerSessionCollection &getSoundTriggerSessionCollection() const 396 { 397 return mSoundTriggerSessions; 398 } getAudioPolicyMixCollection()399 virtual const AudioPolicyMixCollection &getAudioPolicyMixCollection() const 400 { 401 return mPolicyMixes; 402 } getOutputs()403 virtual const SwAudioOutputCollection &getOutputs() const 404 { 405 return mOutputs; 406 } getInputs()407 virtual const AudioInputCollection &getInputs() const 408 { 409 return mInputs; 410 } getAvailableOutputDevices()411 virtual const DeviceVector getAvailableOutputDevices() const 412 { 413 return mAvailableOutputDevices.filterForEngine(); 414 } getAvailableInputDevices()415 virtual const DeviceVector getAvailableInputDevices() const 416 { 417 // legacy and non-legacy remote-submix are managed by the engine, do not filter 418 return mAvailableInputDevices; 419 } getDefaultOutputDevice()420 virtual const sp<DeviceDescriptor> &getDefaultOutputDevice() const 421 { 422 return mDefaultOutputDevice; 423 } 424 getVolumeGroups()425 std::vector<volume_group_t> getVolumeGroups() const 426 { 427 return mEngine->getVolumeGroups(); 428 } 429 toVolumeSource(volume_group_t volumeGroup)430 VolumeSource toVolumeSource(volume_group_t volumeGroup) const 431 { 432 return static_cast<VolumeSource>(volumeGroup); 433 } toVolumeSource(const audio_attributes_t & attributes)434 VolumeSource toVolumeSource(const audio_attributes_t &attributes) const 435 { 436 return toVolumeSource(mEngine->getVolumeGroupForAttributes(attributes)); 437 } toVolumeSource(audio_stream_type_t stream)438 VolumeSource toVolumeSource(audio_stream_type_t stream) const 439 { 440 return toVolumeSource(mEngine->getVolumeGroupForStreamType(stream)); 441 } getVolumeCurves(VolumeSource volumeSource)442 IVolumeCurves &getVolumeCurves(VolumeSource volumeSource) 443 { 444 auto *curves = mEngine->getVolumeCurvesForVolumeGroup( 445 static_cast<volume_group_t>(volumeSource)); 446 ALOG_ASSERT(curves != nullptr, "No curves for volume source %d", volumeSource); 447 return *curves; 448 } getVolumeCurves(const audio_attributes_t & attr)449 IVolumeCurves &getVolumeCurves(const audio_attributes_t &attr) 450 { 451 auto *curves = mEngine->getVolumeCurvesForAttributes(attr); 452 ALOG_ASSERT(curves != nullptr, "No curves for attributes %s", toString(attr).c_str()); 453 return *curves; 454 } getVolumeCurves(audio_stream_type_t stream)455 IVolumeCurves &getVolumeCurves(audio_stream_type_t stream) 456 { 457 auto *curves = mEngine->getVolumeCurvesForStreamType(stream); 458 ALOG_ASSERT(curves != nullptr, "No curves for stream %s", toString(stream).c_str()); 459 return *curves; 460 } 461 462 void addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc); 463 void removeOutput(audio_io_handle_t output); 464 void addInput(audio_io_handle_t input, const sp<AudioInputDescriptor>& inputDesc); 465 466 // change the route of the specified output. Returns the number of ms we have slept to 467 // allow new routing to take effect in certain cases. 468 uint32_t setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc, 469 const DeviceVector &device, 470 bool force = false, 471 int delayMs = 0, 472 audio_patch_handle_t *patchHandle = NULL, 473 bool requiresMuteCheck = true); 474 status_t resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc, 475 int delayMs = 0, 476 audio_patch_handle_t *patchHandle = NULL); 477 status_t setInputDevice(audio_io_handle_t input, 478 const sp<DeviceDescriptor> &device, 479 bool force = false, 480 audio_patch_handle_t *patchHandle = NULL); 481 status_t resetInputDevice(audio_io_handle_t input, 482 audio_patch_handle_t *patchHandle = NULL); 483 484 // compute the actual volume for a given stream according to the requested index and a particular 485 // device 486 virtual float computeVolume(IVolumeCurves &curves, 487 VolumeSource volumeSource, 488 int index, 489 const DeviceTypeSet& deviceTypes); 490 491 // rescale volume index from srcStream within range of dstStream 492 int rescaleVolumeIndex(int srcIndex, 493 VolumeSource fromVolumeSource, 494 VolumeSource toVolumeSource); 495 // check that volume change is permitted, compute and send new volume to audio hardware 496 virtual status_t checkAndSetVolume(IVolumeCurves &curves, 497 VolumeSource volumeSource, int index, 498 const sp<AudioOutputDescriptor>& outputDesc, 499 DeviceTypeSet deviceTypes, 500 int delayMs = 0, bool force = false); 501 502 // apply all stream volumes to the specified output and device 503 void applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc, 504 const DeviceTypeSet& deviceTypes, 505 int delayMs = 0, bool force = false); 506 507 /** 508 * @brief setStrategyMute Mute or unmute all active clients on the considered output 509 * following the given strategy. 510 * @param strategy to be considered 511 * @param on true for mute, false for unmute 512 * @param outputDesc to be considered 513 * @param delayMs 514 * @param device 515 */ 516 void setStrategyMute(product_strategy_t strategy, 517 bool on, 518 const sp<AudioOutputDescriptor>& outputDesc, 519 int delayMs = 0, 520 DeviceTypeSet deviceTypes = DeviceTypeSet()); 521 522 /** 523 * @brief setVolumeSourceMute Mute or unmute the volume source on the specified output 524 * @param volumeSource to be muted/unmute (may host legacy streams or by extension set of 525 * audio attributes) 526 * @param on true to mute, false to umute 527 * @param outputDesc on which the client following the volume group shall be muted/umuted 528 * @param delayMs 529 * @param device 530 */ 531 void setVolumeSourceMute(VolumeSource volumeSource, 532 bool on, 533 const sp<AudioOutputDescriptor>& outputDesc, 534 int delayMs = 0, 535 DeviceTypeSet deviceTypes = DeviceTypeSet()); 536 537 audio_mode_t getPhoneState(); 538 539 // true if device is in a telephony or VoIP call 540 virtual bool isInCall(); 541 // true if given state represents a device in a telephony or VoIP call 542 virtual bool isStateInCall(int state); 543 // true if playback to call TX or capture from call RX is possible 544 bool isCallAudioAccessible(); 545 546 // when a device is connected, checks if an open output can be routed 547 // to this device. If none is open, tries to open one of the available outputs. 548 // Returns an output suitable to this device or 0. 549 // when a device is disconnected, checks if an output is not used any more and 550 // returns its handle if any. 551 // transfers the audio tracks and effects from one output thread to another accordingly. 552 status_t checkOutputsForDevice(const sp<DeviceDescriptor>& device, 553 audio_policy_dev_state_t state, 554 SortedVector<audio_io_handle_t>& outputs); 555 556 status_t checkInputsForDevice(const sp<DeviceDescriptor>& device, 557 audio_policy_dev_state_t state); 558 559 // close an output and its companion duplicating output. 560 void closeOutput(audio_io_handle_t output); 561 562 // close an input. 563 void closeInput(audio_io_handle_t input); 564 565 // runs all the checks required for accommodating changes in devices and outputs 566 // if 'onOutputsChecked' callback is provided, it is executed after the outputs 567 // check via 'checkOutputForAllStrategies'. If the callback returns 'true', 568 // A2DP suspend status is rechecked. 569 void checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked = nullptr); 570 571 /** 572 * @brief updates routing for all outputs (including call if call in progress). 573 * @param delayMs delay for unmuting if required 574 */ 575 void updateCallAndOutputRouting(bool forceVolumeReeval = true, uint32_t delayMs = 0); 576 isCallRxAudioSource(const sp<SourceClientDescriptor> & source)577 bool isCallRxAudioSource(const sp<SourceClientDescriptor> &source) { 578 return mCallRxSourceClientPort != AUDIO_PORT_HANDLE_NONE 579 && source == mAudioSources.valueFor(mCallRxSourceClientPort); 580 } 581 582 void connectTelephonyRxAudioSource(); 583 584 void disconnectTelephonyRxAudioSource(); 585 586 /** 587 * @brief updates routing for all inputs. 588 */ 589 void updateInputRouting(); 590 591 /** 592 * @brief checkOutputForAttributes checks and if necessary changes outputs used for the 593 * given audio attributes. 594 * must be called every time a condition that affects the output choice for a given 595 * attributes changes: connected device, phone state, force use... 596 * Must be called before updateDevicesAndOutputs() 597 * @param attr to be considered 598 */ 599 void checkOutputForAttributes(const audio_attributes_t &attr); 600 601 /** 602 * @brief checkAudioSourceForAttributes checks if any AudioSource following the same routing 603 * as the given audio attributes is not routed and try to connect it. 604 * It must be called once checkOutputForAttributes has been called for orphans AudioSource, 605 * aka AudioSource not attached to any Audio Output (e.g. AudioSource connected to direct 606 * Output which has been disconnected (and output closed) due to sink device unavailable). 607 * @param attr to be considered 608 */ 609 void checkAudioSourceForAttributes(const audio_attributes_t &attr); 610 611 bool followsSameRouting(const audio_attributes_t &lAttr, 612 const audio_attributes_t &rAttr) const; 613 614 /** 615 * @brief checkOutputForAllStrategies Same as @see checkOutputForAttributes() 616 * but for a all product strategies in order of priority 617 */ 618 void checkOutputForAllStrategies(); 619 620 // Same as checkOutputForStrategy but for secondary outputs. Make sure if a secondary 621 // output condition changes, the track is properly rerouted 622 void checkSecondaryOutputs(); 623 624 // manages A2DP output suspend/restore according to phone state and BT SCO usage 625 void checkA2dpSuspend(); 626 627 // selects the most appropriate device on output for current state 628 // must be called every time a condition that affects the device choice for a given output is 629 // changed: connected device, phone state, force use, output start, output stop.. 630 // see getDeviceForStrategy() for the use of fromCache parameter 631 DeviceVector getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc, 632 bool fromCache); 633 634 /** 635 * @brief updateDevicesAndOutputs: updates cache of devices of the engine 636 * must be called every time a condition that affects the device choice is changed: 637 * connected device, phone state, force use... 638 * cached values are used by getOutputDevicesForStream()/getDevicesForAttributes if 639 * parameter fromCache is true. 640 * Must be called after checkOutputForAllStrategies() 641 */ 642 void updateDevicesAndOutputs(); 643 644 // selects the most appropriate device on input for current state 645 sp<DeviceDescriptor> getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc); 646 getMaxEffectsCpuLoad()647 virtual uint32_t getMaxEffectsCpuLoad() 648 { 649 return mEffects.getMaxEffectsCpuLoad(); 650 } 651 getMaxEffectsMemory()652 virtual uint32_t getMaxEffectsMemory() 653 { 654 return mEffects.getMaxEffectsMemory(); 655 } 656 657 SortedVector<audio_io_handle_t> getOutputsForDevices( 658 const DeviceVector &devices, const SwAudioOutputCollection& openOutputs); 659 660 /** 661 * @brief checkDeviceMuteStrategies mute/unmute strategies 662 * using an incompatible device combination. 663 * if muting, wait for the audio in pcm buffer to be drained before proceeding 664 * if unmuting, unmute only after the specified delay 665 * @param outputDesc 666 * @param prevDevice 667 * @param delayMs 668 * @return the number of ms waited 669 */ 670 virtual uint32_t checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc, 671 const DeviceVector &prevDevices, 672 uint32_t delayMs); 673 674 audio_io_handle_t selectOutput(const SortedVector<audio_io_handle_t>& outputs, 675 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE, 676 audio_format_t format = AUDIO_FORMAT_INVALID, 677 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE, 678 uint32_t samplingRate = 0, 679 audio_session_t sessionId = AUDIO_SESSION_NONE); 680 // samplingRate, format, channelMask are in/out and so may be modified 681 sp<IOProfile> getInputProfile(const sp<DeviceDescriptor> & device, 682 uint32_t& samplingRate, 683 audio_format_t& format, 684 audio_channel_mask_t& channelMask, 685 audio_input_flags_t flags); 686 /** 687 * @brief getProfileForOutput 688 * @param devices vector of descriptors, may be empty if ignoring the device is required 689 * @param samplingRate 690 * @param format 691 * @param channelMask 692 * @param flags 693 * @param directOnly 694 * @return IOProfile to be used if found, nullptr otherwise 695 */ 696 sp<IOProfile> getProfileForOutput(const DeviceVector &devices, 697 uint32_t samplingRate, 698 audio_format_t format, 699 audio_channel_mask_t channelMask, 700 audio_output_flags_t flags, 701 bool directOnly); 702 703 audio_io_handle_t selectOutputForMusicEffects(); 704 addAudioPatch(audio_patch_handle_t handle,const sp<AudioPatch> & patch)705 virtual status_t addAudioPatch(audio_patch_handle_t handle, const sp<AudioPatch>& patch) 706 { 707 return mAudioPatches.addAudioPatch(handle, patch); 708 } removeAudioPatch(audio_patch_handle_t handle)709 virtual status_t removeAudioPatch(audio_patch_handle_t handle) 710 { 711 return mAudioPatches.removeAudioPatch(handle); 712 } 713 isPrimaryModule(const sp<HwModule> & module)714 bool isPrimaryModule(const sp<HwModule> &module) const 715 { 716 if (module == 0 || !hasPrimaryOutput()) { 717 return false; 718 } 719 return module->getHandle() == mPrimaryOutput->getModuleHandle(); 720 } availablePrimaryOutputDevices()721 DeviceVector availablePrimaryOutputDevices() const 722 { 723 if (!hasPrimaryOutput()) { 724 return DeviceVector(); 725 } 726 return mAvailableOutputDevices.filter(mPrimaryOutput->supportedDevices()); 727 } availablePrimaryModuleInputDevices()728 DeviceVector availablePrimaryModuleInputDevices() const 729 { 730 if (!hasPrimaryOutput()) { 731 return DeviceVector(); 732 } 733 return mAvailableInputDevices.getDevicesFromHwModule( 734 mPrimaryOutput->getModuleHandle()); 735 } 736 /** 737 * @brief getFirstDeviceId of the Device Vector 738 * @return if the collection is not empty, it returns the first device Id, 739 * otherwise AUDIO_PORT_HANDLE_NONE 740 */ getFirstDeviceId(const DeviceVector & devices)741 audio_port_handle_t getFirstDeviceId(const DeviceVector &devices) const 742 { 743 return (devices.size() > 0) ? devices.itemAt(0)->getId() : AUDIO_PORT_HANDLE_NONE; 744 } getFirstDeviceAddress(const DeviceVector & devices)745 String8 getFirstDeviceAddress(const DeviceVector &devices) const 746 { 747 return (devices.size() > 0) ? 748 String8(devices.itemAt(0)->address().c_str()) : String8(""); 749 } 750 751 status_t updateCallRouting( 752 bool fromCache, uint32_t delayMs = 0, uint32_t *waitMs = nullptr); 753 status_t updateCallRoutingInternal( 754 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs); 755 sp<AudioPatch> createTelephonyPatch(bool isRx, const sp<DeviceDescriptor> &device, 756 uint32_t delayMs); 757 /** 758 * @brief selectBestRxSinkDevicesForCall: if the primary module host both Telephony Rx/Tx 759 * devices, and it declares also supporting a HW bridge between the Telephony Rx and the 760 * given sink device for Voice Call audio attributes, select this device in prio. 761 * Otherwise, getNewOutputDevices() is called on the primary output to select sink device. 762 * @param fromCache true to prevent engine reconsidering all product strategies and retrieve 763 * from engine cache. 764 * @return vector of devices, empty if none is found. 765 */ 766 DeviceVector selectBestRxSinkDevicesForCall(bool fromCache); 767 bool isDeviceOfModule(const sp<DeviceDescriptor>& devDesc, const char *moduleId) const; 768 769 status_t startSource(const sp<SwAudioOutputDescriptor>& outputDesc, 770 const sp<TrackClientDescriptor>& client, 771 uint32_t *delayMs); 772 status_t stopSource(const sp<SwAudioOutputDescriptor>& outputDesc, 773 const sp<TrackClientDescriptor>& client); 774 775 void clearAudioPatches(uid_t uid); 776 void clearSessionRoutes(uid_t uid); 777 778 /** 779 * @brief checkStrategyRoute: when an output is beeing rerouted, reconsider each output 780 * that may host a strategy playing on the considered output. 781 * @param ps product strategy that initiated the rerouting 782 * @param ouptutToSkip output that initiated the rerouting 783 */ 784 void checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip); 785 hasPrimaryOutput()786 status_t hasPrimaryOutput() const { return mPrimaryOutput != 0; } 787 788 status_t connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc); 789 status_t disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc); 790 791 sp<SourceClientDescriptor> getSourceForAttributesOnOutput(audio_io_handle_t output, 792 const audio_attributes_t &attr); 793 void clearAudioSourcesForOutput(audio_io_handle_t output); 794 795 void cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc); 796 797 void clearAudioSources(uid_t uid); 798 799 static bool streamsMatchForvolume(audio_stream_type_t stream1, 800 audio_stream_type_t stream2); 801 802 void closeActiveClients(const sp<AudioInputDescriptor>& input); 803 void closeClient(audio_port_handle_t portId); 804 805 const uid_t mUidCached; // AID_AUDIOSERVER 806 AudioPolicyClientInterface *mpClientInterface; // audio policy client interface 807 sp<SwAudioOutputDescriptor> mPrimaryOutput; // primary output descriptor 808 // list of descriptors for outputs currently opened 809 810 sp<SwAudioOutputDescriptor> mSpatializerOutput; 811 812 SwAudioOutputCollection mOutputs; 813 // copy of mOutputs before setDeviceConnectionState() opens new outputs 814 // reset to mOutputs when updateDevicesAndOutputs() is called. 815 SwAudioOutputCollection mPreviousOutputs; 816 AudioInputCollection mInputs; // list of input descriptors 817 818 DeviceVector mOutputDevicesAll; // all output devices from the config 819 DeviceVector mInputDevicesAll; // all input devices from the config 820 DeviceVector mAvailableOutputDevices; // all available output devices 821 DeviceVector mAvailableInputDevices; // all available input devices 822 823 bool mLimitRingtoneVolume; // limit ringtone volume to music volume if headset connected 824 825 float mLastVoiceVolume; // last voice volume value sent to audio HAL 826 bool mA2dpSuspended; // true if A2DP output is suspended 827 828 EffectDescriptorCollection mEffects; // list of registered audio effects 829 sp<DeviceDescriptor> mDefaultOutputDevice; // output device selected by default at boot time 830 HwModuleCollection mHwModules; // contains modules that have been loaded successfully 831 HwModuleCollection mHwModulesAll; // contains all modules declared in the config 832 833 AudioPolicyConfig mConfig; 834 835 std::atomic<uint32_t> mAudioPortGeneration; 836 837 AudioPatchCollection mAudioPatches; 838 839 SoundTriggerSessionCollection mSoundTriggerSessions; 840 841 sp<AudioPatch> mCallTxPatch; 842 843 HwAudioOutputCollection mHwOutputs; 844 SourceClientCollection mAudioSources; 845 846 // for supporting "beacon" streams, i.e. streams that only play on speaker, and never 847 // when something other than STREAM_TTS (a.k.a. "Transmitted Through Speaker") is playing 848 enum { 849 STARTING_OUTPUT, 850 STARTING_BEACON, 851 STOPPING_OUTPUT, 852 STOPPING_BEACON 853 }; 854 uint32_t mBeaconMuteRefCount; // ref count for stream that would mute beacon 855 uint32_t mBeaconPlayingRefCount;// ref count for the playing beacon streams 856 bool mBeaconMuted; // has STREAM_TTS been muted 857 bool mTtsOutputAvailable; // true if a dedicated output for TTS stream is available 858 859 bool mMasterMono; // true if we wish to force all outputs to mono 860 AudioPolicyMixCollection mPolicyMixes; // list of registered mixes 861 audio_io_handle_t mMusicEffectOutput; // output selected for music effects 862 863 uint32_t nextAudioPortGeneration(); 864 865 // Audio Policy Engine Interface. 866 EngineInstance mEngine; 867 868 // Surround formats that are enabled manually. Taken into account when 869 // "encoded surround" is forced into "manual" mode. 870 std::unordered_set<audio_format_t> mManualSurroundFormats; 871 872 std::unordered_map<uid_t, audio_flags_mask_t> mAllowedCapturePolicies; 873 874 // The map of device descriptor and formats reported by the device. 875 std::map<wp<DeviceDescriptor>, FormatVector> mReportedFormatsMap; 876 877 // Cached product strategy ID corresponding to legacy strategy STRATEGY_PHONE 878 product_strategy_t mCommunnicationStrategy; 879 880 // The port handle of the hardware audio source created internally for the Call RX audio 881 // end point. 882 audio_port_handle_t mCallRxSourceClientPort = AUDIO_PORT_HANDLE_NONE; 883 884 // Support for Multi-Stream Decoder (MSD) module 885 sp<DeviceDescriptor> getMsdAudioInDevice() const; 886 DeviceVector getMsdAudioOutDevices() const; 887 const AudioPatchCollection getMsdOutputPatches() const; 888 status_t getMsdProfiles(bool hwAvSync, 889 const InputProfileCollection &inputProfiles, 890 const OutputProfileCollection &outputProfiles, 891 const sp<DeviceDescriptor> &sourceDevice, 892 const sp<DeviceDescriptor> &sinkDevice, 893 AudioProfileVector &sourceProfiles, 894 AudioProfileVector &sinkProfiles) const; 895 status_t getBestMsdConfig(bool hwAvSync, 896 const AudioProfileVector &sourceProfiles, 897 const AudioProfileVector &sinkProfiles, 898 audio_port_config *sourceConfig, 899 audio_port_config *sinkConfig) const; 900 PatchBuilder buildMsdPatch(bool msdIsSource, const sp<DeviceDescriptor> &device) const; 901 status_t setMsdOutputPatches(const DeviceVector *outputDevices = nullptr); 902 void releaseMsdOutputPatches(const DeviceVector& devices); 903 private: 904 void onNewAudioModulesAvailableInt(DeviceVector *newDevices); 905 906 // Add or remove AC3 DTS encodings based on user preferences. 907 void modifySurroundFormats(const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr); 908 void modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr); 909 910 // If any, resolve any "dynamic" fields of an Audio Profiles collection 911 void updateAudioProfiles(const sp<DeviceDescriptor>& devDesc, audio_io_handle_t ioHandle, 912 AudioProfileVector &profiles); 913 914 // Notify the policy client of any change of device state with AUDIO_IO_HANDLE_NONE, 915 // so that the client interprets it as global to audio hardware interfaces. 916 // It can give a chance to HAL implementer to retrieve dynamic capabilities associated 917 // to this device for example. 918 // TODO avoid opening stream to retrieve capabilities of a profile. 919 void broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device, 920 audio_policy_dev_state_t state); 921 922 // updates device caching and output for streams that can influence the 923 // routing of notifications 924 void handleNotificationRoutingForStream(audio_stream_type_t stream); curAudioPortGeneration()925 uint32_t curAudioPortGeneration() const { return mAudioPortGeneration; } 926 // internal method, get audio_attributes_t from either a source audio_attributes_t 927 // or audio_stream_type_t, respectively. 928 status_t getAudioAttributes(audio_attributes_t *dstAttr, 929 const audio_attributes_t *srcAttr, 930 audio_stream_type_t srcStream); 931 // internal method, called by getOutputForAttr() and connectAudioSource. 932 status_t getOutputForAttrInt(audio_attributes_t *resultAttr, 933 audio_io_handle_t *output, 934 audio_session_t session, 935 const audio_attributes_t *attr, 936 audio_stream_type_t *stream, 937 uid_t uid, 938 const audio_config_t *config, 939 audio_output_flags_t *flags, 940 audio_port_handle_t *selectedDeviceId, 941 bool *isRequestedDeviceForExclusiveUse, 942 std::vector<sp<AudioPolicyMix>> *secondaryMixes, 943 output_type_t *outputType); 944 // internal method to return the output handle for the given device and format 945 audio_io_handle_t getOutputForDevices( 946 const DeviceVector &devices, 947 audio_session_t session, 948 const audio_attributes_t *attr, 949 const audio_config_t *config, 950 audio_output_flags_t *flags, 951 bool forceMutingHaptic = false); 952 953 // Internal method checking if a direct output can be opened matching the requested 954 // attributes, flags, config and devices. 955 // If NAME_NOT_FOUND is returned, an attempt can be made to open a mixed output. 956 status_t openDirectOutput( 957 audio_stream_type_t stream, 958 audio_session_t session, 959 const audio_config_t *config, 960 audio_output_flags_t flags, 961 const DeviceVector &devices, 962 audio_io_handle_t *output); 963 964 sp<IOProfile> getSpatializerOutputProfile(const audio_config_t *config, 965 const AudioDeviceTypeAddrVector &devices) const; 966 967 static bool isChannelMaskSpatialized(audio_channel_mask_t channels); 968 969 void checkVirtualizerClientRoutes(); 970 971 /** 972 * @brief getInputForDevice selects an input handle for a given input device and 973 * requester context 974 * @param device to be used by requester, selected by policy mix rules or engine 975 * @param session requester session id 976 * @param uid requester uid 977 * @param attributes requester audio attributes (e.g. input source and tags matter) 978 * @param config requester audio configuration (e.g. sample rate, format, channel mask). 979 * @param flags requester input flags 980 * @param policyMix may be null, policy rules to be followed by the requester 981 * @return input io handle aka unique input identifier selected for this device. 982 */ 983 audio_io_handle_t getInputForDevice(const sp<DeviceDescriptor> &device, 984 audio_session_t session, 985 const audio_attributes_t &attributes, 986 const audio_config_base_t *config, 987 audio_input_flags_t flags, 988 const sp<AudioPolicyMix> &policyMix); 989 990 // event is one of STARTING_OUTPUT, STARTING_BEACON, STOPPING_OUTPUT, STOPPING_BEACON 991 // returns 0 if no mute/unmute event happened, the largest latency of the device where 992 // the mute/unmute happened 993 uint32_t handleEventForBeacon(int event); 994 uint32_t setBeaconMute(bool mute); 995 bool isValidAttributes(const audio_attributes_t *paa); 996 997 // Called by setDeviceConnectionState(). 998 status_t setDeviceConnectionStateInt(audio_devices_t deviceType, 999 audio_policy_dev_state_t state, 1000 const char *device_address, 1001 const char *device_name, 1002 audio_format_t encodedFormat); 1003 status_t setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device, 1004 audio_policy_dev_state_t state); 1005 1006 void setEngineDeviceConnectionState(const sp<DeviceDescriptor> device, 1007 audio_policy_dev_state_t state); 1008 updateMono(audio_io_handle_t output)1009 void updateMono(audio_io_handle_t output) { 1010 AudioParameter param; 1011 param.addInt(String8(AudioParameter::keyMonoOutput), (int)mMasterMono); 1012 mpClientInterface->setParameters(output, param.toString()); 1013 } 1014 1015 /** 1016 * @brief createAudioPatchInternal internal function to manage audio patch creation 1017 * @param[in] patch structure containing sink and source ports configuration 1018 * @param[out] handle patch handle to be provided if patch installed correctly 1019 * @param[in] uid of the client 1020 * @param[in] delayMs if required 1021 * @param[in] sourceDesc [optional] in case of external source, source client to be 1022 * configured by the patch, i.e. assigning an Output (HW or SW) 1023 * @return NO_ERROR if patch installed correctly, error code otherwise. 1024 */ 1025 status_t createAudioPatchInternal(const struct audio_patch *patch, 1026 audio_patch_handle_t *handle, 1027 uid_t uid, uint32_t delayMs = 0, 1028 const sp<SourceClientDescriptor>& sourceDesc = nullptr); 1029 /** 1030 * @brief releaseAudioPatchInternal internal function to remove an audio patch 1031 * @param[in] handle of the patch to be removed 1032 * @param[in] delayMs if required 1033 * @return NO_ERROR if patch removed correctly, error code otherwise. 1034 */ 1035 status_t releaseAudioPatchInternal(audio_patch_handle_t handle, uint32_t delayMs = 0); 1036 1037 status_t installPatch(const char *caller, 1038 audio_patch_handle_t *patchHandle, 1039 AudioIODescriptorInterface *ioDescriptor, 1040 const struct audio_patch *patch, 1041 int delayMs); 1042 status_t installPatch(const char *caller, 1043 ssize_t index, 1044 audio_patch_handle_t *patchHandle, 1045 const struct audio_patch *patch, 1046 int delayMs, 1047 uid_t uid, 1048 sp<AudioPatch> *patchDescPtr); 1049 1050 bool areAllDevicesSupported( 1051 const AudioDeviceTypeAddrVector& devices, 1052 std::function<bool(audio_devices_t)> predicate, 1053 const char* context); 1054 1055 bool isScoRequestedForComm() const; 1056 1057 bool areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output); 1058 1059 sp<SwAudioOutputDescriptor> openOutputWithProfileAndDevice(const sp<IOProfile>& profile, 1060 const DeviceVector& devices); 1061 1062 }; 1063 1064 }; 1065