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