AudioPolicyManager.h revision d9cfeb447356cb6334379eaf5da1e49424eb5979
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
18#include <stdint.h>
19#include <sys/types.h>
20#include <cutils/config_utils.h>
21#include <cutils/misc.h>
22#include <utils/Timers.h>
23#include <utils/Errors.h>
24#include <utils/KeyedVector.h>
25#include <utils/SortedVector.h>
26#include "AudioPolicyInterface.h"
27
28
29namespace android {
30
31// ----------------------------------------------------------------------------
32
33// Attenuation applied to STRATEGY_SONIFICATION streams when a headset is connected: 6dB
34#define SONIFICATION_HEADSET_VOLUME_FACTOR 0.5
35// Min volume for STRATEGY_SONIFICATION streams when limited by music volume: -36dB
36#define SONIFICATION_HEADSET_VOLUME_MIN  0.016
37// Time in milliseconds during which we consider that music is still active after a music
38// track was stopped - see computeVolume()
39#define SONIFICATION_HEADSET_MUSIC_DELAY  5000
40// Time in milliseconds after media stopped playing during which we consider that the
41// sonification should be as unobtrusive as during the time media was playing.
42#define SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY 5000
43// Time in milliseconds during witch some streams are muted while the audio path
44// is switched
45#define MUTE_TIME_MS 2000
46
47#define NUM_TEST_OUTPUTS 5
48
49#define NUM_VOL_CURVE_KNEES 2
50
51// Default minimum length allowed for offloading a compressed track
52// Can be overridden by the audio.offload.min.duration.secs property
53#define OFFLOAD_DEFAULT_MIN_DURATION_SECS 60
54
55#define MAX_MIXER_SAMPLING_RATE 48000
56#define MAX_MIXER_CHANNEL_COUNT 8
57
58// ----------------------------------------------------------------------------
59// AudioPolicyManager implements audio policy manager behavior common to all platforms.
60// ----------------------------------------------------------------------------
61
62class AudioPolicyManager: public AudioPolicyInterface
63#ifdef AUDIO_POLICY_TEST
64    , public Thread
65#endif //AUDIO_POLICY_TEST
66{
67
68public:
69                AudioPolicyManager(AudioPolicyClientInterface *clientInterface);
70        virtual ~AudioPolicyManager();
71
72        // AudioPolicyInterface
73        virtual status_t setDeviceConnectionState(audio_devices_t device,
74                                                          audio_policy_dev_state_t state,
75                                                          const char *device_address);
76        virtual audio_policy_dev_state_t getDeviceConnectionState(audio_devices_t device,
77                                                                              const char *device_address);
78        virtual void setPhoneState(audio_mode_t state);
79        virtual void setForceUse(audio_policy_force_use_t usage,
80                                 audio_policy_forced_cfg_t config);
81        virtual audio_policy_forced_cfg_t getForceUse(audio_policy_force_use_t usage);
82        virtual void setSystemProperty(const char* property, const char* value);
83        virtual status_t initCheck();
84        virtual audio_io_handle_t getOutput(audio_stream_type_t stream,
85                                            uint32_t samplingRate,
86                                            audio_format_t format,
87                                            audio_channel_mask_t channelMask,
88                                            audio_output_flags_t flags,
89                                            const audio_offload_info_t *offloadInfo);
90        virtual audio_io_handle_t getOutputForAttr(const audio_attributes_t *attr,
91                                            uint32_t samplingRate,
92                                            audio_format_t format,
93                                            audio_channel_mask_t channelMask,
94                                            audio_output_flags_t flags,
95                                            const audio_offload_info_t *offloadInfo);
96        virtual status_t startOutput(audio_io_handle_t output,
97                                     audio_stream_type_t stream,
98                                     int session = 0);
99        virtual status_t stopOutput(audio_io_handle_t output,
100                                    audio_stream_type_t stream,
101                                    int session = 0);
102        virtual void releaseOutput(audio_io_handle_t output);
103        virtual audio_io_handle_t getInput(audio_source_t inputSource,
104                                            uint32_t samplingRate,
105                                            audio_format_t format,
106                                            audio_channel_mask_t channelMask,
107                                            audio_session_t session,
108                                            audio_input_flags_t flags);
109
110        // indicates to the audio policy manager that the input starts being used.
111        virtual status_t startInput(audio_io_handle_t input,
112                                    audio_session_t session);
113
114        // indicates to the audio policy manager that the input stops being used.
115        virtual status_t stopInput(audio_io_handle_t input,
116                                   audio_session_t session);
117        virtual void releaseInput(audio_io_handle_t input,
118                                  audio_session_t session);
119        virtual void closeAllInputs();
120        virtual void initStreamVolume(audio_stream_type_t stream,
121                                                    int indexMin,
122                                                    int indexMax);
123        virtual status_t setStreamVolumeIndex(audio_stream_type_t stream,
124                                              int index,
125                                              audio_devices_t device);
126        virtual status_t getStreamVolumeIndex(audio_stream_type_t stream,
127                                              int *index,
128                                              audio_devices_t device);
129
130        // return the strategy corresponding to a given stream type
131        virtual uint32_t getStrategyForStream(audio_stream_type_t stream);
132        // return the strategy corresponding to the given audio attributes
133        virtual uint32_t getStrategyForAttr(const audio_attributes_t *attr);
134
135        // return the enabled output devices for the given stream type
136        virtual audio_devices_t getDevicesForStream(audio_stream_type_t stream);
137
138        virtual audio_io_handle_t getOutputForEffect(const effect_descriptor_t *desc = NULL);
139        virtual status_t registerEffect(const effect_descriptor_t *desc,
140                                        audio_io_handle_t io,
141                                        uint32_t strategy,
142                                        int session,
143                                        int id);
144        virtual status_t unregisterEffect(int id);
145        virtual status_t setEffectEnabled(int id, bool enabled);
146
147        virtual bool isStreamActive(audio_stream_type_t stream, uint32_t inPastMs = 0) const;
148        // return whether a stream is playing remotely, override to change the definition of
149        //   local/remote playback, used for instance by notification manager to not make
150        //   media players lose audio focus when not playing locally
151        virtual bool isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs = 0) const;
152        virtual bool isSourceActive(audio_source_t source) const;
153
154        virtual status_t dump(int fd);
155
156        virtual bool isOffloadSupported(const audio_offload_info_t& offloadInfo);
157
158        virtual status_t listAudioPorts(audio_port_role_t role,
159                                        audio_port_type_t type,
160                                        unsigned int *num_ports,
161                                        struct audio_port *ports,
162                                        unsigned int *generation);
163        virtual status_t getAudioPort(struct audio_port *port);
164        virtual status_t createAudioPatch(const struct audio_patch *patch,
165                                           audio_patch_handle_t *handle,
166                                           uid_t uid);
167        virtual status_t releaseAudioPatch(audio_patch_handle_t handle,
168                                              uid_t uid);
169        virtual status_t listAudioPatches(unsigned int *num_patches,
170                                          struct audio_patch *patches,
171                                          unsigned int *generation);
172        virtual status_t setAudioPortConfig(const struct audio_port_config *config);
173        virtual void clearAudioPatches(uid_t uid);
174
175        virtual status_t acquireSoundTriggerSession(audio_session_t *session,
176                                               audio_io_handle_t *ioHandle,
177                                               audio_devices_t *device);
178
179        virtual status_t releaseSoundTriggerSession(audio_session_t session);
180
181protected:
182
183        enum routing_strategy {
184            STRATEGY_MEDIA,
185            STRATEGY_PHONE,
186            STRATEGY_SONIFICATION,
187            STRATEGY_SONIFICATION_RESPECTFUL,
188            STRATEGY_DTMF,
189            STRATEGY_ENFORCED_AUDIBLE,
190            STRATEGY_TRANSMITTED_THROUGH_SPEAKER,
191            NUM_STRATEGIES
192        };
193
194        // 4 points to define the volume attenuation curve, each characterized by the volume
195        // index (from 0 to 100) at which they apply, and the attenuation in dB at that index.
196        // we use 100 steps to avoid rounding errors when computing the volume in volIndexToAmpl()
197
198        enum { VOLMIN = 0, VOLKNEE1 = 1, VOLKNEE2 = 2, VOLMAX = 3, VOLCNT = 4};
199
200        class VolumeCurvePoint
201        {
202        public:
203            int mIndex;
204            float mDBAttenuation;
205        };
206
207        // device categories used for volume curve management.
208        enum device_category {
209            DEVICE_CATEGORY_HEADSET,
210            DEVICE_CATEGORY_SPEAKER,
211            DEVICE_CATEGORY_EARPIECE,
212            DEVICE_CATEGORY_EXT_MEDIA,
213            DEVICE_CATEGORY_CNT
214        };
215
216        class HwModule;
217
218        class AudioGain: public RefBase
219        {
220        public:
221            AudioGain(int index, bool useInChannelMask);
222            virtual ~AudioGain() {}
223
224            void dump(int fd, int spaces, int index) const;
225
226            void getDefaultConfig(struct audio_gain_config *config);
227            status_t checkConfig(const struct audio_gain_config *config);
228            int               mIndex;
229            struct audio_gain mGain;
230            bool              mUseInChannelMask;
231        };
232
233        class AudioPort: public virtual RefBase
234        {
235        public:
236            AudioPort(const String8& name, audio_port_type_t type,
237                      audio_port_role_t role, const sp<HwModule>& module);
238            virtual ~AudioPort() {}
239
240            virtual void toAudioPort(struct audio_port *port) const;
241
242            void importAudioPort(const sp<AudioPort> port);
243            void clearCapabilities();
244
245            void loadSamplingRates(char *name);
246            void loadFormats(char *name);
247            void loadOutChannels(char *name);
248            void loadInChannels(char *name);
249
250            audio_gain_mode_t loadGainMode(char *name);
251            void loadGain(cnode *root, int index);
252            void loadGains(cnode *root);
253
254            // searches for an exact match
255            status_t checkExactSamplingRate(uint32_t samplingRate) const;
256            // searches for a compatible match, and returns the best match via updatedSamplingRate
257            status_t checkCompatibleSamplingRate(uint32_t samplingRate,
258                    uint32_t *updatedSamplingRate) const;
259            // searches for an exact match
260            status_t checkExactChannelMask(audio_channel_mask_t channelMask) const;
261            // searches for a compatible match, currently implemented for input channel masks only
262            status_t checkCompatibleChannelMask(audio_channel_mask_t channelMask) const;
263            status_t checkFormat(audio_format_t format) const;
264            status_t checkGain(const struct audio_gain_config *gainConfig, int index) const;
265
266            uint32_t pickSamplingRate() const;
267            audio_channel_mask_t pickChannelMask() const;
268            audio_format_t pickFormat() const;
269
270            static const audio_format_t sPcmFormatCompareTable[];
271            static int compareFormats(audio_format_t format1, audio_format_t format2);
272
273            void dump(int fd, int spaces) const;
274
275            String8           mName;
276            audio_port_type_t mType;
277            audio_port_role_t mRole;
278            bool              mUseInChannelMask;
279            // by convention, "0' in the first entry in mSamplingRates, mChannelMasks or mFormats
280            // indicates the supported parameters should be read from the output stream
281            // after it is opened for the first time
282            Vector <uint32_t> mSamplingRates; // supported sampling rates
283            Vector <audio_channel_mask_t> mChannelMasks; // supported channel masks
284            Vector <audio_format_t> mFormats; // supported audio formats
285            Vector < sp<AudioGain> > mGains; // gain controllers
286            sp<HwModule> mModule;                 // audio HW module exposing this I/O stream
287            uint32_t mFlags; // attribute flags (e.g primary output,
288                                                // direct output...).
289        };
290
291        class AudioPortConfig: public virtual RefBase
292        {
293        public:
294            AudioPortConfig();
295            virtual ~AudioPortConfig() {}
296
297            status_t applyAudioPortConfig(const struct audio_port_config *config,
298                                          struct audio_port_config *backupConfig = NULL);
299            virtual void toAudioPortConfig(struct audio_port_config *dstConfig,
300                                   const struct audio_port_config *srcConfig = NULL) const = 0;
301            virtual sp<AudioPort> getAudioPort() const = 0;
302            uint32_t mSamplingRate;
303            audio_format_t mFormat;
304            audio_channel_mask_t mChannelMask;
305            struct audio_gain_config mGain;
306        };
307
308
309        class AudioPatch: public RefBase
310        {
311        public:
312            AudioPatch(audio_patch_handle_t handle,
313                       const struct audio_patch *patch, uid_t uid) :
314                           mHandle(handle), mPatch(*patch), mUid(uid), mAfPatchHandle(0) {}
315
316            status_t dump(int fd, int spaces, int index) const;
317
318            audio_patch_handle_t mHandle;
319            struct audio_patch mPatch;
320            uid_t mUid;
321            audio_patch_handle_t mAfPatchHandle;
322        };
323
324        class DeviceDescriptor: public AudioPort, public AudioPortConfig
325        {
326        public:
327            DeviceDescriptor(const String8& name, audio_devices_t type);
328
329            virtual ~DeviceDescriptor() {}
330
331            bool equals(const sp<DeviceDescriptor>& other) const;
332            virtual void toAudioPortConfig(struct audio_port_config *dstConfig,
333                                   const struct audio_port_config *srcConfig = NULL) const;
334            virtual sp<AudioPort> getAudioPort() const { return (AudioPort*) this; }
335
336            virtual void toAudioPort(struct audio_port *port) const;
337
338            status_t dump(int fd, int spaces, int index) const;
339
340            audio_devices_t mDeviceType;
341            String8 mAddress;
342            audio_port_handle_t mId;
343        };
344
345        class DeviceVector : public SortedVector< sp<DeviceDescriptor> >
346        {
347        public:
348            DeviceVector() : SortedVector(), mDeviceTypes(AUDIO_DEVICE_NONE) {}
349
350            ssize_t         add(const sp<DeviceDescriptor>& item);
351            ssize_t         remove(const sp<DeviceDescriptor>& item);
352            ssize_t         indexOf(const sp<DeviceDescriptor>& item) const;
353
354            audio_devices_t types() const { return mDeviceTypes; }
355
356            void loadDevicesFromType(audio_devices_t types);
357            void loadDevicesFromName(char *name, const DeviceVector& declaredDevices);
358
359            sp<DeviceDescriptor> getDevice(audio_devices_t type, String8 address) const;
360            DeviceVector getDevicesFromType(audio_devices_t types) const;
361            sp<DeviceDescriptor> getDeviceFromId(audio_port_handle_t id) const;
362            sp<DeviceDescriptor> getDeviceFromName(const String8& name) const;
363            DeviceVector getDevicesFromTypeAddr(audio_devices_t type, String8 address)
364                    const;
365
366        private:
367            void refreshTypes();
368            audio_devices_t mDeviceTypes;
369        };
370
371        // the IOProfile class describes the capabilities of an output or input stream.
372        // It is currently assumed that all combination of listed parameters are supported.
373        // It is used by the policy manager to determine if an output or input is suitable for
374        // a given use case,  open/close it accordingly and connect/disconnect audio tracks
375        // to/from it.
376        class IOProfile : public AudioPort
377        {
378        public:
379            IOProfile(const String8& name, audio_port_role_t role, const sp<HwModule>& module);
380            virtual ~IOProfile();
381
382            // This method is used for both output and input.
383            // If parameter updatedSamplingRate is non-NULL, it is assigned the actual sample rate.
384            // For input, flags is interpreted as audio_input_flags_t.
385            // TODO: merge audio_output_flags_t and audio_input_flags_t.
386            bool isCompatibleProfile(audio_devices_t device,
387                                     uint32_t samplingRate,
388                                     uint32_t *updatedSamplingRate,
389                                     audio_format_t format,
390                                     audio_channel_mask_t channelMask,
391                                     uint32_t flags) const;
392
393            void dump(int fd);
394            void log();
395
396            DeviceVector  mSupportedDevices; // supported devices
397                                             // (devices this output can be routed to)
398        };
399
400        class HwModule : public RefBase
401        {
402        public:
403                    HwModule(const char *name);
404                    ~HwModule();
405
406            status_t loadOutput(cnode *root);
407            status_t loadInput(cnode *root);
408            status_t loadDevice(cnode *root);
409
410            void dump(int fd);
411
412            const char *const        mName; // base name of the audio HW module (primary, a2dp ...)
413            uint32_t                 mHalVersion; // audio HAL API version
414            audio_module_handle_t    mHandle;
415            Vector < sp<IOProfile> > mOutputProfiles; // output profiles exposed by this module
416            Vector < sp<IOProfile> > mInputProfiles;  // input profiles exposed by this module
417            DeviceVector             mDeclaredDevices; // devices declared in audio_policy.conf
418
419        };
420
421        // default volume curve
422        static const VolumeCurvePoint sDefaultVolumeCurve[AudioPolicyManager::VOLCNT];
423        // default volume curve for media strategy
424        static const VolumeCurvePoint sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT];
425        // volume curve for non-media audio on ext media outputs (HDMI, Line, etc)
426        static const VolumeCurvePoint sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT];
427        // volume curve for media strategy on speakers
428        static const VolumeCurvePoint sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT];
429        static const VolumeCurvePoint sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT];
430        // volume curve for sonification strategy on speakers
431        static const VolumeCurvePoint sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT];
432        static const VolumeCurvePoint sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT];
433        static const VolumeCurvePoint sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT];
434        static const VolumeCurvePoint sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT];
435        static const VolumeCurvePoint sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT];
436        static const VolumeCurvePoint sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT];
437        static const VolumeCurvePoint sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT];
438        static const VolumeCurvePoint sLinearVolumeCurve[AudioPolicyManager::VOLCNT];
439        static const VolumeCurvePoint sSilentVolumeCurve[AudioPolicyManager::VOLCNT];
440        // default volume curves per stream and device category. See initializeVolumeCurves()
441        static const VolumeCurvePoint *sVolumeProfiles[AUDIO_STREAM_CNT][DEVICE_CATEGORY_CNT];
442
443        // descriptor for audio outputs. Used to maintain current configuration of each opened audio output
444        // and keep track of the usage of this output by each audio stream type.
445        class AudioOutputDescriptor: public AudioPortConfig
446        {
447        public:
448            AudioOutputDescriptor(const sp<IOProfile>& profile);
449
450            status_t    dump(int fd);
451
452            audio_devices_t device() const;
453            void changeRefCount(audio_stream_type_t stream, int delta);
454
455            bool isDuplicated() const { return (mOutput1 != NULL && mOutput2 != NULL); }
456            audio_devices_t supportedDevices();
457            uint32_t latency();
458            bool sharesHwModuleWith(const sp<AudioOutputDescriptor> outputDesc);
459            bool isActive(uint32_t inPastMs = 0) const;
460            bool isStreamActive(audio_stream_type_t stream,
461                                uint32_t inPastMs = 0,
462                                nsecs_t sysTime = 0) const;
463            bool isStrategyActive(routing_strategy strategy,
464                             uint32_t inPastMs = 0,
465                             nsecs_t sysTime = 0) const;
466
467            virtual void toAudioPortConfig(struct audio_port_config *dstConfig,
468                                   const struct audio_port_config *srcConfig = NULL) const;
469            virtual sp<AudioPort> getAudioPort() const { return mProfile; }
470            void toAudioPort(struct audio_port *port) const;
471
472            audio_port_handle_t mId;
473            audio_io_handle_t mIoHandle;              // output handle
474            uint32_t mLatency;                  //
475            audio_output_flags_t mFlags;   //
476            audio_devices_t mDevice;                   // current device this output is routed to
477            audio_patch_handle_t mPatchHandle;
478            uint32_t mRefCount[AUDIO_STREAM_CNT]; // number of streams of each type using this output
479            nsecs_t mStopTime[AUDIO_STREAM_CNT];
480            sp<AudioOutputDescriptor> mOutput1;    // used by duplicated outputs: first output
481            sp<AudioOutputDescriptor> mOutput2;    // used by duplicated outputs: second output
482            float mCurVolume[AUDIO_STREAM_CNT];   // current stream volume
483            int mMuteCount[AUDIO_STREAM_CNT];     // mute request counter
484            const sp<IOProfile> mProfile;          // I/O profile this output derives from
485            bool mStrategyMutedByDevice[NUM_STRATEGIES]; // strategies muted because of incompatible
486                                                // device selection. See checkDeviceMuteStrategies()
487            uint32_t mDirectOpenCount; // number of clients using this output (direct outputs only)
488        };
489
490        // descriptor for audio inputs. Used to maintain current configuration of each opened audio input
491        // and keep track of the usage of this input.
492        class AudioInputDescriptor: public AudioPortConfig
493        {
494        public:
495            AudioInputDescriptor(const sp<IOProfile>& profile);
496
497            status_t    dump(int fd);
498
499            audio_port_handle_t           mId;
500            audio_io_handle_t             mIoHandle;       // input handle
501            audio_devices_t               mDevice;         // current device this input is routed to
502            audio_patch_handle_t          mPatchHandle;
503            uint32_t                      mRefCount;       // number of AudioRecord clients using
504                                                           // this input
505            uint32_t                      mOpenRefCount;
506            audio_source_t                mInputSource;    // input source selected by application
507                                                           //(mediarecorder.h)
508            const sp<IOProfile>           mProfile;        // I/O profile this output derives from
509            SortedVector<audio_session_t> mSessions;       // audio sessions attached to this input
510            bool                          mIsSoundTrigger; // used by a soundtrigger capture
511
512            virtual void toAudioPortConfig(struct audio_port_config *dstConfig,
513                                   const struct audio_port_config *srcConfig = NULL) const;
514            virtual sp<AudioPort> getAudioPort() const { return mProfile; }
515            void toAudioPort(struct audio_port *port) const;
516        };
517
518        // stream descriptor used for volume control
519        class StreamDescriptor
520        {
521        public:
522            StreamDescriptor();
523
524            int getVolumeIndex(audio_devices_t device);
525            void dump(int fd);
526
527            int mIndexMin;      // min volume index
528            int mIndexMax;      // max volume index
529            KeyedVector<audio_devices_t, int> mIndexCur;   // current volume index per device
530            bool mCanBeMuted;   // true is the stream can be muted
531
532            const VolumeCurvePoint *mVolumeCurve[DEVICE_CATEGORY_CNT];
533        };
534
535        // stream descriptor used for volume control
536        class EffectDescriptor : public RefBase
537        {
538        public:
539
540            status_t dump(int fd);
541
542            int mIo;                // io the effect is attached to
543            routing_strategy mStrategy; // routing strategy the effect is associated to
544            int mSession;               // audio session the effect is on
545            effect_descriptor_t mDesc;  // effect descriptor
546            bool mEnabled;              // enabled state: CPU load being used or not
547        };
548
549        void addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc);
550        void addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc);
551
552        // return the strategy corresponding to a given stream type
553        static routing_strategy getStrategy(audio_stream_type_t stream);
554
555        // return appropriate device for streams handled by the specified strategy according to current
556        // phone state, connected devices...
557        // if fromCache is true, the device is returned from mDeviceForStrategy[],
558        // otherwise it is determine by current state
559        // (device connected,phone state, force use, a2dp output...)
560        // This allows to:
561        //  1 speed up process when the state is stable (when starting or stopping an output)
562        //  2 access to either current device selection (fromCache == true) or
563        // "future" device selection (fromCache == false) when called from a context
564        //  where conditions are changing (setDeviceConnectionState(), setPhoneState()...) AND
565        //  before updateDevicesAndOutputs() is called.
566        virtual audio_devices_t getDeviceForStrategy(routing_strategy strategy,
567                                                     bool fromCache);
568
569        // change the route of the specified output. Returns the number of ms we have slept to
570        // allow new routing to take effect in certain cases.
571        uint32_t setOutputDevice(audio_io_handle_t output,
572                             audio_devices_t device,
573                             bool force = false,
574                             int delayMs = 0,
575                             audio_patch_handle_t *patchHandle = NULL,
576                             const char* address = NULL);
577        status_t resetOutputDevice(audio_io_handle_t output,
578                                   int delayMs = 0,
579                                   audio_patch_handle_t *patchHandle = NULL);
580        status_t setInputDevice(audio_io_handle_t input,
581                                audio_devices_t device,
582                                bool force = false,
583                                audio_patch_handle_t *patchHandle = NULL);
584        status_t resetInputDevice(audio_io_handle_t input,
585                                  audio_patch_handle_t *patchHandle = NULL);
586
587        // select input device corresponding to requested audio source
588        virtual audio_devices_t getDeviceForInputSource(audio_source_t inputSource);
589
590        // return io handle of active input or 0 if no input is active
591        //    Only considers inputs from physical devices (e.g. main mic, headset mic) when
592        //    ignoreVirtualInputs is true.
593        audio_io_handle_t getActiveInput(bool ignoreVirtualInputs = true);
594
595        uint32_t activeInputsCount() const;
596
597        // initialize volume curves for each strategy and device category
598        void initializeVolumeCurves();
599
600        // compute the actual volume for a given stream according to the requested index and a particular
601        // device
602        virtual float computeVolume(audio_stream_type_t stream, int index,
603                                    audio_io_handle_t output, audio_devices_t device);
604
605        // check that volume change is permitted, compute and send new volume to audio hardware
606        virtual status_t checkAndSetVolume(audio_stream_type_t stream, int index,
607                                           audio_io_handle_t output,
608                                           audio_devices_t device,
609                                           int delayMs = 0, bool force = false);
610
611        // apply all stream volumes to the specified output and device
612        void applyStreamVolumes(audio_io_handle_t output, audio_devices_t device, int delayMs = 0, bool force = false);
613
614        // Mute or unmute all streams handled by the specified strategy on the specified output
615        void setStrategyMute(routing_strategy strategy,
616                             bool on,
617                             audio_io_handle_t output,
618                             int delayMs = 0,
619                             audio_devices_t device = (audio_devices_t)0);
620
621        // Mute or unmute the stream on the specified output
622        void setStreamMute(audio_stream_type_t stream,
623                           bool on,
624                           audio_io_handle_t output,
625                           int delayMs = 0,
626                           audio_devices_t device = (audio_devices_t)0);
627
628        // handle special cases for sonification strategy while in call: mute streams or replace by
629        // a special tone in the device used for communication
630        void handleIncallSonification(audio_stream_type_t stream, bool starting, bool stateChange);
631
632        // true if device is in a telephony or VoIP call
633        virtual bool isInCall();
634
635        // true if given state represents a device in a telephony or VoIP call
636        virtual bool isStateInCall(int state);
637
638        // when a device is connected, checks if an open output can be routed
639        // to this device. If none is open, tries to open one of the available outputs.
640        // Returns an output suitable to this device or 0.
641        // when a device is disconnected, checks if an output is not used any more and
642        // returns its handle if any.
643        // transfers the audio tracks and effects from one output thread to another accordingly.
644        status_t checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
645                                       audio_policy_dev_state_t state,
646                                       SortedVector<audio_io_handle_t>& outputs,
647                                       const String8 address);
648
649        status_t checkInputsForDevice(audio_devices_t device,
650                                      audio_policy_dev_state_t state,
651                                      SortedVector<audio_io_handle_t>& inputs,
652                                      const String8 address);
653
654        // close an output and its companion duplicating output.
655        void closeOutput(audio_io_handle_t output);
656
657        // close an input.
658        void closeInput(audio_io_handle_t input);
659
660        // checks and if necessary changes outputs used for all strategies.
661        // must be called every time a condition that affects the output choice for a given strategy
662        // changes: connected device, phone state, force use...
663        // Must be called before updateDevicesAndOutputs()
664        void checkOutputForStrategy(routing_strategy strategy);
665
666        // Same as checkOutputForStrategy() but for a all strategies in order of priority
667        void checkOutputForAllStrategies();
668
669        // manages A2DP output suspend/restore according to phone state and BT SCO usage
670        void checkA2dpSuspend();
671
672        // returns the A2DP output handle if it is open or 0 otherwise
673        audio_io_handle_t getA2dpOutput();
674
675        // selects the most appropriate device on output for current state
676        // must be called every time a condition that affects the device choice for a given output is
677        // changed: connected device, phone state, force use, output start, output stop..
678        // see getDeviceForStrategy() for the use of fromCache parameter
679        audio_devices_t getNewOutputDevice(audio_io_handle_t output, bool fromCache);
680
681        // updates cache of device used by all strategies (mDeviceForStrategy[])
682        // must be called every time a condition that affects the device choice for a given strategy is
683        // changed: connected device, phone state, force use...
684        // cached values are used by getDeviceForStrategy() if parameter fromCache is true.
685         // Must be called after checkOutputForAllStrategies()
686        void updateDevicesAndOutputs();
687
688        // selects the most appropriate device on input for current state
689        audio_devices_t getNewInputDevice(audio_io_handle_t input);
690
691        virtual uint32_t getMaxEffectsCpuLoad();
692        virtual uint32_t getMaxEffectsMemory();
693#ifdef AUDIO_POLICY_TEST
694        virtual     bool        threadLoop();
695                    void        exit();
696        int testOutputIndex(audio_io_handle_t output);
697#endif //AUDIO_POLICY_TEST
698
699        status_t setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled);
700
701        // returns the category the device belongs to with regard to volume curve management
702        static device_category getDeviceCategory(audio_devices_t device);
703
704        // extract one device relevant for volume control from multiple device selection
705        static audio_devices_t getDeviceForVolume(audio_devices_t device);
706
707        SortedVector<audio_io_handle_t> getOutputsForDevice(audio_devices_t device,
708                        DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs);
709        bool vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
710                                           SortedVector<audio_io_handle_t>& outputs2);
711
712        // mute/unmute strategies using an incompatible device combination
713        // if muting, wait for the audio in pcm buffer to be drained before proceeding
714        // if unmuting, unmute only after the specified delay
715        // Returns the number of ms waited
716        uint32_t  checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
717                                            audio_devices_t prevDevice,
718                                            uint32_t delayMs);
719
720        audio_io_handle_t selectOutput(const SortedVector<audio_io_handle_t>& outputs,
721                                       audio_output_flags_t flags,
722                                       audio_format_t format);
723        // samplingRate parameter is an in/out and so may be modified
724        sp<IOProfile> getInputProfile(audio_devices_t device,
725                                   uint32_t& samplingRate,
726                                   audio_format_t format,
727                                   audio_channel_mask_t channelMask,
728                                   audio_input_flags_t flags);
729        sp<IOProfile> getProfileForDirectOutput(audio_devices_t device,
730                                                       uint32_t samplingRate,
731                                                       audio_format_t format,
732                                                       audio_channel_mask_t channelMask,
733                                                       audio_output_flags_t flags);
734
735        audio_io_handle_t selectOutputForEffects(const SortedVector<audio_io_handle_t>& outputs);
736
737        bool isNonOffloadableEffectEnabled();
738
739        status_t addAudioPatch(audio_patch_handle_t handle,
740                               const sp<AudioPatch>& patch);
741        status_t removeAudioPatch(audio_patch_handle_t handle);
742
743        sp<AudioOutputDescriptor> getOutputFromId(audio_port_handle_t id) const;
744        sp<AudioInputDescriptor> getInputFromId(audio_port_handle_t id) const;
745        sp<HwModule> getModuleForDevice(audio_devices_t device) const;
746        sp<HwModule> getModuleFromName(const char *name) const;
747        audio_devices_t availablePrimaryOutputDevices();
748        audio_devices_t availablePrimaryInputDevices();
749
750        void updateCallRouting(audio_devices_t rxDevice, int delayMs = 0);
751
752        //
753        // Audio policy configuration file parsing (audio_policy.conf)
754        //
755        static uint32_t stringToEnum(const struct StringToEnum *table,
756                                     size_t size,
757                                     const char *name);
758        static const char *enumToString(const struct StringToEnum *table,
759                                      size_t size,
760                                      uint32_t value);
761        static bool stringToBool(const char *value);
762        static uint32_t parseOutputFlagNames(char *name);
763        static uint32_t parseInputFlagNames(char *name);
764        static audio_devices_t parseDeviceNames(char *name);
765        void loadHwModule(cnode *root);
766        void loadHwModules(cnode *root);
767        void loadGlobalConfig(cnode *root, const sp<HwModule>& module);
768        status_t loadAudioPolicyConfig(const char *path);
769        void defaultAudioPolicyConfig(void);
770
771
772        uid_t mUidCached;
773        AudioPolicyClientInterface *mpClientInterface;  // audio policy client interface
774        audio_io_handle_t mPrimaryOutput;              // primary output handle
775        // list of descriptors for outputs currently opened
776        DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > mOutputs;
777        // copy of mOutputs before setDeviceConnectionState() opens new outputs
778        // reset to mOutputs when updateDevicesAndOutputs() is called.
779        DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > mPreviousOutputs;
780        DefaultKeyedVector<audio_io_handle_t, sp<AudioInputDescriptor> > mInputs;     // list of input descriptors
781        DeviceVector  mAvailableOutputDevices; // all available output devices
782        DeviceVector  mAvailableInputDevices;  // all available input devices
783        int mPhoneState;                                                    // current phone state
784        audio_policy_forced_cfg_t mForceUse[AUDIO_POLICY_FORCE_USE_CNT];   // current forced use configuration
785
786        StreamDescriptor mStreams[AUDIO_STREAM_CNT];           // stream descriptors for volume control
787        bool    mLimitRingtoneVolume;                                       // limit ringtone volume to music volume if headset connected
788        audio_devices_t mDeviceForStrategy[NUM_STRATEGIES];
789        float   mLastVoiceVolume;                                           // last voice volume value sent to audio HAL
790
791        // Maximum CPU load allocated to audio effects in 0.1 MIPS (ARMv5TE, 0 WS memory) units
792        static const uint32_t MAX_EFFECTS_CPU_LOAD = 1000;
793        // Maximum memory allocated to audio effects in KB
794        static const uint32_t MAX_EFFECTS_MEMORY = 512;
795        uint32_t mTotalEffectsCpuLoad; // current CPU load used by effects
796        uint32_t mTotalEffectsMemory;  // current memory used by effects
797        KeyedVector<int, sp<EffectDescriptor> > mEffects;  // list of registered audio effects
798        bool    mA2dpSuspended;  // true if A2DP output is suspended
799        sp<DeviceDescriptor> mDefaultOutputDevice; // output device selected by default at boot time
800        bool mSpeakerDrcEnabled;// true on devices that use DRC on the DEVICE_CATEGORY_SPEAKER path
801                                // to boost soft sounds, used to adjust volume curves accordingly
802
803        Vector < sp<HwModule> > mHwModules;
804        volatile int32_t mNextUniqueId;
805        volatile int32_t mAudioPortGeneration;
806
807        DefaultKeyedVector<audio_patch_handle_t, sp<AudioPatch> > mAudioPatches;
808
809        DefaultKeyedVector<audio_session_t, audio_io_handle_t> mSoundTriggerSessions;
810
811        sp<AudioPatch> mCallTxPatch;
812        sp<AudioPatch> mCallRxPatch;
813
814        // for supporting "beacon" streams, i.e. streams that only play on speaker, and never
815        // when something other than STREAM_TTS (a.k.a. "Transmitted Through Speaker") is playing
816        enum {
817            STARTING_OUTPUT,
818            STARTING_BEACON,
819            STOPPING_OUTPUT,
820            STOPPING_BEACON
821        };
822        uint32_t mBeaconMuteRefCount;   // ref count for stream that would mute beacon
823        uint32_t mBeaconPlayingRefCount;// ref count for the playing beacon streams
824        bool mBeaconMuted;              // has STREAM_TTS been muted
825
826#ifdef AUDIO_POLICY_TEST
827        Mutex   mLock;
828        Condition mWaitWorkCV;
829
830        int             mCurOutput;
831        bool            mDirectOutput;
832        audio_io_handle_t mTestOutputs[NUM_TEST_OUTPUTS];
833        int             mTestInput;
834        uint32_t        mTestDevice;
835        uint32_t        mTestSamplingRate;
836        uint32_t        mTestFormat;
837        uint32_t        mTestChannels;
838        uint32_t        mTestLatencyMs;
839#endif //AUDIO_POLICY_TEST
840        static float volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
841                int indexInUi);
842private:
843        // updates device caching and output for streams that can influence the
844        //    routing of notifications
845        void handleNotificationRoutingForStream(audio_stream_type_t stream);
846        static bool isVirtualInputDevice(audio_devices_t device);
847        static bool deviceDistinguishesOnAddress(audio_devices_t device);
848        // find the outputs on a given output descriptor that have the given address.
849        // to be called on an AudioOutputDescriptor whose supported devices (as defined
850        //   in mProfile->mSupportedDevices) matches the device whose address is to be matched.
851        // see deviceDistinguishesOnAddress(audio_devices_t) for whether the device type is one
852        //   where addresses are used to distinguish between one connected device and another.
853        void findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
854                const String8 address /*in*/,
855                SortedVector<audio_io_handle_t>& outputs /*out*/);
856        uint32_t nextUniqueId();
857        uint32_t nextAudioPortGeneration();
858        uint32_t curAudioPortGeneration() const { return mAudioPortGeneration; }
859        // internal method to return the output handle for the given device and format
860        audio_io_handle_t getOutputForDevice(
861                audio_devices_t device,
862                audio_stream_type_t stream,
863                uint32_t samplingRate,
864                audio_format_t format,
865                audio_channel_mask_t channelMask,
866                audio_output_flags_t flags,
867                const audio_offload_info_t *offloadInfo);
868        // internal function to derive a stream type value from audio attributes
869        audio_stream_type_t streamTypefromAttributesInt(const audio_attributes_t *attr);
870        // return true if any output is playing anything besides the stream to ignore
871        bool isAnyOutputActive(audio_stream_type_t streamToIgnore);
872        // event is one of STARTING_OUTPUT, STARTING_BEACON, STOPPING_OUTPUT, STOPPING_BEACON
873        // returns 0 if no mute/unmute event happened, the largest latency of the device where
874        //   the mute/unmute happened
875        uint32_t handleEventForBeacon(int event);
876        uint32_t setBeaconMute(bool mute);
877};
878
879};
880