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