Home | History | Annotate | Download | only in service
      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 <binder/IUidObserver.h>
     28 #include <system/audio.h>
     29 #include <system/audio_policy.h>
     30 #include <media/IAudioPolicyService.h>
     31 #include <media/ToneGenerator.h>
     32 #include <media/AudioEffect.h>
     33 #include <media/AudioPolicy.h>
     34 #include <mediautils/ServiceUtilities.h>
     35 #include "AudioPolicyEffects.h"
     36 #include <AudioPolicyInterface.h>
     37 #include <android/hardware/BnSensorPrivacyListener.h>
     38 
     39 #include <unordered_map>
     40 
     41 namespace android {
     42 
     43 // ----------------------------------------------------------------------------
     44 
     45 class AudioPolicyService :
     46     public BinderService<AudioPolicyService>,
     47     public BnAudioPolicyService,
     48     public IBinder::DeathRecipient
     49 {
     50     friend class BinderService<AudioPolicyService>;
     51 
     52 public:
     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                                               audio_format_t encodedFormat);
     67     virtual audio_policy_dev_state_t getDeviceConnectionState(
     68                                                                 audio_devices_t device,
     69                                                                 const char *device_address);
     70     virtual status_t handleDeviceConfigChange(audio_devices_t device,
     71                                               const char *device_address,
     72                                               const char *device_name,
     73                                               audio_format_t encodedFormat);
     74     virtual status_t setPhoneState(audio_mode_t state);
     75     virtual status_t setForceUse(audio_policy_force_use_t usage, audio_policy_forced_cfg_t config);
     76     virtual audio_policy_forced_cfg_t getForceUse(audio_policy_force_use_t usage);
     77     virtual audio_io_handle_t getOutput(audio_stream_type_t stream);
     78     status_t getOutputForAttr(audio_attributes_t *attr,
     79                               audio_io_handle_t *output,
     80                               audio_session_t session,
     81                               audio_stream_type_t *stream,
     82                               pid_t pid,
     83                               uid_t uid,
     84                               const audio_config_t *config,
     85                               audio_output_flags_t flags,
     86                               audio_port_handle_t *selectedDeviceId,
     87                               audio_port_handle_t *portId,
     88                               std::vector<audio_io_handle_t> *secondaryOutputs) override;
     89     virtual status_t startOutput(audio_port_handle_t portId);
     90     virtual status_t stopOutput(audio_port_handle_t portId);
     91     virtual void releaseOutput(audio_port_handle_t portId);
     92     virtual status_t getInputForAttr(const audio_attributes_t *attr,
     93                                      audio_io_handle_t *input,
     94                                      audio_unique_id_t riid,
     95                                      audio_session_t session,
     96                                      pid_t pid,
     97                                      uid_t uid,
     98                                      const String16& opPackageName,
     99                                      const audio_config_base_t *config,
    100                                      audio_input_flags_t flags,
    101                                      audio_port_handle_t *selectedDeviceId = NULL,
    102                                      audio_port_handle_t *portId = NULL);
    103     virtual status_t startInput(audio_port_handle_t portId);
    104     virtual status_t stopInput(audio_port_handle_t portId);
    105     virtual void releaseInput(audio_port_handle_t portId);
    106     virtual status_t initStreamVolume(audio_stream_type_t stream,
    107                                       int indexMin,
    108                                       int indexMax);
    109     virtual status_t setStreamVolumeIndex(audio_stream_type_t stream,
    110                                           int index,
    111                                           audio_devices_t device);
    112     virtual status_t getStreamVolumeIndex(audio_stream_type_t stream,
    113                                           int *index,
    114                                           audio_devices_t device);
    115 
    116     virtual status_t setVolumeIndexForAttributes(const audio_attributes_t &attr,
    117                                                  int index,
    118                                                  audio_devices_t device);
    119     virtual status_t getVolumeIndexForAttributes(const audio_attributes_t &attr,
    120                                                  int &index,
    121                                                  audio_devices_t device);
    122     virtual status_t getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
    123                                                     int &index);
    124     virtual status_t getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
    125                                                     int &index);
    126 
    127     virtual uint32_t getStrategyForStream(audio_stream_type_t stream);
    128     virtual audio_devices_t getDevicesForStream(audio_stream_type_t stream);
    129 
    130     virtual audio_io_handle_t getOutputForEffect(const effect_descriptor_t *desc);
    131     virtual status_t registerEffect(const effect_descriptor_t *desc,
    132                                     audio_io_handle_t io,
    133                                     uint32_t strategy,
    134                                     audio_session_t session,
    135                                     int id);
    136     virtual status_t unregisterEffect(int id);
    137     virtual status_t setEffectEnabled(int id, bool enabled);
    138     status_t moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io) override;
    139     virtual bool isStreamActive(audio_stream_type_t stream, uint32_t inPastMs = 0) const;
    140     virtual bool isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs = 0) const;
    141     virtual bool isSourceActive(audio_source_t source) const;
    142 
    143     virtual status_t queryDefaultPreProcessing(audio_session_t audioSession,
    144                                               effect_descriptor_t *descriptors,
    145                                               uint32_t *count);
    146     virtual status_t addSourceDefaultEffect(const effect_uuid_t *type,
    147                                             const String16& opPackageName,
    148                                             const effect_uuid_t *uuid,
    149                                             int32_t priority,
    150                                             audio_source_t source,
    151                                             audio_unique_id_t* id);
    152     virtual status_t addStreamDefaultEffect(const effect_uuid_t *type,
    153                                             const String16& opPackageName,
    154                                             const effect_uuid_t *uuid,
    155                                             int32_t priority,
    156                                             audio_usage_t usage,
    157                                             audio_unique_id_t* id);
    158     virtual status_t removeSourceDefaultEffect(audio_unique_id_t id);
    159     virtual status_t removeStreamDefaultEffect(audio_unique_id_t id);
    160 
    161     virtual     status_t    onTransact(
    162                                 uint32_t code,
    163                                 const Parcel& data,
    164                                 Parcel* reply,
    165                                 uint32_t flags);
    166 
    167     // IBinder::DeathRecipient
    168     virtual     void        binderDied(const wp<IBinder>& who);
    169 
    170     // RefBase
    171     virtual     void        onFirstRef();
    172 
    173     //
    174     // Helpers for the struct audio_policy_service_ops implementation.
    175     // This is used by the audio policy manager for certain operations that
    176     // are implemented by the policy service.
    177     //
    178     virtual void setParameters(audio_io_handle_t ioHandle,
    179                                const char *keyValuePairs,
    180                                int delayMs);
    181 
    182     virtual status_t setStreamVolume(audio_stream_type_t stream,
    183                                      float volume,
    184                                      audio_io_handle_t output,
    185                                      int delayMs = 0);
    186     virtual status_t setVoiceVolume(float volume, int delayMs = 0);
    187     status_t setAllowedCapturePolicy(uint_t uid, audio_flags_mask_t capturePolicy) override;
    188     virtual bool isOffloadSupported(const audio_offload_info_t &config);
    189     virtual bool isDirectOutputSupported(const audio_config_base_t& config,
    190                                          const audio_attributes_t& attributes);
    191 
    192     virtual status_t listAudioPorts(audio_port_role_t role,
    193                                     audio_port_type_t type,
    194                                     unsigned int *num_ports,
    195                                     struct audio_port *ports,
    196                                     unsigned int *generation);
    197     virtual status_t getAudioPort(struct audio_port *port);
    198     virtual status_t createAudioPatch(const struct audio_patch *patch,
    199                                        audio_patch_handle_t *handle);
    200     virtual status_t releaseAudioPatch(audio_patch_handle_t handle);
    201     virtual status_t listAudioPatches(unsigned int *num_patches,
    202                                       struct audio_patch *patches,
    203                                       unsigned int *generation);
    204     virtual status_t setAudioPortConfig(const struct audio_port_config *config);
    205 
    206     virtual void registerClient(const sp<IAudioPolicyServiceClient>& client);
    207 
    208     virtual void setAudioPortCallbacksEnabled(bool enabled);
    209 
    210     virtual void setAudioVolumeGroupCallbacksEnabled(bool enabled);
    211 
    212     virtual status_t acquireSoundTriggerSession(audio_session_t *session,
    213                                            audio_io_handle_t *ioHandle,
    214                                            audio_devices_t *device);
    215 
    216     virtual status_t releaseSoundTriggerSession(audio_session_t session);
    217 
    218     virtual audio_mode_t getPhoneState();
    219 
    220     virtual status_t registerPolicyMixes(const Vector<AudioMix>& mixes, bool registration);
    221 
    222     virtual status_t setUidDeviceAffinities(uid_t uid, const Vector<AudioDeviceTypeAddr>& devices);
    223 
    224     virtual status_t removeUidDeviceAffinities(uid_t uid);
    225 
    226     virtual status_t startAudioSource(const struct audio_port_config *source,
    227                                       const audio_attributes_t *attributes,
    228                                       audio_port_handle_t *portId);
    229     virtual status_t stopAudioSource(audio_port_handle_t portId);
    230 
    231     virtual status_t setMasterMono(bool mono);
    232     virtual status_t getMasterMono(bool *mono);
    233 
    234     virtual float    getStreamVolumeDB(
    235                 audio_stream_type_t stream, int index, audio_devices_t device);
    236 
    237     virtual status_t getSurroundFormats(unsigned int *numSurroundFormats,
    238                                         audio_format_t *surroundFormats,
    239                                         bool *surroundFormatsEnabled,
    240                                         bool reported);
    241     virtual status_t getHwOffloadEncodingFormatsSupportedForA2DP(
    242                                         std::vector<audio_format_t> *formats);
    243     virtual status_t setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled);
    244 
    245     virtual status_t setAssistantUid(uid_t uid);
    246     virtual status_t setA11yServicesUids(const std::vector<uid_t>& uids);
    247 
    248     virtual bool     isHapticPlaybackSupported();
    249 
    250     virtual status_t listAudioProductStrategies(AudioProductStrategyVector &strategies);
    251     virtual status_t getProductStrategyFromAudioAttributes(const AudioAttributes &aa,
    252                                                            product_strategy_t &productStrategy);
    253 
    254     virtual status_t listAudioVolumeGroups(AudioVolumeGroupVector &groups);
    255 
    256     virtual status_t getVolumeGroupFromAudioAttributes(const AudioAttributes &aa,
    257                                                        volume_group_t &volumeGroup);
    258 
    259     virtual status_t setRttEnabled(bool enabled);
    260 
    261             status_t doStopOutput(audio_port_handle_t portId);
    262             void doReleaseOutput(audio_port_handle_t portId);
    263 
    264             status_t clientCreateAudioPatch(const struct audio_patch *patch,
    265                                       audio_patch_handle_t *handle,
    266                                       int delayMs);
    267             status_t clientReleaseAudioPatch(audio_patch_handle_t handle,
    268                                              int delayMs);
    269             virtual status_t clientSetAudioPortConfig(const struct audio_port_config *config,
    270                                                       int delayMs);
    271 
    272             void removeNotificationClient(uid_t uid, pid_t pid);
    273             void onAudioPortListUpdate();
    274             void doOnAudioPortListUpdate();
    275             void onAudioPatchListUpdate();
    276             void doOnAudioPatchListUpdate();
    277 
    278             void onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state);
    279             void doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state);
    280             void onRecordingConfigurationUpdate(int event,
    281                                                 const record_client_info_t *clientInfo,
    282                                                 const audio_config_base_t *clientConfig,
    283                                                 std::vector<effect_descriptor_t> clientEffects,
    284                                                 const audio_config_base_t *deviceConfig,
    285                                                 std::vector<effect_descriptor_t> effects,
    286                                                 audio_patch_handle_t patchHandle,
    287                                                 audio_source_t source);
    288             void doOnRecordingConfigurationUpdate(int event,
    289                                                   const record_client_info_t *clientInfo,
    290                                                   const audio_config_base_t *clientConfig,
    291                                                   std::vector<effect_descriptor_t> clientEffects,
    292                                                   const audio_config_base_t *deviceConfig,
    293                                                   std::vector<effect_descriptor_t> effects,
    294                                                   audio_patch_handle_t patchHandle,
    295                                                   audio_source_t source);
    296 
    297             void onAudioVolumeGroupChanged(volume_group_t group, int flags);
    298             void doOnAudioVolumeGroupChanged(volume_group_t group, int flags);
    299             void setEffectSuspended(int effectId,
    300                                     audio_session_t sessionId,
    301                                     bool suspended);
    302 
    303 private:
    304                         AudioPolicyService() ANDROID_API;
    305     virtual             ~AudioPolicyService();
    306 
    307             status_t dumpInternals(int fd);
    308 
    309     // Handles binder shell commands
    310     virtual status_t shellCommand(int in, int out, int err, Vector<String16>& args);
    311 
    312     // Sets whether the given UID records only silence
    313     virtual void setAppState_l(uid_t uid, app_state_t state);
    314 
    315     // Overrides the UID state as if it is idle
    316     status_t handleSetUidState(Vector<String16>& args, int err);
    317 
    318     // Clears the override for the UID state
    319     status_t handleResetUidState(Vector<String16>& args, int err);
    320 
    321     // Gets the UID state
    322     status_t handleGetUidState(Vector<String16>& args, int out, int err);
    323 
    324     // Prints the shell command help
    325     status_t printHelp(int out);
    326 
    327     std::string getDeviceTypeStrForPortId(audio_port_handle_t portId);
    328 
    329     status_t getAudioPolicyEffects(sp<AudioPolicyEffects>& audioPolicyEffects);
    330 
    331     app_state_t apmStatFromAmState(int amState);
    332 
    333     void updateUidStates();
    334     void updateUidStates_l();
    335 
    336     void silenceAllRecordings_l();
    337 
    338     static bool isPrivacySensitiveSource(audio_source_t source);
    339     static bool isVirtualSource(audio_source_t source);
    340 
    341     // If recording we need to make sure the UID is allowed to do that. If the UID is idle
    342     // then it cannot record and gets buffers with zeros - silence. As soon as the UID
    343     // transitions to an active state we will start reporting buffers with data. This approach
    344     // transparently handles recording while the UID transitions between idle/active state
    345     // avoiding to get stuck in a state receiving non-empty buffers while idle or in a state
    346     // receiving empty buffers while active.
    347     class UidPolicy : public BnUidObserver, public virtual IBinder::DeathRecipient {
    348     public:
    349         explicit UidPolicy(wp<AudioPolicyService> service)
    350                 : mService(service), mObserverRegistered(false),
    351                   mAssistantUid(0), mRttEnabled(false) {}
    352 
    353         void registerSelf();
    354         void unregisterSelf();
    355 
    356         // IBinder::DeathRecipient implementation
    357         void binderDied(const wp<IBinder> &who) override;
    358 
    359         bool isUidActive(uid_t uid);
    360         int getUidState(uid_t uid);
    361         void setAssistantUid(uid_t uid) { mAssistantUid = uid; }
    362         bool isAssistantUid(uid_t uid) { return uid == mAssistantUid; }
    363         void setA11yUids(const std::vector<uid_t>& uids) { mA11yUids.clear(); mA11yUids = uids; }
    364         bool isA11yUid(uid_t uid);
    365         bool isA11yOnTop();
    366         void setRttEnabled(bool enabled) { mRttEnabled = enabled; }
    367         bool isRttEnabled() { return mRttEnabled; }
    368 
    369         // BnUidObserver implementation
    370         void onUidActive(uid_t uid) override;
    371         void onUidGone(uid_t uid, bool disabled) override;
    372         void onUidIdle(uid_t uid, bool disabled) override;
    373         void onUidStateChanged(uid_t uid, int32_t procState, int64_t procStateSeq);
    374 
    375         void addOverrideUid(uid_t uid, bool active) { updateOverrideUid(uid, active, true); }
    376         void removeOverrideUid(uid_t uid) { updateOverrideUid(uid, false, false); }
    377 
    378         void updateUid(std::unordered_map<uid_t, std::pair<bool, int>> *uids,
    379                        uid_t uid, bool active, int state, bool insert);
    380 
    381      private:
    382         void notifyService();
    383         void updateOverrideUid(uid_t uid, bool active, bool insert);
    384         void updateUidLocked(std::unordered_map<uid_t, std::pair<bool, int>> *uids,
    385                              uid_t uid, bool active, int state, bool insert);
    386         void checkRegistered();
    387 
    388         wp<AudioPolicyService> mService;
    389         Mutex mLock;
    390         bool mObserverRegistered;
    391         std::unordered_map<uid_t, std::pair<bool, int>> mOverrideUids;
    392         std::unordered_map<uid_t, std::pair<bool, int>> mCachedUids;
    393         uid_t mAssistantUid;
    394         std::vector<uid_t> mA11yUids;
    395         bool mRttEnabled;
    396     };
    397 
    398     // If sensor privacy is enabled then all apps, including those that are active, should be
    399     // prevented from recording. This is handled similar to idle UIDs, any app that attempts
    400     // to record while sensor privacy is enabled will receive buffers with zeros. As soon as
    401     // sensor privacy is disabled active apps will receive the expected data when recording.
    402     class SensorPrivacyPolicy : public hardware::BnSensorPrivacyListener {
    403         public:
    404             explicit SensorPrivacyPolicy(wp<AudioPolicyService> service)
    405                     : mService(service) {}
    406 
    407             void registerSelf();
    408             void unregisterSelf();
    409 
    410             bool isSensorPrivacyEnabled();
    411 
    412             binder::Status onSensorPrivacyChanged(bool enabled);
    413 
    414         private:
    415             wp<AudioPolicyService> mService;
    416             std::atomic_bool mSensorPrivacyEnabled;
    417     };
    418 
    419     // Thread used to send audio config commands to audio flinger
    420     // For audio config commands, it is necessary because audio flinger requires that the calling
    421     // process (user) has permission to modify audio settings.
    422     class AudioCommandThread : public Thread {
    423         class AudioCommand;
    424     public:
    425 
    426         // commands for tone AudioCommand
    427         enum {
    428             SET_VOLUME,
    429             SET_PARAMETERS,
    430             SET_VOICE_VOLUME,
    431             STOP_OUTPUT,
    432             RELEASE_OUTPUT,
    433             CREATE_AUDIO_PATCH,
    434             RELEASE_AUDIO_PATCH,
    435             UPDATE_AUDIOPORT_LIST,
    436             UPDATE_AUDIOPATCH_LIST,
    437             CHANGED_AUDIOVOLUMEGROUP,
    438             SET_AUDIOPORT_CONFIG,
    439             DYN_POLICY_MIX_STATE_UPDATE,
    440             RECORDING_CONFIGURATION_UPDATE,
    441             SET_EFFECT_SUSPENDED,
    442         };
    443 
    444         AudioCommandThread (String8 name, const wp<AudioPolicyService>& service);
    445         virtual             ~AudioCommandThread();
    446 
    447                     status_t    dump(int fd);
    448 
    449         // Thread virtuals
    450         virtual     void        onFirstRef();
    451         virtual     bool        threadLoop();
    452 
    453                     void        exit();
    454                     status_t    volumeCommand(audio_stream_type_t stream, float volume,
    455                                             audio_io_handle_t output, int delayMs = 0);
    456                     status_t    parametersCommand(audio_io_handle_t ioHandle,
    457                                             const char *keyValuePairs, int delayMs = 0);
    458                     status_t    voiceVolumeCommand(float volume, int delayMs = 0);
    459                     void        stopOutputCommand(audio_port_handle_t portId);
    460                     void        releaseOutputCommand(audio_port_handle_t portId);
    461                     status_t    sendCommand(sp<AudioCommand>& command, int delayMs = 0);
    462                     void        insertCommand_l(sp<AudioCommand>& command, int delayMs = 0);
    463                     status_t    createAudioPatchCommand(const struct audio_patch *patch,
    464                                                         audio_patch_handle_t *handle,
    465                                                         int delayMs);
    466                     status_t    releaseAudioPatchCommand(audio_patch_handle_t handle,
    467                                                          int delayMs);
    468                     void        updateAudioPortListCommand();
    469                     void        updateAudioPatchListCommand();
    470                     void        changeAudioVolumeGroupCommand(volume_group_t group, int flags);
    471                     status_t    setAudioPortConfigCommand(const struct audio_port_config *config,
    472                                                           int delayMs);
    473                     void        dynamicPolicyMixStateUpdateCommand(const String8& regId,
    474                                                                    int32_t state);
    475                     void        recordingConfigurationUpdateCommand(
    476                                                     int event,
    477                                                     const record_client_info_t *clientInfo,
    478                                                     const audio_config_base_t *clientConfig,
    479                                                     std::vector<effect_descriptor_t> clientEffects,
    480                                                     const audio_config_base_t *deviceConfig,
    481                                                     std::vector<effect_descriptor_t> effects,
    482                                                     audio_patch_handle_t patchHandle,
    483                                                     audio_source_t source);
    484                     void        setEffectSuspendedCommand(int effectId,
    485                                                           audio_session_t sessionId,
    486                                                           bool suspended);
    487                     void        insertCommand_l(AudioCommand *command, int delayMs = 0);
    488     private:
    489         class AudioCommandData;
    490 
    491         // descriptor for requested tone playback event
    492         class AudioCommand: public RefBase {
    493 
    494         public:
    495             AudioCommand()
    496             : mCommand(-1), mStatus(NO_ERROR), mWaitStatus(false) {}
    497 
    498             void dump(char* buffer, size_t size);
    499 
    500             int mCommand;   // SET_VOLUME, SET_PARAMETERS...
    501             nsecs_t mTime;  // time stamp
    502             Mutex mLock;    // mutex associated to mCond
    503             Condition mCond; // condition for status return
    504             status_t mStatus; // command status
    505             bool mWaitStatus; // true if caller is waiting for status
    506             sp<AudioCommandData> mParam;     // command specific parameter data
    507         };
    508 
    509         class AudioCommandData: public RefBase {
    510         public:
    511             virtual ~AudioCommandData() {}
    512         protected:
    513             AudioCommandData() {}
    514         };
    515 
    516         class VolumeData : public AudioCommandData {
    517         public:
    518             audio_stream_type_t mStream;
    519             float mVolume;
    520             audio_io_handle_t mIO;
    521         };
    522 
    523         class ParametersData : public AudioCommandData {
    524         public:
    525             audio_io_handle_t mIO;
    526             String8 mKeyValuePairs;
    527         };
    528 
    529         class VoiceVolumeData : public AudioCommandData {
    530         public:
    531             float mVolume;
    532         };
    533 
    534         class StopOutputData : public AudioCommandData {
    535         public:
    536             audio_port_handle_t mPortId;
    537         };
    538 
    539         class ReleaseOutputData : public AudioCommandData {
    540         public:
    541             audio_port_handle_t mPortId;
    542         };
    543 
    544         class CreateAudioPatchData : public AudioCommandData {
    545         public:
    546             struct audio_patch mPatch;
    547             audio_patch_handle_t mHandle;
    548         };
    549 
    550         class ReleaseAudioPatchData : public AudioCommandData {
    551         public:
    552             audio_patch_handle_t mHandle;
    553         };
    554 
    555         class AudioVolumeGroupData : public AudioCommandData {
    556         public:
    557             volume_group_t mGroup;
    558             int mFlags;
    559         };
    560 
    561         class SetAudioPortConfigData : public AudioCommandData {
    562         public:
    563             struct audio_port_config mConfig;
    564         };
    565 
    566         class DynPolicyMixStateUpdateData : public AudioCommandData {
    567         public:
    568             String8 mRegId;
    569             int32_t mState;
    570         };
    571 
    572         class RecordingConfigurationUpdateData : public AudioCommandData {
    573         public:
    574             int mEvent;
    575             record_client_info_t mClientInfo;
    576             struct audio_config_base mClientConfig;
    577             std::vector<effect_descriptor_t> mClientEffects;
    578             struct audio_config_base mDeviceConfig;
    579             std::vector<effect_descriptor_t> mEffects;
    580             audio_patch_handle_t mPatchHandle;
    581             audio_source_t mSource;
    582         };
    583 
    584         class SetEffectSuspendedData : public AudioCommandData {
    585         public:
    586             int mEffectId;
    587             audio_session_t mSessionId;
    588             bool mSuspended;
    589         };
    590 
    591         Mutex   mLock;
    592         Condition mWaitWorkCV;
    593         Vector < sp<AudioCommand> > mAudioCommands; // list of pending commands
    594         sp<AudioCommand> mLastCommand;      // last processed command (used by dump)
    595         String8 mName;                      // string used by wake lock fo delayed commands
    596         wp<AudioPolicyService> mService;
    597     };
    598 
    599     class AudioPolicyClient : public AudioPolicyClientInterface
    600     {
    601      public:
    602         explicit AudioPolicyClient(AudioPolicyService *service) : mAudioPolicyService(service) {}
    603         virtual ~AudioPolicyClient() {}
    604 
    605         //
    606         // Audio HW module functions
    607         //
    608 
    609         // loads a HW module.
    610         virtual audio_module_handle_t loadHwModule(const char *name);
    611 
    612         //
    613         // Audio output Control functions
    614         //
    615 
    616         // opens an audio output with the requested parameters. The parameter values can indicate to use the default values
    617         // in case the audio policy manager has no specific requirements for the output being opened.
    618         // When the function returns, the parameter values reflect the actual values used by the audio hardware output stream.
    619         // The audio policy manager can check if the proposed parameters are suitable or not and act accordingly.
    620         virtual status_t openOutput(audio_module_handle_t module,
    621                                     audio_io_handle_t *output,
    622                                     audio_config_t *config,
    623                                     audio_devices_t *devices,
    624                                     const String8& address,
    625                                     uint32_t *latencyMs,
    626                                     audio_output_flags_t flags);
    627         // creates a special output that is duplicated to the two outputs passed as arguments. The duplication is performed by
    628         // a special mixer thread in the AudioFlinger.
    629         virtual audio_io_handle_t openDuplicateOutput(audio_io_handle_t output1, audio_io_handle_t output2);
    630         // closes the output stream
    631         virtual status_t closeOutput(audio_io_handle_t output);
    632         // suspends the output. When an output is suspended, the corresponding audio hardware output stream is placed in
    633         // standby and the AudioTracks attached to the mixer thread are still processed but the output mix is discarded.
    634         virtual status_t suspendOutput(audio_io_handle_t output);
    635         // restores a suspended output.
    636         virtual status_t restoreOutput(audio_io_handle_t output);
    637 
    638         //
    639         // Audio input Control functions
    640         //
    641 
    642         // opens an audio input
    643         virtual audio_io_handle_t openInput(audio_module_handle_t module,
    644                                             audio_io_handle_t *input,
    645                                             audio_config_t *config,
    646                                             audio_devices_t *devices,
    647                                             const String8& address,
    648                                             audio_source_t source,
    649                                             audio_input_flags_t flags);
    650         // closes an audio input
    651         virtual status_t closeInput(audio_io_handle_t input);
    652         //
    653         // misc control functions
    654         //
    655 
    656         // set a stream volume for a particular output. For the same user setting, a given stream type can have different volumes
    657         // for each output (destination device) it is attached to.
    658         virtual status_t setStreamVolume(audio_stream_type_t stream, float volume, audio_io_handle_t output, int delayMs = 0);
    659 
    660         // invalidate a stream type, causing a reroute to an unspecified new output
    661         virtual status_t invalidateStream(audio_stream_type_t stream);
    662 
    663         // function enabling to send proprietary informations directly from audio policy manager to audio hardware interface.
    664         virtual void setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs, int delayMs = 0);
    665         // function enabling to receive proprietary informations directly from audio hardware interface to audio policy manager.
    666         virtual String8 getParameters(audio_io_handle_t ioHandle, const String8& keys);
    667 
    668         // set down link audio volume.
    669         virtual status_t setVoiceVolume(float volume, int delayMs = 0);
    670 
    671         // move effect to the specified output
    672         virtual status_t moveEffects(audio_session_t session,
    673                                          audio_io_handle_t srcOutput,
    674                                          audio_io_handle_t dstOutput);
    675 
    676                 void setEffectSuspended(int effectId,
    677                                         audio_session_t sessionId,
    678                                         bool suspended) override;
    679 
    680         /* Create a patch between several source and sink ports */
    681         virtual status_t createAudioPatch(const struct audio_patch *patch,
    682                                            audio_patch_handle_t *handle,
    683                                            int delayMs);
    684 
    685         /* Release a patch */
    686         virtual status_t releaseAudioPatch(audio_patch_handle_t handle,
    687                                            int delayMs);
    688 
    689         /* Set audio port configuration */
    690         virtual status_t setAudioPortConfig(const struct audio_port_config *config, int delayMs);
    691 
    692         virtual void onAudioPortListUpdate();
    693         virtual void onAudioPatchListUpdate();
    694         virtual void onDynamicPolicyMixStateUpdate(String8 regId, int32_t state);
    695         virtual void onRecordingConfigurationUpdate(int event,
    696                                                     const record_client_info_t *clientInfo,
    697                                                     const audio_config_base_t *clientConfig,
    698                                                     std::vector<effect_descriptor_t> clientEffects,
    699                                                     const audio_config_base_t *deviceConfig,
    700                                                     std::vector<effect_descriptor_t> effects,
    701                                                     audio_patch_handle_t patchHandle,
    702                                                     audio_source_t source);
    703 
    704         virtual void onAudioVolumeGroupChanged(volume_group_t group, int flags);
    705 
    706         virtual audio_unique_id_t newAudioUniqueId(audio_unique_id_use_t use);
    707 
    708      private:
    709         AudioPolicyService *mAudioPolicyService;
    710     };
    711 
    712     // --- Notification Client ---
    713     class NotificationClient : public IBinder::DeathRecipient {
    714     public:
    715                             NotificationClient(const sp<AudioPolicyService>& service,
    716                                                 const sp<IAudioPolicyServiceClient>& client,
    717                                                 uid_t uid, pid_t pid);
    718         virtual             ~NotificationClient();
    719 
    720                             void      onAudioPortListUpdate();
    721                             void      onAudioPatchListUpdate();
    722                             void      onDynamicPolicyMixStateUpdate(const String8& regId,
    723                                                                     int32_t state);
    724                             void      onAudioVolumeGroupChanged(volume_group_t group, int flags);
    725                             void      onRecordingConfigurationUpdate(
    726                                                     int event,
    727                                                     const record_client_info_t *clientInfo,
    728                                                     const audio_config_base_t *clientConfig,
    729                                                     std::vector<effect_descriptor_t> clientEffects,
    730                                                     const audio_config_base_t *deviceConfig,
    731                                                     std::vector<effect_descriptor_t> effects,
    732                                                     audio_patch_handle_t patchHandle,
    733                                                     audio_source_t source);
    734                             void      setAudioPortCallbacksEnabled(bool enabled);
    735                             void setAudioVolumeGroupCallbacksEnabled(bool enabled);
    736 
    737                             uid_t uid() {
    738                                 return mUid;
    739                             }
    740 
    741                 // IBinder::DeathRecipient
    742                 virtual     void        binderDied(const wp<IBinder>& who);
    743 
    744     private:
    745                             NotificationClient(const NotificationClient&);
    746                             NotificationClient& operator = (const NotificationClient&);
    747 
    748         const wp<AudioPolicyService>        mService;
    749         const uid_t                         mUid;
    750         const pid_t                         mPid;
    751         const sp<IAudioPolicyServiceClient> mAudioPolicyServiceClient;
    752               bool                          mAudioPortCallbacksEnabled;
    753               bool                          mAudioVolumeGroupCallbacksEnabled;
    754     };
    755 
    756     class AudioClient : public virtual RefBase {
    757     public:
    758                 AudioClient(const audio_attributes_t attributes,
    759                             const audio_io_handle_t io, uid_t uid, pid_t pid,
    760                             const audio_session_t session, const audio_port_handle_t deviceId) :
    761                                 attributes(attributes), io(io), uid(uid), pid(pid),
    762                                 session(session), deviceId(deviceId), active(false) {}
    763                 ~AudioClient() override = default;
    764 
    765 
    766         const audio_attributes_t attributes; // source, flags ...
    767         const audio_io_handle_t io;          // audio HAL stream IO handle
    768         const uid_t uid;                     // client UID
    769         const pid_t pid;                     // client PID
    770         const audio_session_t session;       // audio session ID
    771         const audio_port_handle_t deviceId;  // selected input device port ID
    772               bool active;                   // Playback/Capture is active or inactive
    773     };
    774 
    775     // --- AudioRecordClient ---
    776     // Information about each registered AudioRecord client
    777     // (between calls to getInputForAttr() and releaseInput())
    778     class AudioRecordClient : public AudioClient {
    779     public:
    780                 AudioRecordClient(const audio_attributes_t attributes,
    781                           const audio_io_handle_t io, uid_t uid, pid_t pid,
    782                           const audio_session_t session, const audio_port_handle_t deviceId,
    783                           const String16& opPackageName,
    784                           bool canCaptureOutput, bool canCaptureHotword) :
    785                     AudioClient(attributes, io, uid, pid, session, deviceId),
    786                     opPackageName(opPackageName), startTimeNs(0),
    787                     canCaptureOutput(canCaptureOutput), canCaptureHotword(canCaptureHotword) {}
    788                 ~AudioRecordClient() override = default;
    789 
    790         const String16 opPackageName;        // client package name
    791         nsecs_t startTimeNs;
    792         const bool canCaptureOutput;
    793         const bool canCaptureHotword;
    794     };
    795 
    796     // --- AudioPlaybackClient ---
    797     // Information about each registered AudioTrack client
    798     // (between calls to getOutputForAttr() and releaseOutput())
    799     class AudioPlaybackClient : public AudioClient {
    800     public:
    801                 AudioPlaybackClient(const audio_attributes_t attributes,
    802                       const audio_io_handle_t io, uid_t uid, pid_t pid,
    803                             const audio_session_t session, audio_port_handle_t deviceId,
    804                             audio_stream_type_t stream) :
    805                     AudioClient(attributes, io, uid, pid, session, deviceId), stream(stream) {}
    806                 ~AudioPlaybackClient() override = default;
    807 
    808         const audio_stream_type_t stream;
    809     };
    810 
    811     void getPlaybackClientAndEffects(audio_port_handle_t portId,
    812                                      sp<AudioPlaybackClient>& client,
    813                                      sp<AudioPolicyEffects>& effects,
    814                                      const char *context);
    815 
    816 
    817     // A class automatically clearing and restoring binder caller identity inside
    818     // a code block (scoped variable)
    819     // Declare one systematically before calling AudioPolicyManager methods so that they are
    820     // executed with the same level of privilege as audioserver process.
    821     class AutoCallerClear {
    822     public:
    823             AutoCallerClear() :
    824                 mToken(IPCThreadState::self()->clearCallingIdentity()) {}
    825             ~AutoCallerClear() {
    826                 IPCThreadState::self()->restoreCallingIdentity(mToken);
    827             }
    828 
    829     private:
    830         const   int64_t mToken;
    831     };
    832 
    833     // Internal dump utilities.
    834     status_t dumpPermissionDenial(int fd);
    835 
    836 
    837     mutable Mutex mLock;    // prevents concurrent access to AudioPolicy manager functions changing
    838                             // device connection state  or routing
    839     // Note: lock acquisition order is always mLock > mEffectsLock:
    840     // mLock protects AudioPolicyManager methods that can call into audio flinger
    841     // and possibly back in to audio policy service and acquire mEffectsLock.
    842     sp<AudioCommandThread> mAudioCommandThread;     // audio commands thread
    843     sp<AudioCommandThread> mOutputCommandThread;    // process stop and release output
    844     struct audio_policy_device *mpAudioPolicyDev;
    845     struct audio_policy *mpAudioPolicy;
    846     AudioPolicyInterface *mAudioPolicyManager;
    847     AudioPolicyClient *mAudioPolicyClient;
    848 
    849     DefaultKeyedVector< int64_t, sp<NotificationClient> >    mNotificationClients;
    850     Mutex mNotificationClientsLock;  // protects mNotificationClients
    851     // Manage all effects configured in audio_effects.conf
    852     // never hold AudioPolicyService::mLock when calling AudioPolicyEffects methods as
    853     // those can call back into AudioPolicyService methods and try to acquire the mutex
    854     sp<AudioPolicyEffects> mAudioPolicyEffects;
    855     audio_mode_t mPhoneState;
    856 
    857     sp<UidPolicy> mUidPolicy;
    858     sp<SensorPrivacyPolicy> mSensorPrivacyPolicy;
    859 
    860     DefaultKeyedVector< audio_port_handle_t, sp<AudioRecordClient> >   mAudioRecordClients;
    861     DefaultKeyedVector< audio_port_handle_t, sp<AudioPlaybackClient> >   mAudioPlaybackClients;
    862 
    863     MediaPackageManager mPackageManager; // To check allowPlaybackCapture
    864 };
    865 
    866 } // namespace android
    867 
    868 #endif // ANDROID_AUDIOPOLICYSERVICE_H
    869