AudioSystem.h revision 7281aa9810b33eff47b00104db26c97c77931611
1/*
2 * Copyright (C) 2008 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#ifndef ANDROID_AUDIOSYSTEM_H_
18#define ANDROID_AUDIOSYSTEM_H_
19
20#include <hardware/audio_effect.h>
21#include <media/AudioPolicy.h>
22#include <media/AudioIoDescriptor.h>
23#include <media/IAudioFlingerClient.h>
24#include <media/IAudioPolicyServiceClient.h>
25#include <system/audio.h>
26#include <system/audio_policy.h>
27#include <utils/Errors.h>
28#include <utils/Mutex.h>
29
30namespace android {
31
32typedef void (*audio_error_callback)(status_t err);
33typedef void (*dynamic_policy_callback)(int event, String8 regId, int val);
34typedef void (*record_config_callback)(int event, int session, int source,
35                const audio_config_base_t *clientConfig,
36                const audio_config_base_t *deviceConfig);
37
38class IAudioFlinger;
39class IAudioPolicyService;
40class String8;
41
42class AudioSystem
43{
44public:
45
46    /* These are static methods to control the system-wide AudioFlinger
47     * only privileged processes can have access to them
48     */
49
50    // mute/unmute microphone
51    static status_t muteMicrophone(bool state);
52    static status_t isMicrophoneMuted(bool *state);
53
54    // set/get master volume
55    static status_t setMasterVolume(float value);
56    static status_t getMasterVolume(float* volume);
57
58    // mute/unmute audio outputs
59    static status_t setMasterMute(bool mute);
60    static status_t getMasterMute(bool* mute);
61
62    // set/get stream volume on specified output
63    static status_t setStreamVolume(audio_stream_type_t stream, float value,
64                                    audio_io_handle_t output);
65    static status_t getStreamVolume(audio_stream_type_t stream, float* volume,
66                                    audio_io_handle_t output);
67
68    // mute/unmute stream
69    static status_t setStreamMute(audio_stream_type_t stream, bool mute);
70    static status_t getStreamMute(audio_stream_type_t stream, bool* mute);
71
72    // set audio mode in audio hardware
73    static status_t setMode(audio_mode_t mode);
74
75    // returns true in *state if tracks are active on the specified stream or have been active
76    // in the past inPastMs milliseconds
77    static status_t isStreamActive(audio_stream_type_t stream, bool *state, uint32_t inPastMs);
78    // returns true in *state if tracks are active for what qualifies as remote playback
79    // on the specified stream or have been active in the past inPastMs milliseconds. Remote
80    // playback isn't mutually exclusive with local playback.
81    static status_t isStreamActiveRemotely(audio_stream_type_t stream, bool *state,
82            uint32_t inPastMs);
83    // returns true in *state if a recorder is currently recording with the specified source
84    static status_t isSourceActive(audio_source_t source, bool *state);
85
86    // set/get audio hardware parameters. The function accepts a list of parameters
87    // key value pairs in the form: key1=value1;key2=value2;...
88    // Some keys are reserved for standard parameters (See AudioParameter class).
89    // The versions with audio_io_handle_t are intended for internal media framework use only.
90    static status_t setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs);
91    static String8  getParameters(audio_io_handle_t ioHandle, const String8& keys);
92    // The versions without audio_io_handle_t are intended for JNI.
93    static status_t setParameters(const String8& keyValuePairs);
94    static String8  getParameters(const String8& keys);
95
96    static void setErrorCallback(audio_error_callback cb);
97    static void setDynPolicyCallback(dynamic_policy_callback cb);
98    static void setRecordConfigCallback(record_config_callback);
99
100    // helper function to obtain AudioFlinger service handle
101    static const sp<IAudioFlinger> get_audio_flinger();
102
103    static float linearToLog(int volume);
104    static int logToLinear(float volume);
105
106    // Returned samplingRate and frameCount output values are guaranteed
107    // to be non-zero if status == NO_ERROR
108    // FIXME This API assumes a route, and so should be deprecated.
109    static status_t getOutputSamplingRate(uint32_t* samplingRate,
110            audio_stream_type_t stream);
111    // FIXME This API assumes a route, and so should be deprecated.
112    static status_t getOutputFrameCount(size_t* frameCount,
113            audio_stream_type_t stream);
114    // FIXME This API assumes a route, and so should be deprecated.
115    static status_t getOutputLatency(uint32_t* latency,
116            audio_stream_type_t stream);
117    static status_t getSamplingRate(audio_io_handle_t output,
118                                          uint32_t* samplingRate);
119    // returns the number of frames per audio HAL write buffer. Corresponds to
120    // audio_stream->get_buffer_size()/audio_stream_out_frame_size()
121    static status_t getFrameCount(audio_io_handle_t output,
122                                  size_t* frameCount);
123    // returns the audio output latency in ms. Corresponds to
124    // audio_stream_out->get_latency()
125    static status_t getLatency(audio_io_handle_t output,
126                               uint32_t* latency);
127
128    // return status NO_ERROR implies *buffSize > 0
129    // FIXME This API assumes a route, and so should deprecated.
130    static status_t getInputBufferSize(uint32_t sampleRate, audio_format_t format,
131        audio_channel_mask_t channelMask, size_t* buffSize);
132
133    static status_t setVoiceVolume(float volume);
134
135    // return the number of audio frames written by AudioFlinger to audio HAL and
136    // audio dsp to DAC since the specified output has exited standby.
137    // returned status (from utils/Errors.h) can be:
138    // - NO_ERROR: successful operation, halFrames and dspFrames point to valid data
139    // - INVALID_OPERATION: Not supported on current hardware platform
140    // - BAD_VALUE: invalid parameter
141    // NOTE: this feature is not supported on all hardware platforms and it is
142    // necessary to check returned status before using the returned values.
143    static status_t getRenderPosition(audio_io_handle_t output,
144                                      uint32_t *halFrames,
145                                      uint32_t *dspFrames);
146
147    // return the number of input frames lost by HAL implementation, or 0 if the handle is invalid
148    static uint32_t getInputFramesLost(audio_io_handle_t ioHandle);
149
150    // Allocate a new unique ID for use as an audio session ID or I/O handle.
151    // If unable to contact AudioFlinger, returns AUDIO_UNIQUE_ID_ALLOCATE instead.
152    // FIXME If AudioFlinger were to ever exhaust the unique ID namespace,
153    //       this method could fail by returning either AUDIO_UNIQUE_ID_ALLOCATE
154    //       or an unspecified existing unique ID.
155    static audio_unique_id_t newAudioUniqueId();
156
157    static void acquireAudioSessionId(int audioSession, pid_t pid);
158    static void releaseAudioSessionId(int audioSession, pid_t pid);
159
160    // Get the HW synchronization source used for an audio session.
161    // Return a valid source or AUDIO_HW_SYNC_INVALID if an error occurs
162    // or no HW sync source is used.
163    static audio_hw_sync_t getAudioHwSyncForSession(audio_session_t sessionId);
164
165    // Indicate JAVA services are ready (scheduling, power management ...)
166    static status_t systemReady();
167
168    // Events used to synchronize actions between audio sessions.
169    // For instance SYNC_EVENT_PRESENTATION_COMPLETE can be used to delay recording start until
170    // playback is complete on another audio session.
171    // See definitions in MediaSyncEvent.java
172    enum sync_event_t {
173        SYNC_EVENT_SAME = -1,             // used internally to indicate restart with same event
174        SYNC_EVENT_NONE = 0,
175        SYNC_EVENT_PRESENTATION_COMPLETE,
176
177        //
178        // Define new events here: SYNC_EVENT_START, SYNC_EVENT_STOP, SYNC_EVENT_TIME ...
179        //
180        SYNC_EVENT_CNT,
181    };
182
183    // Timeout for synchronous record start. Prevents from blocking the record thread forever
184    // if the trigger event is not fired.
185    static const uint32_t kSyncRecordStartTimeOutMs = 30000;
186
187    //
188    // IAudioPolicyService interface (see AudioPolicyInterface for method descriptions)
189    //
190    static status_t setDeviceConnectionState(audio_devices_t device, audio_policy_dev_state_t state,
191                                             const char *device_address, const char *device_name);
192    static audio_policy_dev_state_t getDeviceConnectionState(audio_devices_t device,
193                                                                const char *device_address);
194    static status_t setPhoneState(audio_mode_t state);
195    static status_t setForceUse(audio_policy_force_use_t usage, audio_policy_forced_cfg_t config);
196    static audio_policy_forced_cfg_t getForceUse(audio_policy_force_use_t usage);
197
198    // Client must successfully hand off the handle reference to AudioFlinger via createTrack(),
199    // or release it with releaseOutput().
200    static audio_io_handle_t getOutput(audio_stream_type_t stream,
201                                        uint32_t samplingRate = 0,
202                                        audio_format_t format = AUDIO_FORMAT_DEFAULT,
203                                        audio_channel_mask_t channelMask = AUDIO_CHANNEL_OUT_STEREO,
204                                        audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
205                                        const audio_offload_info_t *offloadInfo = NULL);
206    static status_t getOutputForAttr(const audio_attributes_t *attr,
207                                     audio_io_handle_t *output,
208                                     audio_session_t session,
209                                     audio_stream_type_t *stream,
210                                     uid_t uid,
211                                     uint32_t samplingRate = 0,
212                                     audio_format_t format = AUDIO_FORMAT_DEFAULT,
213                                     audio_channel_mask_t channelMask = AUDIO_CHANNEL_OUT_STEREO,
214                                     audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
215                                     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE,
216                                     const audio_offload_info_t *offloadInfo = NULL);
217    static status_t startOutput(audio_io_handle_t output,
218                                audio_stream_type_t stream,
219                                audio_session_t session);
220    static status_t stopOutput(audio_io_handle_t output,
221                               audio_stream_type_t stream,
222                               audio_session_t session);
223    static void releaseOutput(audio_io_handle_t output,
224                              audio_stream_type_t stream,
225                              audio_session_t session);
226
227    // Client must successfully hand off the handle reference to AudioFlinger via openRecord(),
228    // or release it with releaseInput().
229    static status_t getInputForAttr(const audio_attributes_t *attr,
230                                    audio_io_handle_t *input,
231                                    audio_session_t session,
232                                    uid_t uid,
233                                    uint32_t samplingRate,
234                                    audio_format_t format,
235                                    audio_channel_mask_t channelMask,
236                                    audio_input_flags_t flags,
237                                    audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE);
238
239    static status_t startInput(audio_io_handle_t input,
240                               audio_session_t session);
241    static status_t stopInput(audio_io_handle_t input,
242                              audio_session_t session);
243    static void releaseInput(audio_io_handle_t input,
244                             audio_session_t session);
245    static status_t initStreamVolume(audio_stream_type_t stream,
246                                      int indexMin,
247                                      int indexMax);
248    static status_t setStreamVolumeIndex(audio_stream_type_t stream,
249                                         int index,
250                                         audio_devices_t device);
251    static status_t getStreamVolumeIndex(audio_stream_type_t stream,
252                                         int *index,
253                                         audio_devices_t device);
254
255    static uint32_t getStrategyForStream(audio_stream_type_t stream);
256    static audio_devices_t getDevicesForStream(audio_stream_type_t stream);
257
258    static audio_io_handle_t getOutputForEffect(const effect_descriptor_t *desc);
259    static status_t registerEffect(const effect_descriptor_t *desc,
260                                    audio_io_handle_t io,
261                                    uint32_t strategy,
262                                    int session,
263                                    int id);
264    static status_t unregisterEffect(int id);
265    static status_t setEffectEnabled(int id, bool enabled);
266
267    // clear stream to output mapping cache (gStreamOutputMap)
268    // and output configuration cache (gOutputs)
269    static void clearAudioConfigCache();
270
271    static const sp<IAudioPolicyService> get_audio_policy_service();
272
273    // helpers for android.media.AudioManager.getProperty(), see description there for meaning
274    static uint32_t getPrimaryOutputSamplingRate();
275    static size_t getPrimaryOutputFrameCount();
276
277    static status_t setLowRamDevice(bool isLowRamDevice);
278
279    // Check if hw offload is possible for given format, stream type, sample rate,
280    // bit rate, duration, video and streaming or offload property is enabled
281    static bool isOffloadSupported(const audio_offload_info_t& info);
282
283    // check presence of audio flinger service.
284    // returns NO_ERROR if binding to service succeeds, DEAD_OBJECT otherwise
285    static status_t checkAudioFlinger();
286
287    /* List available audio ports and their attributes */
288    static status_t listAudioPorts(audio_port_role_t role,
289                                   audio_port_type_t type,
290                                   unsigned int *num_ports,
291                                   struct audio_port *ports,
292                                   unsigned int *generation);
293
294    /* Get attributes for a given audio port */
295    static status_t getAudioPort(struct audio_port *port);
296
297    /* Create an audio patch between several source and sink ports */
298    static status_t createAudioPatch(const struct audio_patch *patch,
299                                       audio_patch_handle_t *handle);
300
301    /* Release an audio patch */
302    static status_t releaseAudioPatch(audio_patch_handle_t handle);
303
304    /* List existing audio patches */
305    static status_t listAudioPatches(unsigned int *num_patches,
306                                      struct audio_patch *patches,
307                                      unsigned int *generation);
308    /* Set audio port configuration */
309    static status_t setAudioPortConfig(const struct audio_port_config *config);
310
311
312    static status_t acquireSoundTriggerSession(audio_session_t *session,
313                                           audio_io_handle_t *ioHandle,
314                                           audio_devices_t *device);
315    static status_t releaseSoundTriggerSession(audio_session_t session);
316
317    static audio_mode_t getPhoneState();
318
319    static status_t registerPolicyMixes(Vector<AudioMix> mixes, bool registration);
320
321    static status_t startAudioSource(const struct audio_port_config *source,
322                                      const audio_attributes_t *attributes,
323                                      audio_io_handle_t *handle);
324    static status_t stopAudioSource(audio_io_handle_t handle);
325
326    static status_t setMasterMono(bool mono);
327    static status_t getMasterMono(bool *mono);
328
329    // ----------------------------------------------------------------------------
330
331    class AudioPortCallback : public RefBase
332    {
333    public:
334
335                AudioPortCallback() {}
336        virtual ~AudioPortCallback() {}
337
338        virtual void onAudioPortListUpdate() = 0;
339        virtual void onAudioPatchListUpdate() = 0;
340        virtual void onServiceDied() = 0;
341
342    };
343
344    static status_t addAudioPortCallback(const sp<AudioPortCallback>& callback);
345    static status_t removeAudioPortCallback(const sp<AudioPortCallback>& callback);
346
347    class AudioDeviceCallback : public RefBase
348    {
349    public:
350
351                AudioDeviceCallback() {}
352        virtual ~AudioDeviceCallback() {}
353
354        virtual void onAudioDeviceUpdate(audio_io_handle_t audioIo,
355                                         audio_port_handle_t deviceId) = 0;
356    };
357
358    static status_t addAudioDeviceCallback(const sp<AudioDeviceCallback>& callback,
359                                           audio_io_handle_t audioIo);
360    static status_t removeAudioDeviceCallback(const sp<AudioDeviceCallback>& callback,
361                                              audio_io_handle_t audioIo);
362
363    static audio_port_handle_t getDeviceIdForIo(audio_io_handle_t audioIo);
364
365private:
366
367    class AudioFlingerClient: public IBinder::DeathRecipient, public BnAudioFlingerClient
368    {
369    public:
370        AudioFlingerClient() :
371            mInBuffSize(0), mInSamplingRate(0),
372            mInFormat(AUDIO_FORMAT_DEFAULT), mInChannelMask(AUDIO_CHANNEL_NONE) {
373        }
374
375        void clearIoCache();
376        status_t getInputBufferSize(uint32_t sampleRate, audio_format_t format,
377                                    audio_channel_mask_t channelMask, size_t* buffSize);
378        sp<AudioIoDescriptor> getIoDescriptor(audio_io_handle_t ioHandle);
379
380        // DeathRecipient
381        virtual void binderDied(const wp<IBinder>& who);
382
383        // IAudioFlingerClient
384
385        // indicate a change in the configuration of an output or input: keeps the cached
386        // values for output/input parameters up-to-date in client process
387        virtual void ioConfigChanged(audio_io_config_event event,
388                                     const sp<AudioIoDescriptor>& ioDesc);
389
390
391        status_t addAudioDeviceCallback(const sp<AudioDeviceCallback>& callback,
392                                               audio_io_handle_t audioIo);
393        status_t removeAudioDeviceCallback(const sp<AudioDeviceCallback>& callback,
394                                           audio_io_handle_t audioIo);
395
396        audio_port_handle_t getDeviceIdForIo(audio_io_handle_t audioIo);
397
398    private:
399        Mutex                               mLock;
400        DefaultKeyedVector<audio_io_handle_t, sp<AudioIoDescriptor> >   mIoDescriptors;
401        DefaultKeyedVector<audio_io_handle_t, Vector < sp<AudioDeviceCallback> > >
402                                                                        mAudioDeviceCallbacks;
403        // cached values for recording getInputBufferSize() queries
404        size_t                              mInBuffSize;    // zero indicates cache is invalid
405        uint32_t                            mInSamplingRate;
406        audio_format_t                      mInFormat;
407        audio_channel_mask_t                mInChannelMask;
408        sp<AudioIoDescriptor> getIoDescriptor_l(audio_io_handle_t ioHandle);
409    };
410
411    class AudioPolicyServiceClient: public IBinder::DeathRecipient,
412                                    public BnAudioPolicyServiceClient
413    {
414    public:
415        AudioPolicyServiceClient() {
416        }
417
418        int addAudioPortCallback(const sp<AudioPortCallback>& callback);
419        int removeAudioPortCallback(const sp<AudioPortCallback>& callback);
420
421        // DeathRecipient
422        virtual void binderDied(const wp<IBinder>& who);
423
424        // IAudioPolicyServiceClient
425        virtual void onAudioPortListUpdate();
426        virtual void onAudioPatchListUpdate();
427        virtual void onDynamicPolicyMixStateUpdate(String8 regId, int32_t state);
428        virtual void onRecordingConfigurationUpdate(int event, audio_session_t session,
429                        audio_source_t source, const audio_config_base_t *clientConfig,
430                        const audio_config_base_t *deviceConfig);
431
432    private:
433        Mutex                               mLock;
434        Vector <sp <AudioPortCallback> >    mAudioPortCallbacks;
435    };
436
437    static const sp<AudioFlingerClient> getAudioFlingerClient();
438    static sp<AudioIoDescriptor> getIoDescriptor(audio_io_handle_t ioHandle);
439
440    static sp<AudioFlingerClient> gAudioFlingerClient;
441    static sp<AudioPolicyServiceClient> gAudioPolicyServiceClient;
442    friend class AudioFlingerClient;
443    friend class AudioPolicyServiceClient;
444
445    static Mutex gLock;      // protects gAudioFlinger and gAudioErrorCallback,
446    static Mutex gLockAPS;   // protects gAudioPolicyService and gAudioPolicyServiceClient
447    static sp<IAudioFlinger> gAudioFlinger;
448    static audio_error_callback gAudioErrorCallback;
449    static dynamic_policy_callback gDynPolicyCallback;
450    static record_config_callback gRecordConfigCallback;
451
452    static size_t gInBuffSize;
453    // previous parameters for recording buffer size queries
454    static uint32_t gPrevInSamplingRate;
455    static audio_format_t gPrevInFormat;
456    static audio_channel_mask_t gPrevInChannelMask;
457
458    static sp<IAudioPolicyService> gAudioPolicyService;
459};
460
461};  // namespace android
462
463#endif  /*ANDROID_AUDIOSYSTEM_H_*/
464