• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2009 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_AUDIOPOLICYSERVICE_H
18 #define ANDROID_AUDIOPOLICYSERVICE_H
19 
20 #include <cutils/misc.h>
21 #include <cutils/config_utils.h>
22 #include <cutils/compiler.h>
23 #include <utils/String8.h>
24 #include <utils/Vector.h>
25 #include <utils/SortedVector.h>
26 #include <binder/BinderService.h>
27 #include <system/audio.h>
28 #include <system/audio_policy.h>
29 #include <media/IAudioPolicyService.h>
30 #include <media/ToneGenerator.h>
31 #include <media/AudioEffect.h>
32 #include <media/AudioPolicy.h>
33 #include "AudioPolicyEffects.h"
34 #include "managerdefault/AudioPolicyManager.h"
35 
36 
37 namespace android {
38 
39 // ----------------------------------------------------------------------------
40 
41 class AudioPolicyService :
42     public BinderService<AudioPolicyService>,
43     public BnAudioPolicyService,
44     public IBinder::DeathRecipient
45 {
46     friend class BinderService<AudioPolicyService>;
47 
48 public:
49     // for BinderService
getServiceName()50     static const char *getServiceName() ANDROID_API { return "media.audio_policy"; }
51 
52     virtual status_t    dump(int fd, const Vector<String16>& args);
53 
54     //
55     // BnAudioPolicyService (see AudioPolicyInterface for method descriptions)
56     //
57 
58     virtual status_t setDeviceConnectionState(audio_devices_t device,
59                                               audio_policy_dev_state_t state,
60                                               const char *device_address,
61                                               const char *device_name);
62     virtual audio_policy_dev_state_t getDeviceConnectionState(
63                                                                 audio_devices_t device,
64                                                                 const char *device_address);
65     virtual status_t handleDeviceConfigChange(audio_devices_t device,
66                                               const char *device_address,
67                                               const char *device_name);
68     virtual status_t setPhoneState(audio_mode_t state);
69     virtual status_t setForceUse(audio_policy_force_use_t usage, audio_policy_forced_cfg_t config);
70     virtual audio_policy_forced_cfg_t getForceUse(audio_policy_force_use_t usage);
71     virtual audio_io_handle_t getOutput(audio_stream_type_t stream,
72                                         uint32_t samplingRate = 0,
73                                         audio_format_t format = AUDIO_FORMAT_DEFAULT,
74                                         audio_channel_mask_t channelMask = 0,
75                                         audio_output_flags_t flags =
76                                                 AUDIO_OUTPUT_FLAG_NONE,
77                                         const audio_offload_info_t *offloadInfo = NULL);
78     virtual status_t getOutputForAttr(const audio_attributes_t *attr,
79                                       audio_io_handle_t *output,
80                                       audio_session_t session,
81                                       audio_stream_type_t *stream,
82                                       uid_t uid,
83                                       const audio_config_t *config,
84                                       audio_output_flags_t flags,
85                                       audio_port_handle_t *selectedDeviceId,
86                                       audio_port_handle_t *portId);
87     virtual status_t startOutput(audio_io_handle_t output,
88                                  audio_stream_type_t stream,
89                                  audio_session_t session);
90     virtual status_t stopOutput(audio_io_handle_t output,
91                                 audio_stream_type_t stream,
92                                 audio_session_t session);
93     virtual void releaseOutput(audio_io_handle_t output,
94                                audio_stream_type_t stream,
95                                audio_session_t session);
96     virtual status_t getInputForAttr(const audio_attributes_t *attr,
97                                      audio_io_handle_t *input,
98                                      audio_session_t session,
99                                      pid_t pid,
100                                      uid_t uid,
101                                      const audio_config_base_t *config,
102                                      audio_input_flags_t flags,
103                                      audio_port_handle_t *selectedDeviceId = NULL,
104                                      audio_port_handle_t *portId = NULL);
105     virtual status_t startInput(audio_io_handle_t input,
106                                 audio_session_t session);
107     virtual status_t stopInput(audio_io_handle_t input,
108                                audio_session_t session);
109     virtual void releaseInput(audio_io_handle_t input,
110                               audio_session_t session);
111     virtual status_t initStreamVolume(audio_stream_type_t stream,
112                                       int indexMin,
113                                       int indexMax);
114     virtual status_t setStreamVolumeIndex(audio_stream_type_t stream,
115                                           int index,
116                                           audio_devices_t device);
117     virtual status_t getStreamVolumeIndex(audio_stream_type_t stream,
118                                           int *index,
119                                           audio_devices_t device);
120 
121     virtual uint32_t getStrategyForStream(audio_stream_type_t stream);
122     virtual audio_devices_t getDevicesForStream(audio_stream_type_t stream);
123 
124     virtual audio_io_handle_t getOutputForEffect(const effect_descriptor_t *desc);
125     virtual status_t registerEffect(const effect_descriptor_t *desc,
126                                     audio_io_handle_t io,
127                                     uint32_t strategy,
128                                     audio_session_t session,
129                                     int id);
130     virtual status_t unregisterEffect(int id);
131     virtual status_t setEffectEnabled(int id, bool enabled);
132     virtual bool isStreamActive(audio_stream_type_t stream, uint32_t inPastMs = 0) const;
133     virtual bool isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs = 0) const;
134     virtual bool isSourceActive(audio_source_t source) const;
135 
136     virtual status_t queryDefaultPreProcessing(audio_session_t audioSession,
137                                               effect_descriptor_t *descriptors,
138                                               uint32_t *count);
139     virtual     status_t    onTransact(
140                                 uint32_t code,
141                                 const Parcel& data,
142                                 Parcel* reply,
143                                 uint32_t flags);
144 
145     // IBinder::DeathRecipient
146     virtual     void        binderDied(const wp<IBinder>& who);
147 
148     // RefBase
149     virtual     void        onFirstRef();
150 
151     //
152     // Helpers for the struct audio_policy_service_ops implementation.
153     // This is used by the audio policy manager for certain operations that
154     // are implemented by the policy service.
155     //
156     virtual void setParameters(audio_io_handle_t ioHandle,
157                                const char *keyValuePairs,
158                                int delayMs);
159 
160     virtual status_t setStreamVolume(audio_stream_type_t stream,
161                                      float volume,
162                                      audio_io_handle_t output,
163                                      int delayMs = 0);
164     virtual status_t startTone(audio_policy_tone_t tone, audio_stream_type_t stream);
165     virtual status_t stopTone();
166     virtual status_t setVoiceVolume(float volume, int delayMs = 0);
167     virtual bool isOffloadSupported(const audio_offload_info_t &config);
168 
169     virtual status_t listAudioPorts(audio_port_role_t role,
170                                     audio_port_type_t type,
171                                     unsigned int *num_ports,
172                                     struct audio_port *ports,
173                                     unsigned int *generation);
174     virtual status_t getAudioPort(struct audio_port *port);
175     virtual status_t createAudioPatch(const struct audio_patch *patch,
176                                        audio_patch_handle_t *handle);
177     virtual status_t releaseAudioPatch(audio_patch_handle_t handle);
178     virtual status_t listAudioPatches(unsigned int *num_patches,
179                                       struct audio_patch *patches,
180                                       unsigned int *generation);
181     virtual status_t setAudioPortConfig(const struct audio_port_config *config);
182 
183     virtual void registerClient(const sp<IAudioPolicyServiceClient>& client);
184 
185     virtual void setAudioPortCallbacksEnabled(bool enabled);
186 
187     virtual status_t acquireSoundTriggerSession(audio_session_t *session,
188                                            audio_io_handle_t *ioHandle,
189                                            audio_devices_t *device);
190 
191     virtual status_t releaseSoundTriggerSession(audio_session_t session);
192 
193     virtual audio_mode_t getPhoneState();
194 
195     virtual status_t registerPolicyMixes(const Vector<AudioMix>& mixes, bool registration);
196 
197     virtual status_t startAudioSource(const struct audio_port_config *source,
198                                       const audio_attributes_t *attributes,
199                                       audio_patch_handle_t *handle);
200     virtual status_t stopAudioSource(audio_patch_handle_t handle);
201 
202     virtual status_t setMasterMono(bool mono);
203     virtual status_t getMasterMono(bool *mono);
204 
205     virtual float    getStreamVolumeDB(
206                 audio_stream_type_t stream, int index, audio_devices_t device);
207 
208             status_t doStopOutput(audio_io_handle_t output,
209                                   audio_stream_type_t stream,
210                                   audio_session_t session);
211             void doReleaseOutput(audio_io_handle_t output,
212                                  audio_stream_type_t stream,
213                                  audio_session_t session);
214 
215             status_t clientCreateAudioPatch(const struct audio_patch *patch,
216                                       audio_patch_handle_t *handle,
217                                       int delayMs);
218             status_t clientReleaseAudioPatch(audio_patch_handle_t handle,
219                                              int delayMs);
220             virtual status_t clientSetAudioPortConfig(const struct audio_port_config *config,
221                                                       int delayMs);
222 
223             void removeNotificationClient(uid_t uid);
224             void onAudioPortListUpdate();
225             void doOnAudioPortListUpdate();
226             void onAudioPatchListUpdate();
227             void doOnAudioPatchListUpdate();
228 
229             void onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state);
230             void doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state);
231             void onRecordingConfigurationUpdate(int event, const record_client_info_t *clientInfo,
232                     const audio_config_base_t *clientConfig,
233                     const audio_config_base_t *deviceConfig, audio_patch_handle_t patchHandle);
234             void doOnRecordingConfigurationUpdate(int event, const record_client_info_t *clientInfo,
235                     const audio_config_base_t *clientConfig,
236                     const audio_config_base_t *deviceConfig, audio_patch_handle_t patchHandle);
237 
238 private:
239                         AudioPolicyService() ANDROID_API;
240     virtual             ~AudioPolicyService();
241 
242             status_t dumpInternals(int fd);
243 
244     // Thread used for tone playback and to send audio config commands to audio flinger
245     // For tone playback, using a separate thread is necessary to avoid deadlock with mLock because
246     // startTone() and stopTone() are normally called with mLock locked and requesting a tone start
247     // or stop will cause calls to AudioPolicyService and an attempt to lock mLock.
248     // For audio config commands, it is necessary because audio flinger requires that the calling
249     // process (user) has permission to modify audio settings.
250     class AudioCommandThread : public Thread {
251         class AudioCommand;
252     public:
253 
254         // commands for tone AudioCommand
255         enum {
256             START_TONE,
257             STOP_TONE,
258             SET_VOLUME,
259             SET_PARAMETERS,
260             SET_VOICE_VOLUME,
261             STOP_OUTPUT,
262             RELEASE_OUTPUT,
263             CREATE_AUDIO_PATCH,
264             RELEASE_AUDIO_PATCH,
265             UPDATE_AUDIOPORT_LIST,
266             UPDATE_AUDIOPATCH_LIST,
267             SET_AUDIOPORT_CONFIG,
268             DYN_POLICY_MIX_STATE_UPDATE,
269             RECORDING_CONFIGURATION_UPDATE
270         };
271 
272         AudioCommandThread (String8 name, const wp<AudioPolicyService>& service);
273         virtual             ~AudioCommandThread();
274 
275                     status_t    dump(int fd);
276 
277         // Thread virtuals
278         virtual     void        onFirstRef();
279         virtual     bool        threadLoop();
280 
281                     void        exit();
282                     void        startToneCommand(ToneGenerator::tone_type type,
283                                                  audio_stream_type_t stream);
284                     void        stopToneCommand();
285                     status_t    volumeCommand(audio_stream_type_t stream, float volume,
286                                             audio_io_handle_t output, int delayMs = 0);
287                     status_t    parametersCommand(audio_io_handle_t ioHandle,
288                                             const char *keyValuePairs, int delayMs = 0);
289                     status_t    voiceVolumeCommand(float volume, int delayMs = 0);
290                     void        stopOutputCommand(audio_io_handle_t output,
291                                                   audio_stream_type_t stream,
292                                                   audio_session_t session);
293                     void        releaseOutputCommand(audio_io_handle_t output,
294                                                      audio_stream_type_t stream,
295                                                      audio_session_t session);
296                     status_t    sendCommand(sp<AudioCommand>& command, int delayMs = 0);
297                     void        insertCommand_l(sp<AudioCommand>& command, int delayMs = 0);
298                     status_t    createAudioPatchCommand(const struct audio_patch *patch,
299                                                         audio_patch_handle_t *handle,
300                                                         int delayMs);
301                     status_t    releaseAudioPatchCommand(audio_patch_handle_t handle,
302                                                          int delayMs);
303                     void        updateAudioPortListCommand();
304                     void        updateAudioPatchListCommand();
305                     status_t    setAudioPortConfigCommand(const struct audio_port_config *config,
306                                                           int delayMs);
307                     void        dynamicPolicyMixStateUpdateCommand(const String8& regId, int32_t state);
308                     void        recordingConfigurationUpdateCommand(
309                                                         int event,
310                                                         const record_client_info_t *clientInfo,
311                                                         const audio_config_base_t *clientConfig,
312                                                         const audio_config_base_t *deviceConfig,
313                                                         audio_patch_handle_t patchHandle);
314                     void        insertCommand_l(AudioCommand *command, int delayMs = 0);
315 
316     private:
317         class AudioCommandData;
318 
319         // descriptor for requested tone playback event
320         class AudioCommand: public RefBase {
321 
322         public:
AudioCommand()323             AudioCommand()
324             : mCommand(-1), mStatus(NO_ERROR), mWaitStatus(false) {}
325 
326             void dump(char* buffer, size_t size);
327 
328             int mCommand;   // START_TONE, STOP_TONE ...
329             nsecs_t mTime;  // time stamp
330             Mutex mLock;    // mutex associated to mCond
331             Condition mCond; // condition for status return
332             status_t mStatus; // command status
333             bool mWaitStatus; // true if caller is waiting for status
334             sp<AudioCommandData> mParam;     // command specific parameter data
335         };
336 
337         class AudioCommandData: public RefBase {
338         public:
~AudioCommandData()339             virtual ~AudioCommandData() {}
340         protected:
AudioCommandData()341             AudioCommandData() {}
342         };
343 
344         class ToneData : public AudioCommandData {
345         public:
346             ToneGenerator::tone_type mType; // tone type (START_TONE only)
347             audio_stream_type_t mStream;    // stream type (START_TONE only)
348         };
349 
350         class VolumeData : public AudioCommandData {
351         public:
352             audio_stream_type_t mStream;
353             float mVolume;
354             audio_io_handle_t mIO;
355         };
356 
357         class ParametersData : public AudioCommandData {
358         public:
359             audio_io_handle_t mIO;
360             String8 mKeyValuePairs;
361         };
362 
363         class VoiceVolumeData : public AudioCommandData {
364         public:
365             float mVolume;
366         };
367 
368         class StopOutputData : public AudioCommandData {
369         public:
370             audio_io_handle_t mIO;
371             audio_stream_type_t mStream;
372             audio_session_t mSession;
373         };
374 
375         class ReleaseOutputData : public AudioCommandData {
376         public:
377             audio_io_handle_t mIO;
378             audio_stream_type_t mStream;
379             audio_session_t mSession;
380         };
381 
382         class CreateAudioPatchData : public AudioCommandData {
383         public:
384             struct audio_patch mPatch;
385             audio_patch_handle_t mHandle;
386         };
387 
388         class ReleaseAudioPatchData : public AudioCommandData {
389         public:
390             audio_patch_handle_t mHandle;
391         };
392 
393         class SetAudioPortConfigData : public AudioCommandData {
394         public:
395             struct audio_port_config mConfig;
396         };
397 
398         class DynPolicyMixStateUpdateData : public AudioCommandData {
399         public:
400             String8 mRegId;
401             int32_t mState;
402         };
403 
404         class RecordingConfigurationUpdateData : public AudioCommandData {
405         public:
406             int mEvent;
407             record_client_info_t mClientInfo;
408             struct audio_config_base mClientConfig;
409             struct audio_config_base mDeviceConfig;
410             audio_patch_handle_t mPatchHandle;
411         };
412 
413         Mutex   mLock;
414         Condition mWaitWorkCV;
415         Vector < sp<AudioCommand> > mAudioCommands; // list of pending commands
416         ToneGenerator *mpToneGenerator;     // the tone generator
417         sp<AudioCommand> mLastCommand;      // last processed command (used by dump)
418         String8 mName;                      // string used by wake lock fo delayed commands
419         wp<AudioPolicyService> mService;
420     };
421 
422     class AudioPolicyClient : public AudioPolicyClientInterface
423     {
424      public:
AudioPolicyClient(AudioPolicyService * service)425         explicit AudioPolicyClient(AudioPolicyService *service) : mAudioPolicyService(service) {}
~AudioPolicyClient()426         virtual ~AudioPolicyClient() {}
427 
428         //
429         // Audio HW module functions
430         //
431 
432         // loads a HW module.
433         virtual audio_module_handle_t loadHwModule(const char *name);
434 
435         //
436         // Audio output Control functions
437         //
438 
439         // opens an audio output with the requested parameters. The parameter values can indicate to use the default values
440         // in case the audio policy manager has no specific requirements for the output being opened.
441         // When the function returns, the parameter values reflect the actual values used by the audio hardware output stream.
442         // The audio policy manager can check if the proposed parameters are suitable or not and act accordingly.
443         virtual status_t openOutput(audio_module_handle_t module,
444                                     audio_io_handle_t *output,
445                                     audio_config_t *config,
446                                     audio_devices_t *devices,
447                                     const String8& address,
448                                     uint32_t *latencyMs,
449                                     audio_output_flags_t flags);
450         // creates a special output that is duplicated to the two outputs passed as arguments. The duplication is performed by
451         // a special mixer thread in the AudioFlinger.
452         virtual audio_io_handle_t openDuplicateOutput(audio_io_handle_t output1, audio_io_handle_t output2);
453         // closes the output stream
454         virtual status_t closeOutput(audio_io_handle_t output);
455         // suspends the output. When an output is suspended, the corresponding audio hardware output stream is placed in
456         // standby and the AudioTracks attached to the mixer thread are still processed but the output mix is discarded.
457         virtual status_t suspendOutput(audio_io_handle_t output);
458         // restores a suspended output.
459         virtual status_t restoreOutput(audio_io_handle_t output);
460 
461         //
462         // Audio input Control functions
463         //
464 
465         // opens an audio input
466         virtual audio_io_handle_t openInput(audio_module_handle_t module,
467                                             audio_io_handle_t *input,
468                                             audio_config_t *config,
469                                             audio_devices_t *devices,
470                                             const String8& address,
471                                             audio_source_t source,
472                                             audio_input_flags_t flags);
473         // closes an audio input
474         virtual status_t closeInput(audio_io_handle_t input);
475         //
476         // misc control functions
477         //
478 
479         // set a stream volume for a particular output. For the same user setting, a given stream type can have different volumes
480         // for each output (destination device) it is attached to.
481         virtual status_t setStreamVolume(audio_stream_type_t stream, float volume, audio_io_handle_t output, int delayMs = 0);
482 
483         // invalidate a stream type, causing a reroute to an unspecified new output
484         virtual status_t invalidateStream(audio_stream_type_t stream);
485 
486         // function enabling to send proprietary informations directly from audio policy manager to audio hardware interface.
487         virtual void setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs, int delayMs = 0);
488         // function enabling to receive proprietary informations directly from audio hardware interface to audio policy manager.
489         virtual String8 getParameters(audio_io_handle_t ioHandle, const String8& keys);
490 
491         // request the playback of a tone on the specified stream: used for instance to replace notification sounds when playing
492         // over a telephony device during a phone call.
493         virtual status_t startTone(audio_policy_tone_t tone, audio_stream_type_t stream);
494         virtual status_t stopTone();
495 
496         // set down link audio volume.
497         virtual status_t setVoiceVolume(float volume, int delayMs = 0);
498 
499         // move effect to the specified output
500         virtual status_t moveEffects(audio_session_t session,
501                                          audio_io_handle_t srcOutput,
502                                          audio_io_handle_t dstOutput);
503 
504         /* Create a patch between several source and sink ports */
505         virtual status_t createAudioPatch(const struct audio_patch *patch,
506                                            audio_patch_handle_t *handle,
507                                            int delayMs);
508 
509         /* Release a patch */
510         virtual status_t releaseAudioPatch(audio_patch_handle_t handle,
511                                            int delayMs);
512 
513         /* Set audio port configuration */
514         virtual status_t setAudioPortConfig(const struct audio_port_config *config, int delayMs);
515 
516         virtual void onAudioPortListUpdate();
517         virtual void onAudioPatchListUpdate();
518         virtual void onDynamicPolicyMixStateUpdate(String8 regId, int32_t state);
519         virtual void onRecordingConfigurationUpdate(int event,
520                         const record_client_info_t *clientInfo,
521                         const audio_config_base_t *clientConfig,
522                         const audio_config_base_t *deviceConfig, audio_patch_handle_t patchHandle);
523 
524         virtual audio_unique_id_t newAudioUniqueId(audio_unique_id_use_t use);
525 
526      private:
527         AudioPolicyService *mAudioPolicyService;
528     };
529 
530     // --- Notification Client ---
531     class NotificationClient : public IBinder::DeathRecipient {
532     public:
533                             NotificationClient(const sp<AudioPolicyService>& service,
534                                                 const sp<IAudioPolicyServiceClient>& client,
535                                                 uid_t uid);
536         virtual             ~NotificationClient();
537 
538                             void      onAudioPortListUpdate();
539                             void      onAudioPatchListUpdate();
540                             void      onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state);
541                             void      onRecordingConfigurationUpdate(
542                                         int event, const record_client_info_t *clientInfo,
543                                         const audio_config_base_t *clientConfig,
544                                         const audio_config_base_t *deviceConfig,
545                                         audio_patch_handle_t patchHandle);
546                             void      setAudioPortCallbacksEnabled(bool enabled);
547 
548                 // IBinder::DeathRecipient
549                 virtual     void        binderDied(const wp<IBinder>& who);
550 
551     private:
552                             NotificationClient(const NotificationClient&);
553                             NotificationClient& operator = (const NotificationClient&);
554 
555         const wp<AudioPolicyService>        mService;
556         const uid_t                         mUid;
557         const sp<IAudioPolicyServiceClient> mAudioPolicyServiceClient;
558               bool                          mAudioPortCallbacksEnabled;
559     };
560 
561     // Internal dump utilities.
562     status_t dumpPermissionDenial(int fd);
563 
564 
565     mutable Mutex mLock;    // prevents concurrent access to AudioPolicy manager functions changing
566                             // device connection state  or routing
567     mutable Mutex mEffectsLock; // serialize access to Effect state within APM.
568     // Note: lock acquisition order is always mLock > mEffectsLock:
569     // mLock protects AudioPolicyManager methods that can call into audio flinger
570     // and possibly back in to audio policy service and acquire mEffectsLock.
571     sp<AudioCommandThread> mAudioCommandThread;     // audio commands thread
572     sp<AudioCommandThread> mTonePlaybackThread;     // tone playback thread
573     sp<AudioCommandThread> mOutputCommandThread;    // process stop and release output
574     struct audio_policy_device *mpAudioPolicyDev;
575     struct audio_policy *mpAudioPolicy;
576     AudioPolicyInterface *mAudioPolicyManager;
577     AudioPolicyClient *mAudioPolicyClient;
578 
579     DefaultKeyedVector< uid_t, sp<NotificationClient> >    mNotificationClients;
580     Mutex mNotificationClientsLock;  // protects mNotificationClients
581     // Manage all effects configured in audio_effects.conf
582     sp<AudioPolicyEffects> mAudioPolicyEffects;
583     audio_mode_t mPhoneState;
584 };
585 
586 }; // namespace android
587 
588 #endif // ANDROID_AUDIOPOLICYSERVICE_H
589