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