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