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