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