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