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