AudioSystem.h revision be916aa1267e2e6b1c148f51d11bcbbc79cb864c
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 <utils/RefBase.h>
21#include <utils/threads.h>
22#include <media/IAudioFlinger.h>
23#include <media/AudioCommon.h>
24
25namespace android {
26
27typedef void (*audio_error_callback)(status_t err);
28typedef int audio_io_handle_t;
29
30class IAudioPolicyService;
31class String8;
32
33class AudioSystem
34{
35public:
36
37    enum stream_type {
38        DEFAULT          =-1,
39        VOICE_CALL       = 0,
40        SYSTEM           = 1,
41        RING             = 2,
42        MUSIC            = 3,
43        ALARM            = 4,
44        NOTIFICATION     = 5,
45        BLUETOOTH_SCO    = 6,
46        ENFORCED_AUDIBLE = 7, // Sounds that cannot be muted by user and must be routed to speaker
47        DTMF             = 8,
48        TTS              = 9,
49        NUM_STREAM_TYPES
50    };
51
52    // Audio sub formats (see AudioSystem::audio_format).
53    enum pcm_sub_format {
54        PCM_SUB_16_BIT          = PCM_FORMAT_S15, // must be 1 for backward compatibility
55        PCM_SUB_8_BIT           = PCM_FORMAT_U8, // must be 2 for backward compatibility
56    };
57
58    // MP3 sub format field definition : can use 11 LSBs in the same way as MP3 frame header to specify
59    // bit rate, stereo mode, version...
60    enum mp3_sub_format {
61        //TODO
62    };
63
64    // AMR NB/WB sub format field definition: specify frame block interleaving, bandwidth efficient or octet aligned,
65    // encoding mode for recording...
66    enum amr_sub_format {
67        //TODO
68    };
69
70    // AAC sub format field definition: specify profile or bitrate for recording...
71    enum aac_sub_format {
72        //TODO
73    };
74
75    // VORBIS sub format field definition: specify quality for recording...
76    enum vorbis_sub_format {
77        //TODO
78    };
79
80    // Audio format consists in a main format field (upper 8 bits) and a sub format field (lower 24 bits).
81    // The main format indicates the main codec type. The sub format field indicates options and parameters
82    // for each format. The sub format is mainly used for record to indicate for instance the requested bitrate
83    // or profile. It can also be used for certain formats to give informations not present in the encoded
84    // audio stream (e.g. octet alignement for AMR).
85    enum audio_format {
86        INVALID_FORMAT      = -1,
87        FORMAT_DEFAULT      = 0,
88        PCM                 = 0x00000000, // must be 0 for backward compatibility
89        MP3                 = 0x01000000,
90        AMR_NB              = 0x02000000,
91        AMR_WB              = 0x03000000,
92        AAC                 = 0x04000000,
93        HE_AAC_V1           = 0x05000000,
94        HE_AAC_V2           = 0x06000000,
95        VORBIS              = 0x07000000,
96        MAIN_FORMAT_MASK    = 0xFF000000,
97        SUB_FORMAT_MASK     = 0x00FFFFFF,
98        // Aliases
99        PCM_16_BIT          = (PCM|PCM_SUB_16_BIT),
100        PCM_8_BIT          = (PCM|PCM_SUB_8_BIT)
101    };
102
103
104    // Channel mask definitions must be kept in sync with JAVA values in /media/java/android/media/AudioFormat.java
105    enum audio_channels {
106        // output channels
107        CHANNEL_OUT_FRONT_LEFT = CHANNEL_FRONT_LEFT,
108        CHANNEL_OUT_FRONT_RIGHT = CHANNEL_FRONT_RIGHT,
109        CHANNEL_OUT_FRONT_CENTER = CHANNEL_FRONT_CENTER,
110        CHANNEL_OUT_LOW_FREQUENCY = CHANNEL_LOW_FREQUENCY,
111        CHANNEL_OUT_BACK_LEFT = CHANNEL_BACK_LEFT,
112        CHANNEL_OUT_BACK_RIGHT = CHANNEL_BACK_RIGHT,
113        CHANNEL_OUT_FRONT_LEFT_OF_CENTER = CHANNEL_FRONT_LEFT_OF_CENTER,
114        CHANNEL_OUT_FRONT_RIGHT_OF_CENTER = CHANNEL_FRONT_RIGHT_OF_CENTER,
115        CHANNEL_OUT_BACK_CENTER = CHANNEL_BACK_CENTER,
116        CHANNEL_OUT_MONO = CHANNEL_MONO,
117        CHANNEL_OUT_STEREO = CHANNEL_STEREO,
118        CHANNEL_OUT_QUAD = CHANNEL_QUAD,
119        CHANNEL_OUT_SURROUND = CHANNEL_SURROUND,
120        CHANNEL_OUT_5POINT1 = CHANNEL_5POINT1,
121        CHANNEL_OUT_7POINT1 = CHANNEL_7POINT1,
122        CHANNEL_OUT_ALL = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT |
123                CHANNEL_OUT_FRONT_CENTER | CHANNEL_OUT_LOW_FREQUENCY | CHANNEL_OUT_BACK_LEFT | CHANNEL_OUT_BACK_RIGHT |
124                CHANNEL_OUT_FRONT_LEFT_OF_CENTER | CHANNEL_OUT_FRONT_RIGHT_OF_CENTER | CHANNEL_OUT_BACK_CENTER),
125
126        // input channels
127        CHANNEL_IN_LEFT = 0x4,
128        CHANNEL_IN_RIGHT = 0x8,
129        CHANNEL_IN_FRONT = 0x10,
130        CHANNEL_IN_BACK = 0x20,
131        CHANNEL_IN_LEFT_PROCESSED = 0x40,
132        CHANNEL_IN_RIGHT_PROCESSED = 0x80,
133        CHANNEL_IN_FRONT_PROCESSED = 0x100,
134        CHANNEL_IN_BACK_PROCESSED = 0x200,
135        CHANNEL_IN_PRESSURE = 0x400,
136        CHANNEL_IN_X_AXIS = 0x800,
137        CHANNEL_IN_Y_AXIS = 0x1000,
138        CHANNEL_IN_Z_AXIS = 0x2000,
139        CHANNEL_IN_VOICE_UPLINK = 0x4000,
140        CHANNEL_IN_VOICE_DNLINK = 0x8000,
141        CHANNEL_IN_MONO = CHANNEL_IN_FRONT,
142        CHANNEL_IN_STEREO = (CHANNEL_IN_LEFT | CHANNEL_IN_RIGHT),
143        CHANNEL_IN_ALL = (CHANNEL_IN_LEFT | CHANNEL_IN_RIGHT | CHANNEL_IN_FRONT | CHANNEL_IN_BACK|
144                CHANNEL_IN_LEFT_PROCESSED | CHANNEL_IN_RIGHT_PROCESSED | CHANNEL_IN_FRONT_PROCESSED | CHANNEL_IN_BACK_PROCESSED|
145                CHANNEL_IN_PRESSURE | CHANNEL_IN_X_AXIS | CHANNEL_IN_Y_AXIS | CHANNEL_IN_Z_AXIS |
146                CHANNEL_IN_VOICE_UPLINK | CHANNEL_IN_VOICE_DNLINK)
147    };
148
149    enum audio_mode {
150        MODE_INVALID = -2,
151        MODE_CURRENT = -1,
152        MODE_NORMAL = 0,
153        MODE_RINGTONE,
154        MODE_IN_CALL,
155        NUM_MODES  // not a valid entry, denotes end-of-list
156    };
157
158    enum audio_in_acoustics {
159        AGC_ENABLE    = 0x0001,
160        AGC_DISABLE   = 0,
161        NS_ENABLE     = 0x0002,
162        NS_DISABLE    = 0,
163        TX_IIR_ENABLE = 0x0004,
164        TX_DISABLE    = 0
165    };
166
167    /* These are static methods to control the system-wide AudioFlinger
168     * only privileged processes can have access to them
169     */
170
171    // mute/unmute microphone
172    static status_t muteMicrophone(bool state);
173    static status_t isMicrophoneMuted(bool *state);
174
175    // set/get master volume
176    static status_t setMasterVolume(float value);
177    static status_t getMasterVolume(float* volume);
178    // mute/unmute audio outputs
179    static status_t setMasterMute(bool mute);
180    static status_t getMasterMute(bool* mute);
181
182    // set/get stream volume on specified output
183    static status_t setStreamVolume(int stream, float value, int output);
184    static status_t getStreamVolume(int stream, float* volume, int output);
185
186    // mute/unmute stream
187    static status_t setStreamMute(int stream, bool mute);
188    static status_t getStreamMute(int stream, bool* mute);
189
190    // set audio mode in audio hardware (see AudioSystem::audio_mode)
191    static status_t setMode(int mode);
192
193    // returns true in *state if tracks are active on the specified stream
194    static status_t isStreamActive(int stream, bool *state);
195
196    // set/get audio hardware parameters. The function accepts a list of parameters
197    // key value pairs in the form: key1=value1;key2=value2;...
198    // Some keys are reserved for standard parameters (See AudioParameter class).
199    static status_t setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs);
200    static String8  getParameters(audio_io_handle_t ioHandle, const String8& keys);
201
202    static void setErrorCallback(audio_error_callback cb);
203
204    // helper function to obtain AudioFlinger service handle
205    static const sp<IAudioFlinger>& get_audio_flinger();
206
207    static float linearToLog(int volume);
208    static int logToLinear(float volume);
209
210    static status_t getOutputSamplingRate(int* samplingRate, int stream = DEFAULT);
211    static status_t getOutputFrameCount(int* frameCount, int stream = DEFAULT);
212    static status_t getOutputLatency(uint32_t* latency, int stream = DEFAULT);
213
214    static bool routedToA2dpOutput(int streamType);
215
216    static status_t getInputBufferSize(uint32_t sampleRate, int format, int channelCount,
217        size_t* buffSize);
218
219    static status_t setVoiceVolume(float volume);
220
221    // return the number of audio frames written by AudioFlinger to audio HAL and
222    // audio dsp to DAC since the output on which the specificed stream is playing
223    // has exited standby.
224    // returned status (from utils/Errors.h) can be:
225    // - NO_ERROR: successful operation, halFrames and dspFrames point to valid data
226    // - INVALID_OPERATION: Not supported on current hardware platform
227    // - BAD_VALUE: invalid parameter
228    // NOTE: this feature is not supported on all hardware platforms and it is
229    // necessary to check returned status before using the returned values.
230    static status_t getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int stream = DEFAULT);
231
232    static unsigned int  getInputFramesLost(audio_io_handle_t ioHandle);
233
234    static int newAudioSessionId();
235    //
236    // AudioPolicyService interface
237    //
238
239    enum audio_devices {
240        // output devices
241        DEVICE_OUT_EARPIECE = DEVICE_EARPIECE,
242        DEVICE_OUT_SPEAKER = DEVICE_SPEAKER,
243        DEVICE_OUT_WIRED_HEADSET = DEVICE_WIRED_HEADSET,
244        DEVICE_OUT_WIRED_HEADPHONE = DEVICE_WIRED_HEADPHONE,
245        DEVICE_OUT_BLUETOOTH_SCO = DEVICE_BLUETOOTH_SCO,
246        DEVICE_OUT_BLUETOOTH_SCO_HEADSET = DEVICE_BLUETOOTH_SCO_HEADSET,
247        DEVICE_OUT_BLUETOOTH_SCO_CARKIT = DEVICE_BLUETOOTH_SCO_CARKIT,
248        DEVICE_OUT_BLUETOOTH_A2DP = DEVICE_BLUETOOTH_A2DP,
249        DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES = DEVICE_BLUETOOTH_A2DP_HEADPHONES,
250        DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER = DEVICE_BLUETOOTH_A2DP_SPEAKER,
251        DEVICE_OUT_AUX_DIGITAL = DEVICE_AUX_DIGITAL,
252        DEVICE_OUT_DEFAULT = 0x8000,
253        DEVICE_OUT_ALL = (DEVICE_OUT_EARPIECE | DEVICE_OUT_SPEAKER | DEVICE_OUT_WIRED_HEADSET |
254                DEVICE_OUT_WIRED_HEADPHONE | DEVICE_OUT_BLUETOOTH_SCO | DEVICE_OUT_BLUETOOTH_SCO_HEADSET |
255                DEVICE_OUT_BLUETOOTH_SCO_CARKIT | DEVICE_OUT_BLUETOOTH_A2DP | DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
256                DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER | DEVICE_OUT_AUX_DIGITAL | DEVICE_OUT_DEFAULT),
257        DEVICE_OUT_ALL_A2DP = (DEVICE_OUT_BLUETOOTH_A2DP | DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
258                DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
259
260        // input devices
261        DEVICE_IN_COMMUNICATION = 0x10000,
262        DEVICE_IN_AMBIENT = 0x20000,
263        DEVICE_IN_BUILTIN_MIC = 0x40000,
264        DEVICE_IN_BLUETOOTH_SCO_HEADSET = 0x80000,
265        DEVICE_IN_WIRED_HEADSET = 0x100000,
266        DEVICE_IN_AUX_DIGITAL = 0x200000,
267        DEVICE_IN_VOICE_CALL = 0x400000,
268        DEVICE_IN_BACK_MIC = 0x800000,
269        DEVICE_IN_DEFAULT = 0x80000000,
270
271        DEVICE_IN_ALL = (DEVICE_IN_COMMUNICATION | DEVICE_IN_AMBIENT | DEVICE_IN_BUILTIN_MIC |
272                DEVICE_IN_BLUETOOTH_SCO_HEADSET | DEVICE_IN_WIRED_HEADSET | DEVICE_IN_AUX_DIGITAL |
273                DEVICE_IN_VOICE_CALL | DEVICE_IN_BACK_MIC | DEVICE_IN_DEFAULT)
274    };
275
276    // device connection states used for setDeviceConnectionState()
277    enum device_connection_state {
278        DEVICE_STATE_UNAVAILABLE,
279        DEVICE_STATE_AVAILABLE,
280        NUM_DEVICE_STATES
281    };
282
283    // request to open a direct output with getOutput() (by opposition to sharing an output with other AudioTracks)
284    enum output_flags {
285        OUTPUT_FLAG_INDIRECT = 0x0,
286        OUTPUT_FLAG_DIRECT = 0x1
287    };
288
289    // device categories used for setForceUse()
290    enum forced_config {
291        FORCE_NONE,
292        FORCE_SPEAKER,
293        FORCE_HEADPHONES,
294        FORCE_BT_SCO,
295        FORCE_BT_A2DP,
296        FORCE_WIRED_ACCESSORY,
297        FORCE_BT_CAR_DOCK,
298        FORCE_BT_DESK_DOCK,
299        NUM_FORCE_CONFIG,
300        FORCE_DEFAULT = FORCE_NONE
301    };
302
303    // usages used for setForceUse()
304    enum force_use {
305        FOR_COMMUNICATION,
306        FOR_MEDIA,
307        FOR_RECORD,
308        FOR_DOCK,
309        NUM_FORCE_USE
310    };
311
312    // types of io configuration change events received with ioConfigChanged()
313    enum io_config_event {
314        OUTPUT_OPENED,
315        OUTPUT_CLOSED,
316        OUTPUT_CONFIG_CHANGED,
317        INPUT_OPENED,
318        INPUT_CLOSED,
319        INPUT_CONFIG_CHANGED,
320        STREAM_CONFIG_CHANGED,
321        NUM_CONFIG_EVENTS
322    };
323
324    // audio output descritor used to cache output configurations in client process to avoid frequent calls
325    // through IAudioFlinger
326    class OutputDescriptor {
327    public:
328        OutputDescriptor()
329        : samplingRate(0), format(0), channels(0), frameCount(0), latency(0)  {}
330
331        uint32_t samplingRate;
332        int32_t format;
333        int32_t channels;
334        size_t frameCount;
335        uint32_t latency;
336    };
337
338    //
339    // IAudioPolicyService interface (see AudioPolicyInterface for method descriptions)
340    //
341    static status_t setDeviceConnectionState(audio_devices device, device_connection_state state, const char *device_address);
342    static device_connection_state getDeviceConnectionState(audio_devices device, const char *device_address);
343    static status_t setPhoneState(int state);
344    static status_t setRingerMode(uint32_t mode, uint32_t mask);
345    static status_t setForceUse(force_use usage, forced_config config);
346    static forced_config getForceUse(force_use usage);
347    static audio_io_handle_t getOutput(stream_type stream,
348                                        uint32_t samplingRate = 0,
349                                        uint32_t format = FORMAT_DEFAULT,
350                                        uint32_t channels = CHANNEL_OUT_STEREO,
351                                        output_flags flags = OUTPUT_FLAG_INDIRECT);
352    static status_t startOutput(audio_io_handle_t output, AudioSystem::stream_type stream);
353    static status_t stopOutput(audio_io_handle_t output, AudioSystem::stream_type stream);
354    static void releaseOutput(audio_io_handle_t output);
355    static audio_io_handle_t getInput(int inputSource,
356                                    uint32_t samplingRate = 0,
357                                    uint32_t format = FORMAT_DEFAULT,
358                                    uint32_t channels = CHANNEL_IN_MONO,
359                                    audio_in_acoustics acoustics = (audio_in_acoustics)0);
360    static status_t startInput(audio_io_handle_t input);
361    static status_t stopInput(audio_io_handle_t input);
362    static void releaseInput(audio_io_handle_t input);
363    static status_t initStreamVolume(stream_type stream,
364                                      int indexMin,
365                                      int indexMax);
366    static status_t setStreamVolumeIndex(stream_type stream, int index);
367    static status_t getStreamVolumeIndex(stream_type stream, int *index);
368
369    static const sp<IAudioPolicyService>& get_audio_policy_service();
370
371    // ----------------------------------------------------------------------------
372
373    static uint32_t popCount(uint32_t u);
374    static bool isOutputDevice(audio_devices device);
375    static bool isInputDevice(audio_devices device);
376    static bool isA2dpDevice(audio_devices device);
377    static bool isBluetoothScoDevice(audio_devices device);
378    static bool isLowVisibility(stream_type stream);
379    static bool isOutputChannel(uint32_t channel);
380    static bool isInputChannel(uint32_t channel);
381    static bool isValidFormat(uint32_t format);
382    static bool isLinearPCM(uint32_t format);
383
384private:
385
386    class AudioFlingerClient: public IBinder::DeathRecipient, public BnAudioFlingerClient
387    {
388    public:
389        AudioFlingerClient() {
390        }
391
392        // DeathRecipient
393        virtual void binderDied(const wp<IBinder>& who);
394
395        // IAudioFlingerClient
396
397        // indicate a change in the configuration of an output or input: keeps the cached
398        // values for output/input parameters upto date in client process
399        virtual void ioConfigChanged(int event, int ioHandle, void *param2);
400    };
401
402    class AudioPolicyServiceClient: public IBinder::DeathRecipient
403    {
404    public:
405        AudioPolicyServiceClient() {
406        }
407
408        // DeathRecipient
409        virtual void binderDied(const wp<IBinder>& who);
410    };
411
412    static sp<AudioFlingerClient> gAudioFlingerClient;
413    static sp<AudioPolicyServiceClient> gAudioPolicyServiceClient;
414    friend class AudioFlingerClient;
415    friend class AudioPolicyServiceClient;
416
417    static Mutex gLock;
418    static sp<IAudioFlinger> gAudioFlinger;
419    static audio_error_callback gAudioErrorCallback;
420
421    static size_t gInBuffSize;
422    // previous parameters for recording buffer size queries
423    static uint32_t gPrevInSamplingRate;
424    static int gPrevInFormat;
425    static int gPrevInChannelCount;
426
427    static sp<IAudioPolicyService> gAudioPolicyService;
428
429    // mapping between stream types and outputs
430    static DefaultKeyedVector<int, audio_io_handle_t> gStreamOutputMap;
431    // list of output descritor containing cached parameters (sampling rate, framecount, channel count...)
432    static DefaultKeyedVector<audio_io_handle_t, OutputDescriptor *> gOutputs;
433};
434
435class AudioParameter {
436
437public:
438    AudioParameter() {}
439    AudioParameter(const String8& keyValuePairs);
440    virtual ~AudioParameter();
441
442    // reserved parameter keys for changeing standard parameters with setParameters() function.
443    // Using these keys is mandatory for AudioFlinger to properly monitor audio output/input
444    // configuration changes and act accordingly.
445    //  keyRouting: to change audio routing, value is an int in AudioSystem::audio_devices
446    //  keySamplingRate: to change sampling rate routing, value is an int
447    //  keyFormat: to change audio format, value is an int in AudioSystem::audio_format
448    //  keyChannels: to change audio channel configuration, value is an int in AudioSystem::audio_channels
449    //  keyFrameCount: to change audio output frame count, value is an int
450    static const char *keyRouting;
451    static const char *keySamplingRate;
452    static const char *keyFormat;
453    static const char *keyChannels;
454    static const char *keyFrameCount;
455
456    String8 toString();
457
458    status_t add(const String8& key, const String8& value);
459    status_t addInt(const String8& key, const int value);
460    status_t addFloat(const String8& key, const float value);
461
462    status_t remove(const String8& key);
463
464    status_t get(const String8& key, String8& value);
465    status_t getInt(const String8& key, int& value);
466    status_t getFloat(const String8& key, float& value);
467    status_t getAt(size_t index, String8& key, String8& value);
468
469    size_t size() { return mParameters.size(); }
470
471private:
472    String8 mKeyValuePairs;
473    KeyedVector <String8, String8> mParameters;
474};
475
476};  // namespace android
477
478#endif  /*ANDROID_AUDIOSYSTEM_H_*/
479