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