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/AudioDeviceTypeAddr.h>
23 #include <media/AudioPolicy.h>
24 #include <media/AudioProductStrategy.h>
25 #include <media/AudioVolumeGroup.h>
26 #include <media/AudioIoDescriptor.h>
27 #include <media/IAudioFlingerClient.h>
28 #include <media/IAudioPolicyServiceClient.h>
29 #include <media/MicrophoneInfo.h>
30 #include <set>
31 #include <system/audio.h>
32 #include <system/audio_effect.h>
33 #include <system/audio_policy.h>
34 #include <utils/Errors.h>
35 #include <utils/Mutex.h>
36 #include <vector>
37 
38 namespace android {
39 
40 typedef void (*audio_error_callback)(status_t err);
41 typedef void (*dynamic_policy_callback)(int event, String8 regId, int val);
42 typedef void (*record_config_callback)(int event,
43                                        const record_client_info_t *clientInfo,
44                                        const audio_config_base_t *clientConfig,
45                                        std::vector<effect_descriptor_t> clientEffects,
46                                        const audio_config_base_t *deviceConfig,
47                                        std::vector<effect_descriptor_t> effects,
48                                        audio_patch_handle_t patchHandle,
49                                        audio_source_t source);
50 
51 class IAudioFlinger;
52 class IAudioPolicyService;
53 class String8;
54 
55 class AudioSystem
56 {
57 public:
58 
59     // FIXME Declare in binder opcode order, similarly to IAudioFlinger.h and IAudioFlinger.cpp
60 
61     /* These are static methods to control the system-wide AudioFlinger
62      * only privileged processes can have access to them
63      */
64 
65     // mute/unmute microphone
66     static status_t muteMicrophone(bool state);
67     static status_t isMicrophoneMuted(bool *state);
68 
69     // set/get master volume
70     static status_t setMasterVolume(float value);
71     static status_t getMasterVolume(float* volume);
72 
73     // mute/unmute audio outputs
74     static status_t setMasterMute(bool mute);
75     static status_t getMasterMute(bool* mute);
76 
77     // set/get stream volume on specified output
78     static status_t setStreamVolume(audio_stream_type_t stream, float value,
79                                     audio_io_handle_t output);
80     static status_t getStreamVolume(audio_stream_type_t stream, float* volume,
81                                     audio_io_handle_t output);
82 
83     // mute/unmute stream
84     static status_t setStreamMute(audio_stream_type_t stream, bool mute);
85     static status_t getStreamMute(audio_stream_type_t stream, bool* mute);
86 
87     // set audio mode in audio hardware
88     static status_t setMode(audio_mode_t mode);
89 
90     // returns true in *state if tracks are active on the specified stream or have been active
91     // in the past inPastMs milliseconds
92     static status_t isStreamActive(audio_stream_type_t stream, bool *state, uint32_t inPastMs);
93     // returns true in *state if tracks are active for what qualifies as remote playback
94     // on the specified stream or have been active in the past inPastMs milliseconds. Remote
95     // playback isn't mutually exclusive with local playback.
96     static status_t isStreamActiveRemotely(audio_stream_type_t stream, bool *state,
97             uint32_t inPastMs);
98     // returns true in *state if a recorder is currently recording with the specified source
99     static status_t isSourceActive(audio_source_t source, bool *state);
100 
101     // set/get audio hardware parameters. The function accepts a list of parameters
102     // key value pairs in the form: key1=value1;key2=value2;...
103     // Some keys are reserved for standard parameters (See AudioParameter class).
104     // The versions with audio_io_handle_t are intended for internal media framework use only.
105     static status_t setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs);
106     static String8  getParameters(audio_io_handle_t ioHandle, const String8& keys);
107     // The versions without audio_io_handle_t are intended for JNI.
108     static status_t setParameters(const String8& keyValuePairs);
109     static String8  getParameters(const String8& keys);
110 
111     // Registers an error callback. When this callback is invoked, it means all
112     // state implied by this interface has been reset.
113     // Returns a token that can be used for un-registering.
114     // Might block while callbacks are being invoked.
115     static uintptr_t addErrorCallback(audio_error_callback cb);
116 
117     // Un-registers a callback previously added with addErrorCallback.
118     // Might block while callbacks are being invoked.
119     static void removeErrorCallback(uintptr_t cb);
120 
121     static void setDynPolicyCallback(dynamic_policy_callback cb);
122     static void setRecordConfigCallback(record_config_callback);
123 
124     // helper function to obtain AudioFlinger service handle
125     static const sp<IAudioFlinger> get_audio_flinger();
126 
127     static float linearToLog(int volume);
128     static int logToLinear(float volume);
129     static size_t calculateMinFrameCount(
130             uint32_t afLatencyMs, uint32_t afFrameCount, uint32_t afSampleRate,
131             uint32_t sampleRate, float speed /*, uint32_t notificationsPerBufferReq*/);
132 
133     // Returned samplingRate and frameCount output values are guaranteed
134     // to be non-zero if status == NO_ERROR
135     // FIXME This API assumes a route, and so should be deprecated.
136     static status_t getOutputSamplingRate(uint32_t* samplingRate,
137             audio_stream_type_t stream);
138     // FIXME This API assumes a route, and so should be deprecated.
139     static status_t getOutputFrameCount(size_t* frameCount,
140             audio_stream_type_t stream);
141     // FIXME This API assumes a route, and so should be deprecated.
142     static status_t getOutputLatency(uint32_t* latency,
143             audio_stream_type_t stream);
144     // returns the audio HAL sample rate
145     static status_t getSamplingRate(audio_io_handle_t ioHandle,
146                                           uint32_t* samplingRate);
147     // For output threads with a fast mixer, returns the number of frames per normal mixer buffer.
148     // For output threads without a fast mixer, or for input, this is same as getFrameCountHAL().
149     static status_t getFrameCount(audio_io_handle_t ioHandle,
150                                   size_t* frameCount);
151     // returns the audio output latency in ms. Corresponds to
152     // audio_stream_out->get_latency()
153     static status_t getLatency(audio_io_handle_t output,
154                                uint32_t* latency);
155 
156     // return status NO_ERROR implies *buffSize > 0
157     // FIXME This API assumes a route, and so should deprecated.
158     static status_t getInputBufferSize(uint32_t sampleRate, audio_format_t format,
159         audio_channel_mask_t channelMask, size_t* buffSize);
160 
161     static status_t setVoiceVolume(float volume);
162 
163     // return the number of audio frames written by AudioFlinger to audio HAL and
164     // audio dsp to DAC since the specified output has exited standby.
165     // returned status (from utils/Errors.h) can be:
166     // - NO_ERROR: successful operation, halFrames and dspFrames point to valid data
167     // - INVALID_OPERATION: Not supported on current hardware platform
168     // - BAD_VALUE: invalid parameter
169     // NOTE: this feature is not supported on all hardware platforms and it is
170     // necessary to check returned status before using the returned values.
171     static status_t getRenderPosition(audio_io_handle_t output,
172                                       uint32_t *halFrames,
173                                       uint32_t *dspFrames);
174 
175     // return the number of input frames lost by HAL implementation, or 0 if the handle is invalid
176     static uint32_t getInputFramesLost(audio_io_handle_t ioHandle);
177 
178     // Allocate a new unique ID for use as an audio session ID or I/O handle.
179     // If unable to contact AudioFlinger, returns AUDIO_UNIQUE_ID_ALLOCATE instead.
180     // FIXME If AudioFlinger were to ever exhaust the unique ID namespace,
181     //       this method could fail by returning either a reserved ID like AUDIO_UNIQUE_ID_ALLOCATE
182     //       or an unspecified existing unique ID.
183     static audio_unique_id_t newAudioUniqueId(audio_unique_id_use_t use);
184 
185     static void acquireAudioSessionId(audio_session_t audioSession, pid_t pid, uid_t uid);
186     static void releaseAudioSessionId(audio_session_t audioSession, pid_t pid);
187 
188     // Get the HW synchronization source used for an audio session.
189     // Return a valid source or AUDIO_HW_SYNC_INVALID if an error occurs
190     // or no HW sync source is used.
191     static audio_hw_sync_t getAudioHwSyncForSession(audio_session_t sessionId);
192 
193     // Indicate JAVA services are ready (scheduling, power management ...)
194     static status_t systemReady();
195 
196     // Returns the number of frames per audio HAL buffer.
197     // Corresponds to audio_stream->get_buffer_size()/audio_stream_in_frame_size() for input.
198     // See also getFrameCount().
199     static status_t getFrameCountHAL(audio_io_handle_t ioHandle,
200                                      size_t* frameCount);
201 
202     // Events used to synchronize actions between audio sessions.
203     // For instance SYNC_EVENT_PRESENTATION_COMPLETE can be used to delay recording start until
204     // playback is complete on another audio session.
205     // See definitions in MediaSyncEvent.java
206     enum sync_event_t {
207         SYNC_EVENT_SAME = -1,             // used internally to indicate restart with same event
208         SYNC_EVENT_NONE = 0,
209         SYNC_EVENT_PRESENTATION_COMPLETE,
210 
211         //
212         // Define new events here: SYNC_EVENT_START, SYNC_EVENT_STOP, SYNC_EVENT_TIME ...
213         //
214         SYNC_EVENT_CNT,
215     };
216 
217     // Timeout for synchronous record start. Prevents from blocking the record thread forever
218     // if the trigger event is not fired.
219     static const uint32_t kSyncRecordStartTimeOutMs = 30000;
220 
221     //
222     // IAudioPolicyService interface (see AudioPolicyInterface for method descriptions)
223     //
224     static void onNewAudioModulesAvailable();
225     static status_t setDeviceConnectionState(audio_devices_t device, audio_policy_dev_state_t state,
226                                              const char *device_address, const char *device_name,
227                                              audio_format_t encodedFormat);
228     static audio_policy_dev_state_t getDeviceConnectionState(audio_devices_t device,
229                                                                 const char *device_address);
230     static status_t handleDeviceConfigChange(audio_devices_t device,
231                                              const char *device_address,
232                                              const char *device_name,
233                                              audio_format_t encodedFormat);
234     static status_t setPhoneState(audio_mode_t state, uid_t uid);
235     static status_t setForceUse(audio_policy_force_use_t usage, audio_policy_forced_cfg_t config);
236     static audio_policy_forced_cfg_t getForceUse(audio_policy_force_use_t usage);
237 
238     static status_t getOutputForAttr(audio_attributes_t *attr,
239                                      audio_io_handle_t *output,
240                                      audio_session_t session,
241                                      audio_stream_type_t *stream,
242                                      pid_t pid,
243                                      uid_t uid,
244                                      const audio_config_t *config,
245                                      audio_output_flags_t flags,
246                                      audio_port_handle_t *selectedDeviceId,
247                                      audio_port_handle_t *portId,
248                                      std::vector<audio_io_handle_t> *secondaryOutputs);
249     static status_t startOutput(audio_port_handle_t portId);
250     static status_t stopOutput(audio_port_handle_t portId);
251     static void releaseOutput(audio_port_handle_t portId);
252 
253     // Client must successfully hand off the handle reference to AudioFlinger via createRecord(),
254     // or release it with releaseInput().
255     static status_t getInputForAttr(const audio_attributes_t *attr,
256                                     audio_io_handle_t *input,
257                                     audio_unique_id_t riid,
258                                     audio_session_t session,
259                                     pid_t pid,
260                                     uid_t uid,
261                                     const String16& opPackageName,
262                                     const audio_config_base_t *config,
263                                     audio_input_flags_t flags,
264                                     audio_port_handle_t *selectedDeviceId,
265                                     audio_port_handle_t *portId);
266 
267     static status_t startInput(audio_port_handle_t portId);
268     static status_t stopInput(audio_port_handle_t portId);
269     static void releaseInput(audio_port_handle_t portId);
270     static status_t initStreamVolume(audio_stream_type_t stream,
271                                       int indexMin,
272                                       int indexMax);
273     static status_t setStreamVolumeIndex(audio_stream_type_t stream,
274                                          int index,
275                                          audio_devices_t device);
276     static status_t getStreamVolumeIndex(audio_stream_type_t stream,
277                                          int *index,
278                                          audio_devices_t device);
279 
280     static status_t setVolumeIndexForAttributes(const audio_attributes_t &attr,
281                                                 int index,
282                                                 audio_devices_t device);
283     static status_t getVolumeIndexForAttributes(const audio_attributes_t &attr,
284                                                 int &index,
285                                                 audio_devices_t device);
286 
287     static status_t getMaxVolumeIndexForAttributes(const audio_attributes_t &attr, int &index);
288 
289     static status_t getMinVolumeIndexForAttributes(const audio_attributes_t &attr, int &index);
290 
291     static uint32_t getStrategyForStream(audio_stream_type_t stream);
292     static audio_devices_t getDevicesForStream(audio_stream_type_t stream);
293     static status_t getDevicesForAttributes(const AudioAttributes &aa,
294                                             AudioDeviceTypeAddrVector *devices);
295 
296     static audio_io_handle_t getOutputForEffect(const effect_descriptor_t *desc);
297     static status_t registerEffect(const effect_descriptor_t *desc,
298                                     audio_io_handle_t io,
299                                     uint32_t strategy,
300                                     audio_session_t session,
301                                     int id);
302     static status_t unregisterEffect(int id);
303     static status_t setEffectEnabled(int id, bool enabled);
304     static status_t moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io);
305 
306     // clear stream to output mapping cache (gStreamOutputMap)
307     // and output configuration cache (gOutputs)
308     static void clearAudioConfigCache();
309 
310     static const sp<IAudioPolicyService> get_audio_policy_service();
311 
312     // helpers for android.media.AudioManager.getProperty(), see description there for meaning
313     static uint32_t getPrimaryOutputSamplingRate();
314     static size_t getPrimaryOutputFrameCount();
315 
316     static status_t setLowRamDevice(bool isLowRamDevice, int64_t totalMemory);
317 
318     static status_t setSupportedSystemUsages(const std::vector<audio_usage_t>& systemUsages);
319 
320     static status_t setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t flags);
321 
322     // Check if hw offload is possible for given format, stream type, sample rate,
323     // bit rate, duration, video and streaming or offload property is enabled
324     static bool isOffloadSupported(const audio_offload_info_t& info);
325 
326     // check presence of audio flinger service.
327     // returns NO_ERROR if binding to service succeeds, DEAD_OBJECT otherwise
328     static status_t checkAudioFlinger();
329 
330     /* List available audio ports and their attributes */
331     static status_t listAudioPorts(audio_port_role_t role,
332                                    audio_port_type_t type,
333                                    unsigned int *num_ports,
334                                    struct audio_port *ports,
335                                    unsigned int *generation);
336 
337     /* Get attributes for a given audio port */
338     static status_t getAudioPort(struct audio_port *port);
339 
340     /* Create an audio patch between several source and sink ports */
341     static status_t createAudioPatch(const struct audio_patch *patch,
342                                        audio_patch_handle_t *handle);
343 
344     /* Release an audio patch */
345     static status_t releaseAudioPatch(audio_patch_handle_t handle);
346 
347     /* List existing audio patches */
348     static status_t listAudioPatches(unsigned int *num_patches,
349                                       struct audio_patch *patches,
350                                       unsigned int *generation);
351     /* Set audio port configuration */
352     static status_t setAudioPortConfig(const struct audio_port_config *config);
353 
354 
355     static status_t acquireSoundTriggerSession(audio_session_t *session,
356                                            audio_io_handle_t *ioHandle,
357                                            audio_devices_t *device);
358     static status_t releaseSoundTriggerSession(audio_session_t session);
359 
360     static audio_mode_t getPhoneState();
361 
362     static status_t registerPolicyMixes(const Vector<AudioMix>& mixes, bool registration);
363 
364     static status_t setUidDeviceAffinities(uid_t uid, const Vector<AudioDeviceTypeAddr>& devices);
365 
366     static status_t removeUidDeviceAffinities(uid_t uid);
367 
368     static status_t setUserIdDeviceAffinities(int userId, const Vector<AudioDeviceTypeAddr>& devices);
369 
370     static status_t removeUserIdDeviceAffinities(int userId);
371 
372     static status_t startAudioSource(const struct audio_port_config *source,
373                                      const audio_attributes_t *attributes,
374                                      audio_port_handle_t *portId);
375     static status_t stopAudioSource(audio_port_handle_t portId);
376 
377     static status_t setMasterMono(bool mono);
378     static status_t getMasterMono(bool *mono);
379 
380     static status_t setMasterBalance(float balance);
381     static status_t getMasterBalance(float *balance);
382 
383     static float    getStreamVolumeDB(
384             audio_stream_type_t stream, int index, audio_devices_t device);
385 
386     static status_t getMicrophones(std::vector<media::MicrophoneInfo> *microphones);
387 
388     static status_t getHwOffloadEncodingFormatsSupportedForA2DP(
389                                     std::vector<audio_format_t> *formats);
390 
391     // numSurroundFormats holds the maximum number of formats and bool value allowed in the array.
392     // When numSurroundFormats is 0, surroundFormats and surroundFormatsEnabled will not be
393     // populated. The actual number of surround formats should be returned at numSurroundFormats.
394     static status_t getSurroundFormats(unsigned int *numSurroundFormats,
395                                        audio_format_t *surroundFormats,
396                                        bool *surroundFormatsEnabled,
397                                        bool reported);
398     static status_t setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled);
399 
400     static status_t setAssistantUid(uid_t uid);
401     static status_t setA11yServicesUids(const std::vector<uid_t>& uids);
402     static status_t setCurrentImeUid(uid_t uid);
403 
404     static bool     isHapticPlaybackSupported();
405 
406     static status_t listAudioProductStrategies(AudioProductStrategyVector &strategies);
407     static status_t getProductStrategyFromAudioAttributes(const AudioAttributes &aa,
408                                                         product_strategy_t &productStrategy);
409 
410     static audio_attributes_t streamTypeToAttributes(audio_stream_type_t stream);
411     static audio_stream_type_t attributesToStreamType(const audio_attributes_t &attr);
412 
413     static status_t listAudioVolumeGroups(AudioVolumeGroupVector &groups);
414 
415     static status_t getVolumeGroupFromAudioAttributes(const AudioAttributes &aa,
416                                                       volume_group_t &volumeGroup);
417 
418     static status_t setRttEnabled(bool enabled);
419 
420     static bool     isCallScreenModeSupported();
421 
422      /**
423      * Send audio HAL server process pids to native audioserver process for use
424      * when generating audio HAL servers tombstones
425      */
426     static status_t setAudioHalPids(const std::vector<pid_t>& pids);
427 
428     static status_t setPreferredDeviceForStrategy(product_strategy_t strategy,
429             const AudioDeviceTypeAddr &device);
430 
431     static status_t removePreferredDeviceForStrategy(product_strategy_t strategy);
432 
433     static status_t getPreferredDeviceForStrategy(product_strategy_t strategy,
434             AudioDeviceTypeAddr &device);
435 
436     static status_t getDeviceForStrategy(product_strategy_t strategy,
437             AudioDeviceTypeAddr &device);
438 
439     // A listener for capture state changes.
440     class CaptureStateListener : public RefBase {
441     public:
442         // Called whenever capture state changes.
443         virtual void onStateChanged(bool active) = 0;
444         // Called whenever the service dies (and hence our listener is no longer
445         // registered).
446         virtual void onServiceDied() = 0;
447 
448         virtual ~CaptureStateListener() = default;
449     };
450 
451     // Regiseters a listener for sound trigger capture state changes.
452     // There may only be one such listener registered at any point.
453     // The listener onStateChanged() method will be invoked sychronously from
454     // this call with the initial value.
455     // The listener onServiceDied() method will be invoked sychronously from
456     // this call if initial attempt to register failed.
457     // If the audio policy service cannot be reached, this method will return
458     // PERMISSION_DENIED and will not invoke the callback, otherwise, it will
459     // return NO_ERROR.
460     static status_t registerSoundTriggerCaptureStateListener(
461             const sp<CaptureStateListener>& listener);
462 
463     // ----------------------------------------------------------------------------
464 
465     class AudioVolumeGroupCallback : public RefBase
466     {
467     public:
468 
AudioVolumeGroupCallback()469         AudioVolumeGroupCallback() {}
~AudioVolumeGroupCallback()470         virtual ~AudioVolumeGroupCallback() {}
471 
472         virtual void onAudioVolumeGroupChanged(volume_group_t group, int flags) = 0;
473         virtual void onServiceDied() = 0;
474 
475     };
476 
477     static status_t addAudioVolumeGroupCallback(const sp<AudioVolumeGroupCallback>& callback);
478     static status_t removeAudioVolumeGroupCallback(const sp<AudioVolumeGroupCallback>& callback);
479 
480     class AudioPortCallback : public RefBase
481     {
482     public:
483 
AudioPortCallback()484                 AudioPortCallback() {}
~AudioPortCallback()485         virtual ~AudioPortCallback() {}
486 
487         virtual void onAudioPortListUpdate() = 0;
488         virtual void onAudioPatchListUpdate() = 0;
489         virtual void onServiceDied() = 0;
490 
491     };
492 
493     static status_t addAudioPortCallback(const sp<AudioPortCallback>& callback);
494     static status_t removeAudioPortCallback(const sp<AudioPortCallback>& callback);
495 
496     class AudioDeviceCallback : public RefBase
497     {
498     public:
499 
AudioDeviceCallback()500                 AudioDeviceCallback() {}
~AudioDeviceCallback()501         virtual ~AudioDeviceCallback() {}
502 
503         virtual void onAudioDeviceUpdate(audio_io_handle_t audioIo,
504                                          audio_port_handle_t deviceId) = 0;
505     };
506 
507     static status_t addAudioDeviceCallback(const wp<AudioDeviceCallback>& callback,
508                                            audio_io_handle_t audioIo,
509                                            audio_port_handle_t portId);
510     static status_t removeAudioDeviceCallback(const wp<AudioDeviceCallback>& callback,
511                                               audio_io_handle_t audioIo,
512                                               audio_port_handle_t portId);
513 
514     static audio_port_handle_t getDeviceIdForIo(audio_io_handle_t audioIo);
515 
516 private:
517 
518     class AudioFlingerClient: public IBinder::DeathRecipient, public BnAudioFlingerClient
519     {
520     public:
AudioFlingerClient()521         AudioFlingerClient() :
522             mInBuffSize(0), mInSamplingRate(0),
523             mInFormat(AUDIO_FORMAT_DEFAULT), mInChannelMask(AUDIO_CHANNEL_NONE) {
524         }
525 
526         void clearIoCache();
527         status_t getInputBufferSize(uint32_t sampleRate, audio_format_t format,
528                                     audio_channel_mask_t channelMask, size_t* buffSize);
529         sp<AudioIoDescriptor> getIoDescriptor(audio_io_handle_t ioHandle);
530 
531         // DeathRecipient
532         virtual void binderDied(const wp<IBinder>& who);
533 
534         // IAudioFlingerClient
535 
536         // indicate a change in the configuration of an output or input: keeps the cached
537         // values for output/input parameters up-to-date in client process
538         virtual void ioConfigChanged(audio_io_config_event event,
539                                      const sp<AudioIoDescriptor>& ioDesc);
540 
541 
542         status_t addAudioDeviceCallback(const wp<AudioDeviceCallback>& callback,
543                                                audio_io_handle_t audioIo,
544                                                audio_port_handle_t portId);
545         status_t removeAudioDeviceCallback(const wp<AudioDeviceCallback>& callback,
546                                            audio_io_handle_t audioIo,
547                                            audio_port_handle_t portId);
548 
549         audio_port_handle_t getDeviceIdForIo(audio_io_handle_t audioIo);
550 
551     private:
552         Mutex                               mLock;
553         DefaultKeyedVector<audio_io_handle_t, sp<AudioIoDescriptor> >   mIoDescriptors;
554 
555         std::map<audio_io_handle_t, std::map<audio_port_handle_t, wp<AudioDeviceCallback>>>
556                 mAudioDeviceCallbacks;
557         // cached values for recording getInputBufferSize() queries
558         size_t                              mInBuffSize;    // zero indicates cache is invalid
559         uint32_t                            mInSamplingRate;
560         audio_format_t                      mInFormat;
561         audio_channel_mask_t                mInChannelMask;
562         sp<AudioIoDescriptor> getIoDescriptor_l(audio_io_handle_t ioHandle);
563     };
564 
565     class AudioPolicyServiceClient: public IBinder::DeathRecipient,
566                                     public BnAudioPolicyServiceClient
567     {
568     public:
AudioPolicyServiceClient()569         AudioPolicyServiceClient() {
570         }
571 
572         int addAudioPortCallback(const sp<AudioPortCallback>& callback);
573         int removeAudioPortCallback(const sp<AudioPortCallback>& callback);
isAudioPortCbEnabled()574         bool isAudioPortCbEnabled() const { return (mAudioPortCallbacks.size() != 0); }
575 
576         int addAudioVolumeGroupCallback(const sp<AudioVolumeGroupCallback>& callback);
577         int removeAudioVolumeGroupCallback(const sp<AudioVolumeGroupCallback>& callback);
isAudioVolumeGroupCbEnabled()578         bool isAudioVolumeGroupCbEnabled() const { return (mAudioVolumeGroupCallback.size() != 0); }
579 
580         // DeathRecipient
581         virtual void binderDied(const wp<IBinder>& who);
582 
583         // IAudioPolicyServiceClient
584         virtual void onAudioPortListUpdate();
585         virtual void onAudioPatchListUpdate();
586         virtual void onAudioVolumeGroupChanged(volume_group_t group, int flags);
587         virtual void onDynamicPolicyMixStateUpdate(String8 regId, int32_t state);
588         virtual void onRecordingConfigurationUpdate(int event,
589                                                     const record_client_info_t *clientInfo,
590                                                     const audio_config_base_t *clientConfig,
591                                                     std::vector<effect_descriptor_t> clientEffects,
592                                                     const audio_config_base_t *deviceConfig,
593                                                     std::vector<effect_descriptor_t> effects,
594                                                     audio_patch_handle_t patchHandle,
595                                                     audio_source_t source);
596 
597     private:
598         Mutex                               mLock;
599         Vector <sp <AudioPortCallback> >    mAudioPortCallbacks;
600         Vector <sp <AudioVolumeGroupCallback> > mAudioVolumeGroupCallback;
601     };
602 
603     static audio_io_handle_t getOutput(audio_stream_type_t stream);
604     static const sp<AudioFlingerClient> getAudioFlingerClient();
605     static sp<AudioIoDescriptor> getIoDescriptor(audio_io_handle_t ioHandle);
606 
607     // Invokes all registered error callbacks with the given error code.
608     static void reportError(status_t err);
609 
610     static sp<AudioFlingerClient> gAudioFlingerClient;
611     static sp<AudioPolicyServiceClient> gAudioPolicyServiceClient;
612     friend class AudioFlingerClient;
613     friend class AudioPolicyServiceClient;
614 
615     static Mutex gLock;      // protects gAudioFlinger
616     static Mutex gLockErrorCallbacks;      // protects gAudioErrorCallbacks
617     static Mutex gLockAPS;   // protects gAudioPolicyService and gAudioPolicyServiceClient
618     static sp<IAudioFlinger> gAudioFlinger;
619     static std::set<audio_error_callback> gAudioErrorCallbacks;
620     static dynamic_policy_callback gDynPolicyCallback;
621     static record_config_callback gRecordConfigCallback;
622 
623     static size_t gInBuffSize;
624     // previous parameters for recording buffer size queries
625     static uint32_t gPrevInSamplingRate;
626     static audio_format_t gPrevInFormat;
627     static audio_channel_mask_t gPrevInChannelMask;
628 
629     static sp<IAudioPolicyService> gAudioPolicyService;
630 };
631 
632 };  // namespace android
633 
634 #endif  /*ANDROID_AUDIOSYSTEM_H_*/
635