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