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