AudioPolicyManager.h revision df37269852ea92bafd939fe793209d0581c4a574
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 <stdint.h>
20#include <sys/types.h>
21#include <cutils/config_utils.h>
22#include <cutils/misc.h>
23#include <utils/Timers.h>
24#include <utils/Errors.h>
25#include <utils/KeyedVector.h>
26#include <utils/SortedVector.h>
27#include <media/AudioPolicy.h>
28#include "AudioPolicyInterface.h"
29
30#include <AudioGain.h>
31#include <AudioPort.h>
32#include <AudioPatch.h>
33#include <ConfigParsingUtils.h>
34#include <DeviceDescriptor.h>
35#include <IOProfile.h>
36#include <HwModule.h>
37#include <AudioInputDescriptor.h>
38#include <AudioOutputDescriptor.h>
39#include <AudioPolicyMix.h>
40#include <EffectDescriptor.h>
41#include <SoundTriggerSession.h>
42
43namespace android {
44
45// ----------------------------------------------------------------------------
46
47// Attenuation applied to STRATEGY_SONIFICATION streams when a headset is connected: 6dB
48#define SONIFICATION_HEADSET_VOLUME_FACTOR 0.5
49// Min volume for STRATEGY_SONIFICATION streams when limited by music volume: -36dB
50#define SONIFICATION_HEADSET_VOLUME_MIN  0.016
51// Time in milliseconds during which we consider that music is still active after a music
52// track was stopped - see computeVolume()
53#define SONIFICATION_HEADSET_MUSIC_DELAY  5000
54// Time in milliseconds after media stopped playing during which we consider that the
55// sonification should be as unobtrusive as during the time media was playing.
56#define SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY 5000
57// Time in milliseconds during witch some streams are muted while the audio path
58// is switched
59#define MUTE_TIME_MS 2000
60
61#define NUM_TEST_OUTPUTS 5
62
63#define NUM_VOL_CURVE_KNEES 2
64
65// Default minimum length allowed for offloading a compressed track
66// Can be overridden by the audio.offload.min.duration.secs property
67#define OFFLOAD_DEFAULT_MIN_DURATION_SECS 60
68
69// ----------------------------------------------------------------------------
70// AudioPolicyManager implements audio policy manager behavior common to all platforms.
71// ----------------------------------------------------------------------------
72
73class AudioPolicyManager: public AudioPolicyInterface
74#ifdef AUDIO_POLICY_TEST
75    , public Thread
76#endif //AUDIO_POLICY_TEST
77{
78
79public:
80                AudioPolicyManager(AudioPolicyClientInterface *clientInterface);
81        virtual ~AudioPolicyManager();
82
83        // AudioPolicyInterface
84        virtual status_t setDeviceConnectionState(audio_devices_t device,
85                                                          audio_policy_dev_state_t state,
86                                                          const char *device_address,
87                                                          const char *device_name);
88        virtual audio_policy_dev_state_t getDeviceConnectionState(audio_devices_t device,
89                                                                              const char *device_address);
90        virtual void setPhoneState(audio_mode_t state);
91        virtual void setForceUse(audio_policy_force_use_t usage,
92                                 audio_policy_forced_cfg_t config);
93        virtual audio_policy_forced_cfg_t getForceUse(audio_policy_force_use_t usage);
94        virtual void setSystemProperty(const char* property, const char* value);
95        virtual status_t initCheck();
96        virtual audio_io_handle_t getOutput(audio_stream_type_t stream,
97                                            uint32_t samplingRate,
98                                            audio_format_t format,
99                                            audio_channel_mask_t channelMask,
100                                            audio_output_flags_t flags,
101                                            const audio_offload_info_t *offloadInfo);
102        virtual status_t getOutputForAttr(const audio_attributes_t *attr,
103                                          audio_io_handle_t *output,
104                                          audio_session_t session,
105                                          audio_stream_type_t *stream,
106                                          uint32_t samplingRate,
107                                          audio_format_t format,
108                                          audio_channel_mask_t channelMask,
109                                          audio_output_flags_t flags,
110                                          const audio_offload_info_t *offloadInfo);
111        virtual status_t startOutput(audio_io_handle_t output,
112                                     audio_stream_type_t stream,
113                                     audio_session_t session);
114        virtual status_t stopOutput(audio_io_handle_t output,
115                                    audio_stream_type_t stream,
116                                    audio_session_t session);
117        virtual void releaseOutput(audio_io_handle_t output,
118                                   audio_stream_type_t stream,
119                                   audio_session_t session);
120        virtual status_t getInputForAttr(const audio_attributes_t *attr,
121                                         audio_io_handle_t *input,
122                                         audio_session_t session,
123                                         uint32_t samplingRate,
124                                         audio_format_t format,
125                                         audio_channel_mask_t channelMask,
126                                         audio_input_flags_t flags,
127                                         input_type_t *inputType);
128
129        // indicates to the audio policy manager that the input starts being used.
130        virtual status_t startInput(audio_io_handle_t input,
131                                    audio_session_t session);
132
133        // indicates to the audio policy manager that the input stops being used.
134        virtual status_t stopInput(audio_io_handle_t input,
135                                   audio_session_t session);
136        virtual void releaseInput(audio_io_handle_t input,
137                                  audio_session_t session);
138        virtual void closeAllInputs();
139        virtual void initStreamVolume(audio_stream_type_t stream,
140                                                    int indexMin,
141                                                    int indexMax);
142        virtual status_t setStreamVolumeIndex(audio_stream_type_t stream,
143                                              int index,
144                                              audio_devices_t device);
145        virtual status_t getStreamVolumeIndex(audio_stream_type_t stream,
146                                              int *index,
147                                              audio_devices_t device);
148
149        // return the strategy corresponding to a given stream type
150        virtual uint32_t getStrategyForStream(audio_stream_type_t stream);
151        // return the strategy corresponding to the given audio attributes
152        virtual uint32_t getStrategyForAttr(const audio_attributes_t *attr);
153
154        // return the enabled output devices for the given stream type
155        virtual audio_devices_t getDevicesForStream(audio_stream_type_t stream);
156
157        virtual audio_io_handle_t getOutputForEffect(const effect_descriptor_t *desc = NULL);
158        virtual status_t registerEffect(const effect_descriptor_t *desc,
159                                        audio_io_handle_t io,
160                                        uint32_t strategy,
161                                        int session,
162                                        int id);
163        virtual status_t unregisterEffect(int id)
164        {
165            return mEffects.unregisterEffect(id);
166        }
167        virtual status_t setEffectEnabled(int id, bool enabled)
168        {
169            return mEffects.setEffectEnabled(id, enabled);
170        }
171
172        virtual bool isStreamActive(audio_stream_type_t stream, uint32_t inPastMs = 0) const
173        {
174            return mOutputs.isStreamActive(stream, inPastMs);
175        }
176        // return whether a stream is playing remotely, override to change the definition of
177        //   local/remote playback, used for instance by notification manager to not make
178        //   media players lose audio focus when not playing locally
179        //   For the base implementation, "remotely" means playing during screen mirroring which
180        //   uses an output for playback with a non-empty, non "0" address.
181        virtual bool isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs = 0) const
182        {
183            return mOutputs.isStreamActiveRemotely(stream, inPastMs);
184        }
185        virtual bool isSourceActive(audio_source_t source) const;
186
187        virtual status_t dump(int fd);
188
189        virtual bool isOffloadSupported(const audio_offload_info_t& offloadInfo);
190
191        virtual status_t listAudioPorts(audio_port_role_t role,
192                                        audio_port_type_t type,
193                                        unsigned int *num_ports,
194                                        struct audio_port *ports,
195                                        unsigned int *generation);
196        virtual status_t getAudioPort(struct audio_port *port);
197        virtual status_t createAudioPatch(const struct audio_patch *patch,
198                                           audio_patch_handle_t *handle,
199                                           uid_t uid);
200        virtual status_t releaseAudioPatch(audio_patch_handle_t handle,
201                                              uid_t uid);
202        virtual status_t listAudioPatches(unsigned int *num_patches,
203                                          struct audio_patch *patches,
204                                          unsigned int *generation);
205        virtual status_t setAudioPortConfig(const struct audio_port_config *config);
206        virtual void clearAudioPatches(uid_t uid);
207
208        virtual status_t acquireSoundTriggerSession(audio_session_t *session,
209                                               audio_io_handle_t *ioHandle,
210                                               audio_devices_t *device);
211
212        virtual status_t releaseSoundTriggerSession(audio_session_t session)
213        {
214            return mSoundTriggerSessions.releaseSession(session);
215        }
216
217        virtual status_t registerPolicyMixes(Vector<AudioMix> mixes);
218        virtual status_t unregisterPolicyMixes(Vector<AudioMix> mixes);
219
220        // Audio policy configuration file parsing (audio_policy.conf)
221        // TODO candidates to be moved to ConfigParsingUtils
222                void defaultAudioPolicyConfig(void);
223
224                // return the strategy corresponding to a given stream type
225                static routing_strategy getStrategy(audio_stream_type_t stream);
226protected:
227        void addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc);
228        void removeOutput(audio_io_handle_t output);
229        void addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc);
230
231        // return appropriate device for streams handled by the specified strategy according to current
232        // phone state, connected devices...
233        // if fromCache is true, the device is returned from mDeviceForStrategy[],
234        // otherwise it is determine by current state
235        // (device connected,phone state, force use, a2dp output...)
236        // This allows to:
237        //  1 speed up process when the state is stable (when starting or stopping an output)
238        //  2 access to either current device selection (fromCache == true) or
239        // "future" device selection (fromCache == false) when called from a context
240        //  where conditions are changing (setDeviceConnectionState(), setPhoneState()...) AND
241        //  before updateDevicesAndOutputs() is called.
242        virtual audio_devices_t getDeviceForStrategy(routing_strategy strategy,
243                                                     bool fromCache);
244
245        // change the route of the specified output. Returns the number of ms we have slept to
246        // allow new routing to take effect in certain cases.
247        virtual uint32_t setOutputDevice(audio_io_handle_t output,
248                             audio_devices_t device,
249                             bool force = false,
250                             int delayMs = 0,
251                             audio_patch_handle_t *patchHandle = NULL,
252                             const char* address = NULL);
253        status_t resetOutputDevice(audio_io_handle_t output,
254                                   int delayMs = 0,
255                                   audio_patch_handle_t *patchHandle = NULL);
256        status_t setInputDevice(audio_io_handle_t input,
257                                audio_devices_t device,
258                                bool force = false,
259                                audio_patch_handle_t *patchHandle = NULL);
260        status_t resetInputDevice(audio_io_handle_t input,
261                                  audio_patch_handle_t *patchHandle = NULL);
262
263        // select input device corresponding to requested audio source
264        virtual audio_devices_t getDeviceForInputSource(audio_source_t inputSource);
265
266        // initialize volume curves for each strategy and device category
267        void initializeVolumeCurves();
268
269        // compute the actual volume for a given stream according to the requested index and a particular
270        // device
271        virtual float computeVolume(audio_stream_type_t stream, int index,
272                                    audio_io_handle_t output, audio_devices_t device);
273
274        // check that volume change is permitted, compute and send new volume to audio hardware
275        virtual status_t checkAndSetVolume(audio_stream_type_t stream, int index,
276                                           audio_io_handle_t output,
277                                           audio_devices_t device,
278                                           int delayMs = 0, bool force = false);
279
280        // apply all stream volumes to the specified output and device
281        void applyStreamVolumes(audio_io_handle_t output, audio_devices_t device, int delayMs = 0, bool force = false);
282
283        // Mute or unmute all streams handled by the specified strategy on the specified output
284        void setStrategyMute(routing_strategy strategy,
285                             bool on,
286                             audio_io_handle_t output,
287                             int delayMs = 0,
288                             audio_devices_t device = (audio_devices_t)0);
289
290        // Mute or unmute the stream on the specified output
291        void setStreamMute(audio_stream_type_t stream,
292                           bool on,
293                           audio_io_handle_t output,
294                           int delayMs = 0,
295                           audio_devices_t device = (audio_devices_t)0);
296
297        // handle special cases for sonification strategy while in call: mute streams or replace by
298        // a special tone in the device used for communication
299        void handleIncallSonification(audio_stream_type_t stream, bool starting, bool stateChange);
300
301        // true if device is in a telephony or VoIP call
302        virtual bool isInCall();
303
304        // true if given state represents a device in a telephony or VoIP call
305        virtual bool isStateInCall(int state);
306
307        // when a device is connected, checks if an open output can be routed
308        // to this device. If none is open, tries to open one of the available outputs.
309        // Returns an output suitable to this device or 0.
310        // when a device is disconnected, checks if an output is not used any more and
311        // returns its handle if any.
312        // transfers the audio tracks and effects from one output thread to another accordingly.
313        status_t checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
314                                       audio_policy_dev_state_t state,
315                                       SortedVector<audio_io_handle_t>& outputs,
316                                       const String8 address);
317
318        status_t checkInputsForDevice(audio_devices_t device,
319                                      audio_policy_dev_state_t state,
320                                      SortedVector<audio_io_handle_t>& inputs,
321                                      const String8 address);
322
323        // close an output and its companion duplicating output.
324        void closeOutput(audio_io_handle_t output);
325
326        // close an input.
327        void closeInput(audio_io_handle_t input);
328
329        // checks and if necessary changes outputs used for all strategies.
330        // must be called every time a condition that affects the output choice for a given strategy
331        // changes: connected device, phone state, force use...
332        // Must be called before updateDevicesAndOutputs()
333        void checkOutputForStrategy(routing_strategy strategy);
334
335        // Same as checkOutputForStrategy() but for a all strategies in order of priority
336        void checkOutputForAllStrategies();
337
338        // manages A2DP output suspend/restore according to phone state and BT SCO usage
339        void checkA2dpSuspend();
340
341        // selects the most appropriate device on output for current state
342        // must be called every time a condition that affects the device choice for a given output is
343        // changed: connected device, phone state, force use, output start, output stop..
344        // see getDeviceForStrategy() for the use of fromCache parameter
345        audio_devices_t getNewOutputDevice(audio_io_handle_t output, bool fromCache);
346
347        // updates cache of device used by all strategies (mDeviceForStrategy[])
348        // must be called every time a condition that affects the device choice for a given strategy is
349        // changed: connected device, phone state, force use...
350        // cached values are used by getDeviceForStrategy() if parameter fromCache is true.
351         // Must be called after checkOutputForAllStrategies()
352        void updateDevicesAndOutputs();
353
354        // selects the most appropriate device on input for current state
355        audio_devices_t getNewInputDevice(audio_io_handle_t input);
356
357        virtual uint32_t getMaxEffectsCpuLoad()
358        {
359            return mEffects.getMaxEffectsCpuLoad();
360        }
361
362        virtual uint32_t getMaxEffectsMemory()
363        {
364            return mEffects.getMaxEffectsMemory();
365        }
366#ifdef AUDIO_POLICY_TEST
367        virtual     bool        threadLoop();
368                    void        exit();
369        int testOutputIndex(audio_io_handle_t output);
370#endif //AUDIO_POLICY_TEST
371
372        SortedVector<audio_io_handle_t> getOutputsForDevice(audio_devices_t device,
373                                                            AudioOutputCollection openOutputs);
374        bool vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
375                                           SortedVector<audio_io_handle_t>& outputs2);
376
377        // mute/unmute strategies using an incompatible device combination
378        // if muting, wait for the audio in pcm buffer to be drained before proceeding
379        // if unmuting, unmute only after the specified delay
380        // Returns the number of ms waited
381        virtual uint32_t  checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
382                                            audio_devices_t prevDevice,
383                                            uint32_t delayMs);
384
385        audio_io_handle_t selectOutput(const SortedVector<audio_io_handle_t>& outputs,
386                                       audio_output_flags_t flags,
387                                       audio_format_t format);
388        // samplingRate parameter is an in/out and so may be modified
389        sp<IOProfile> getInputProfile(audio_devices_t device,
390                                      String8 address,
391                                      uint32_t& samplingRate,
392                                      audio_format_t format,
393                                      audio_channel_mask_t channelMask,
394                                      audio_input_flags_t flags);
395        sp<IOProfile> getProfileForDirectOutput(audio_devices_t device,
396                                                       uint32_t samplingRate,
397                                                       audio_format_t format,
398                                                       audio_channel_mask_t channelMask,
399                                                       audio_output_flags_t flags);
400
401        audio_io_handle_t selectOutputForEffects(const SortedVector<audio_io_handle_t>& outputs);
402
403        virtual status_t addAudioPatch(audio_patch_handle_t handle, const sp<AudioPatch>& patch)
404        {
405            return mAudioPatches.addAudioPatch(handle, patch);
406        }
407        virtual status_t removeAudioPatch(audio_patch_handle_t handle)
408        {
409            return mAudioPatches.removeAudioPatch(handle);
410        }
411
412        audio_devices_t availablePrimaryOutputDevices() const
413        {
414            return mOutputs.getSupportedDevices(mPrimaryOutput) & mAvailableOutputDevices.types();
415        }
416        audio_devices_t availablePrimaryInputDevices() const
417        {
418            return mAvailableInputDevices.getDevicesFromHwModule(
419                        mOutputs.valueFor(mPrimaryOutput)->getModuleHandle());
420        }
421
422        void updateCallRouting(audio_devices_t rxDevice, int delayMs = 0);
423
424        uid_t mUidCached;
425        AudioPolicyClientInterface *mpClientInterface;  // audio policy client interface
426        audio_io_handle_t mPrimaryOutput;              // primary output handle
427        // list of descriptors for outputs currently opened
428        AudioOutputCollection mOutputs;
429        // copy of mOutputs before setDeviceConnectionState() opens new outputs
430        // reset to mOutputs when updateDevicesAndOutputs() is called.
431        AudioOutputCollection mPreviousOutputs;
432        AudioInputCollection mInputs;     // list of input descriptors
433        DeviceVector  mAvailableOutputDevices; // all available output devices
434        DeviceVector  mAvailableInputDevices;  // all available input devices
435        int mPhoneState;                                                    // current phone state
436        audio_policy_forced_cfg_t mForceUse[AUDIO_POLICY_FORCE_USE_CNT];   // current forced use configuration
437
438        StreamDescriptor mStreams[AUDIO_STREAM_CNT];           // stream descriptors for volume control
439        bool    mLimitRingtoneVolume;                                       // limit ringtone volume to music volume if headset connected
440        audio_devices_t mDeviceForStrategy[NUM_STRATEGIES];
441        float   mLastVoiceVolume;                                           // last voice volume value sent to audio HAL
442
443        EffectDescriptorCollection mEffects;  // list of registered audio effects
444        bool    mA2dpSuspended;  // true if A2DP output is suspended
445        sp<DeviceDescriptor> mDefaultOutputDevice; // output device selected by default at boot time
446        bool mSpeakerDrcEnabled;// true on devices that use DRC on the DEVICE_CATEGORY_SPEAKER path
447                                // to boost soft sounds, used to adjust volume curves accordingly
448
449        HwModuleCollection mHwModules;
450
451        volatile int32_t mAudioPortGeneration;
452
453        AudioPatchCollection mAudioPatches;
454
455        SoundTriggerSessionCollection mSoundTriggerSessions;
456
457        sp<AudioPatch> mCallTxPatch;
458        sp<AudioPatch> mCallRxPatch;
459
460        // for supporting "beacon" streams, i.e. streams that only play on speaker, and never
461        // when something other than STREAM_TTS (a.k.a. "Transmitted Through Speaker") is playing
462        enum {
463            STARTING_OUTPUT,
464            STARTING_BEACON,
465            STOPPING_OUTPUT,
466            STOPPING_BEACON
467        };
468        uint32_t mBeaconMuteRefCount;   // ref count for stream that would mute beacon
469        uint32_t mBeaconPlayingRefCount;// ref count for the playing beacon streams
470        bool mBeaconMuted;              // has STREAM_TTS been muted
471
472        AudioPolicyMixCollection mPolicyMixes; // list of registered mixes
473
474#ifdef AUDIO_POLICY_TEST
475        Mutex   mLock;
476        Condition mWaitWorkCV;
477
478        int             mCurOutput;
479        bool            mDirectOutput;
480        audio_io_handle_t mTestOutputs[NUM_TEST_OUTPUTS];
481        int             mTestInput;
482        uint32_t        mTestDevice;
483        uint32_t        mTestSamplingRate;
484        uint32_t        mTestFormat;
485        uint32_t        mTestChannels;
486        uint32_t        mTestLatencyMs;
487#endif //AUDIO_POLICY_TEST
488
489        uint32_t nextAudioPortGeneration();
490private:
491        // updates device caching and output for streams that can influence the
492        //    routing of notifications
493        void handleNotificationRoutingForStream(audio_stream_type_t stream);
494        // find the outputs on a given output descriptor that have the given address.
495        // to be called on an AudioOutputDescriptor whose supported devices (as defined
496        //   in mProfile->mSupportedDevices) matches the device whose address is to be matched.
497        // see deviceDistinguishesOnAddress(audio_devices_t) for whether the device type is one
498        //   where addresses are used to distinguish between one connected device and another.
499        void findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
500                const audio_devices_t device /*in*/,
501                const String8 address /*in*/,
502                SortedVector<audio_io_handle_t>& outputs /*out*/);
503        uint32_t curAudioPortGeneration() const { return mAudioPortGeneration; }
504        // internal method to return the output handle for the given device and format
505        audio_io_handle_t getOutputForDevice(
506                audio_devices_t device,
507                audio_session_t session,
508                audio_stream_type_t stream,
509                uint32_t samplingRate,
510                audio_format_t format,
511                audio_channel_mask_t channelMask,
512                audio_output_flags_t flags,
513                const audio_offload_info_t *offloadInfo);
514        // internal function to derive a stream type value from audio attributes
515        audio_stream_type_t streamTypefromAttributesInt(const audio_attributes_t *attr);
516        // event is one of STARTING_OUTPUT, STARTING_BEACON, STOPPING_OUTPUT, STOPPING_BEACON
517        // returns 0 if no mute/unmute event happened, the largest latency of the device where
518        //   the mute/unmute happened
519        uint32_t handleEventForBeacon(int event);
520        uint32_t setBeaconMute(bool mute);
521        bool     isValidAttributes(const audio_attributes_t *paa);
522
523        // select input device corresponding to requested audio source and return associated policy
524        // mix if any. Calls getDeviceForInputSource().
525        audio_devices_t getDeviceAndMixForInputSource(audio_source_t inputSource,
526                                                        AudioMix **policyMix = NULL);
527
528        // Called by setDeviceConnectionState().
529        status_t setDeviceConnectionStateInt(audio_devices_t device,
530                                                          audio_policy_dev_state_t state,
531                                                          const char *device_address,
532                                                          const char *device_name);
533
534        bool isStrategyActive(const sp<AudioOutputDescriptor> outputDesc, routing_strategy strategy,
535                              uint32_t inPastMs = 0, nsecs_t sysTime = 0) const;
536};
537
538};
539