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/media/BnAudioPolicyService.h> 21 #include <android/media/GetSpatializerResponse.h> 22 #include <android-base/thread_annotations.h> 23 #include <audio_utils/mutex.h> 24 #include <com/android/media/permission/INativePermissionController.h> 25 #include <cutils/misc.h> 26 #include <cutils/config_utils.h> 27 #include <cutils/compiler.h> 28 #include <utils/String8.h> 29 #include <utils/Vector.h> 30 #include <utils/SortedVector.h> 31 #include <binder/ActivityManager.h> 32 #include <binder/BinderService.h> 33 #include <binder/IUidObserver.h> 34 #include <system/audio.h> 35 #include <system/audio_policy.h> 36 #include <media/ToneGenerator.h> 37 #include <media/AudioEffect.h> 38 #include <media/AudioPolicy.h> 39 #include <media/IAudioPolicyServiceLocal.h> 40 #include <media/NativePermissionController.h> 41 #include <media/UsecaseValidator.h> 42 #include <mediautils/ServiceUtilities.h> 43 #include "AudioPolicyEffects.h" 44 #include "CaptureStateNotifier.h" 45 #include "Spatializer.h" 46 #include <AudioPolicyInterface.h> 47 #include <android/hardware/BnSensorPrivacyListener.h> 48 #include <android/content/AttributionSourceState.h> 49 50 #include <unordered_map> 51 52 namespace android { 53 54 using content::AttributionSourceState; 55 using media::audio::common::AudioConfig; 56 using media::audio::common::AudioConfigBase; 57 using media::audio::common::AudioDevice; 58 using media::audio::common::AudioDeviceDescription; 59 using media::audio::common::AudioFormatDescription; 60 using media::audio::common::AudioMode; 61 using media::audio::common::AudioSource; 62 using media::audio::common::AudioStreamType; 63 using media::audio::common::AudioUsage; 64 using media::audio::common::AudioUuid; 65 using media::audio::common::Int; 66 67 // ---------------------------------------------------------------------------- 68 69 namespace media::audiopolicy { 70 class AudioRecordClient; 71 } 72 73 using ::android::media::audiopolicy::AudioRecordClient; 74 using ::com::android::media::permission::INativePermissionController; 75 using ::com::android::media::permission::NativePermissionController; 76 using ::com::android::media::permission::IPermissionProvider; 77 78 class AudioPolicyService : 79 public BinderService<AudioPolicyService>, 80 public media::BnAudioPolicyService, 81 public IBinder::DeathRecipient, 82 public SpatializerPolicyCallback, 83 public media::IAudioPolicyServiceLocal 84 { 85 friend class sp<AudioPolicyService>; 86 87 public: 88 // for BinderService getServiceName()89 static const char *getServiceName() ANDROID_API { return "media.audio_policy"; } 90 91 virtual status_t dump(int fd, const Vector<String16>& args); 92 93 // 94 // BnAudioPolicyService (see AudioPolicyInterface for method descriptions) 95 // 96 binder::Status onNewAudioModulesAvailable() override; 97 binder::Status setDeviceConnectionState( 98 media::AudioPolicyDeviceState state, 99 const android::media::audio::common::AudioPort& port, 100 const AudioFormatDescription& encodedFormat) override; 101 binder::Status getDeviceConnectionState(const AudioDevice& device, 102 media::AudioPolicyDeviceState* _aidl_return) override; 103 binder::Status handleDeviceConfigChange( 104 const AudioDevice& device, 105 const std::string& deviceName, 106 const AudioFormatDescription& encodedFormat) override; 107 binder::Status setPhoneState(AudioMode state, int32_t uid) override; 108 binder::Status setForceUse(media::AudioPolicyForceUse usage, 109 media::AudioPolicyForcedConfig config) override; 110 binder::Status getForceUse(media::AudioPolicyForceUse usage, 111 media::AudioPolicyForcedConfig* _aidl_return) override; 112 binder::Status getOutput(AudioStreamType stream, int32_t* _aidl_return) override; 113 binder::Status getOutputForAttr(const media::audio::common::AudioAttributes& attr, 114 int32_t session, 115 const AttributionSourceState &attributionSource, 116 const AudioConfig& config, 117 int32_t flags, int32_t selectedDeviceId, 118 media::GetOutputForAttrResponse* _aidl_return) override; 119 binder::Status startOutput(int32_t portId) override; 120 binder::Status stopOutput(int32_t portId) override; 121 binder::Status releaseOutput(int32_t portId) override; 122 binder::Status getInputForAttr(const media::audio::common::AudioAttributes& attr, int32_t input, 123 int32_t riid, int32_t session, 124 const AttributionSourceState &attributionSource, 125 const AudioConfigBase& config, int32_t flags, 126 int32_t selectedDeviceId, 127 media::GetInputForAttrResponse* _aidl_return) override; 128 binder::Status startInput(int32_t portId) override; 129 binder::Status stopInput(int32_t portId) override; 130 binder::Status releaseInput(int32_t portId) override; 131 binder::Status setDeviceAbsoluteVolumeEnabled(const AudioDevice& device, 132 bool enabled, 133 AudioStreamType streamToDriveAbs) override; 134 binder::Status initStreamVolume(AudioStreamType stream, int32_t indexMin, 135 int32_t indexMax) override; 136 binder::Status setStreamVolumeIndex(AudioStreamType stream, 137 const AudioDeviceDescription& device, 138 int32_t index) override; 139 binder::Status getStreamVolumeIndex(AudioStreamType stream, 140 const AudioDeviceDescription& device, 141 int32_t* _aidl_return) override; 142 binder::Status setVolumeIndexForAttributes(const media::audio::common::AudioAttributes& attr, 143 const AudioDeviceDescription& device, 144 int32_t index) override; 145 binder::Status getVolumeIndexForAttributes(const media::audio::common::AudioAttributes& attr, 146 const AudioDeviceDescription& device, 147 int32_t* _aidl_return) override; 148 binder::Status getMaxVolumeIndexForAttributes(const media::audio::common::AudioAttributes& attr, 149 int32_t* _aidl_return) override; 150 binder::Status getMinVolumeIndexForAttributes(const media::audio::common::AudioAttributes& attr, 151 int32_t* _aidl_return) override; 152 binder::Status getStrategyForStream(AudioStreamType stream, 153 int32_t* _aidl_return) override; 154 binder::Status getDevicesForAttributes(const media::audio::common::AudioAttributes& attr, 155 bool forVolume, 156 std::vector<AudioDevice>* _aidl_return) override; 157 binder::Status getOutputForEffect(const media::EffectDescriptor& desc, 158 int32_t* _aidl_return) override; 159 binder::Status registerEffect(const media::EffectDescriptor& desc, int32_t io, int32_t strategy, 160 int32_t session, int32_t id) override; 161 binder::Status unregisterEffect(int32_t id) override; 162 binder::Status setEffectEnabled(int32_t id, bool enabled) override; 163 binder::Status moveEffectsToIo(const std::vector<int32_t>& ids, int32_t io) override; 164 binder::Status isStreamActive(AudioStreamType stream, int32_t inPastMs, 165 bool* _aidl_return) override; 166 binder::Status isStreamActiveRemotely(AudioStreamType stream, int32_t inPastMs, 167 bool* _aidl_return) override; 168 binder::Status isSourceActive(AudioSource source, bool* _aidl_return) override; 169 binder::Status queryDefaultPreProcessing( 170 int32_t audioSession, Int* count, 171 std::vector<media::EffectDescriptor>* _aidl_return) override; 172 binder::Status addSourceDefaultEffect(const AudioUuid& type, 173 const std::string& opPackageName, 174 const AudioUuid& uuid, int32_t priority, 175 AudioSource source, 176 int32_t* _aidl_return) override; 177 binder::Status addStreamDefaultEffect(const AudioUuid& type, 178 const std::string& opPackageName, 179 const AudioUuid& uuid, int32_t priority, 180 AudioUsage usage, int32_t* _aidl_return) override; 181 binder::Status removeSourceDefaultEffect(int32_t id) override; 182 binder::Status removeStreamDefaultEffect(int32_t id) override; 183 binder::Status setSupportedSystemUsages( 184 const std::vector<AudioUsage>& systemUsages) override; 185 binder::Status setAllowedCapturePolicy(int32_t uid, int32_t capturePolicy) override; 186 binder::Status getOffloadSupport(const media::audio::common::AudioOffloadInfo& info, 187 media::AudioOffloadMode* _aidl_return) override; 188 binder::Status isDirectOutputSupported(const AudioConfigBase& config, 189 const media::audio::common::AudioAttributes& attributes, 190 bool* _aidl_return) override; 191 binder::Status listAudioPorts(media::AudioPortRole role, media::AudioPortType type, 192 Int* count, std::vector<media::AudioPortFw>* ports, 193 int32_t* _aidl_return) override; 194 binder::Status listDeclaredDevicePorts(media::AudioPortRole role, 195 std::vector<media::AudioPortFw>* _aidl_return) override; 196 binder::Status getAudioPort(int portId, 197 media::AudioPortFw* _aidl_return) override; 198 binder::Status createAudioPatch(const media::AudioPatchFw& patch, int32_t handle, 199 int32_t* _aidl_return) override; 200 binder::Status releaseAudioPatch(int32_t handle) override; 201 binder::Status listAudioPatches(Int* count, std::vector<media::AudioPatchFw>* patches, 202 int32_t* _aidl_return) override; 203 binder::Status setAudioPortConfig(const media::AudioPortConfigFw& config) override; 204 binder::Status registerClient(const sp<media::IAudioPolicyServiceClient>& client) override; 205 binder::Status setAudioPortCallbacksEnabled(bool enabled) override; 206 binder::Status setAudioVolumeGroupCallbacksEnabled(bool enabled) override; 207 binder::Status acquireSoundTriggerSession(media::SoundTriggerSession* _aidl_return) override; 208 binder::Status releaseSoundTriggerSession(int32_t session) override; 209 binder::Status getPhoneState(AudioMode* _aidl_return) override; 210 binder::Status registerPolicyMixes(const std::vector<media::AudioMix>& mixes, 211 bool registration) override; 212 binder::Status updatePolicyMixes( 213 const ::std::vector<::android::media::AudioMixUpdate>& updates) override; 214 binder::Status setUidDeviceAffinities(int32_t uid, 215 const std::vector<AudioDevice>& devices) override; 216 binder::Status removeUidDeviceAffinities(int32_t uid) override; 217 binder::Status setUserIdDeviceAffinities( 218 int32_t userId, 219 const std::vector<AudioDevice>& devices) override; 220 binder::Status removeUserIdDeviceAffinities(int32_t userId) override; 221 binder::Status startAudioSource(const media::AudioPortConfigFw& source, 222 const media::audio::common::AudioAttributes& attributes, 223 int32_t* _aidl_return) override; 224 binder::Status stopAudioSource(int32_t portId) override; 225 binder::Status setMasterMono(bool mono) override; 226 binder::Status getMasterMono(bool* _aidl_return) override; 227 binder::Status getStreamVolumeDB(AudioStreamType stream, int32_t index, 228 const AudioDeviceDescription& device, 229 float* _aidl_return) override; 230 binder::Status getSurroundFormats(Int* count, 231 std::vector<AudioFormatDescription>* formats, 232 std::vector<bool>* formatsEnabled) override; 233 binder::Status getReportedSurroundFormats( 234 Int* count, std::vector<AudioFormatDescription>* formats) override; 235 binder::Status getHwOffloadFormatsSupportedForBluetoothMedia( 236 const AudioDeviceDescription& device, 237 std::vector<AudioFormatDescription>* _aidl_return) override; 238 binder::Status setSurroundFormatEnabled(const AudioFormatDescription& audioFormat, 239 bool enabled) override; 240 binder::Status setAssistantServicesUids(const std::vector<int32_t>& uids) override; 241 binder::Status setActiveAssistantServicesUids(const std::vector<int32_t>& activeUids) override; 242 binder::Status setA11yServicesUids(const std::vector<int32_t>& uids) override; 243 binder::Status setCurrentImeUid(int32_t uid) override; 244 binder::Status isHapticPlaybackSupported(bool* _aidl_return) override; 245 binder::Status isUltrasoundSupported(bool* _aidl_return) override; 246 binder::Status isHotwordStreamSupported(bool lookbackAudio, bool* _aidl_return) override; 247 binder::Status listAudioProductStrategies( 248 std::vector<media::AudioProductStrategy>* _aidl_return) override; 249 binder::Status getProductStrategyFromAudioAttributes( 250 const media::audio::common::AudioAttributes& aa, 251 bool fallbackOnDefault, 252 int32_t* _aidl_return) override; 253 binder::Status listAudioVolumeGroups( 254 std::vector<media::AudioVolumeGroup>* _aidl_return) override; 255 binder::Status getVolumeGroupFromAudioAttributes( 256 const media::audio::common::AudioAttributes& aa, 257 bool fallbackOnDefault, 258 int32_t* _aidl_return) override; 259 binder::Status setRttEnabled(bool enabled) override; 260 binder::Status isCallScreenModeSupported(bool* _aidl_return) override; 261 binder::Status setDevicesRoleForStrategy( 262 int32_t strategy, media::DeviceRole role, 263 const std::vector<AudioDevice>& devices) override; 264 binder::Status removeDevicesRoleForStrategy( 265 int32_t strategy, media::DeviceRole role, 266 const std::vector<AudioDevice>& devices) override; 267 binder::Status clearDevicesRoleForStrategy( 268 int32_t strategy, 269 media::DeviceRole role) override; 270 binder::Status getDevicesForRoleAndStrategy( 271 int32_t strategy, media::DeviceRole role, 272 std::vector<AudioDevice>* _aidl_return) override; 273 binder::Status setDevicesRoleForCapturePreset( 274 AudioSource audioSource, 275 media::DeviceRole role, 276 const std::vector<AudioDevice>& devices) override; 277 binder::Status addDevicesRoleForCapturePreset( 278 AudioSource audioSource, 279 media::DeviceRole role, 280 const std::vector<AudioDevice>& devices) override; 281 binder::Status removeDevicesRoleForCapturePreset( 282 AudioSource audioSource, 283 media::DeviceRole role, 284 const std::vector<AudioDevice>& devices) override; 285 binder::Status clearDevicesRoleForCapturePreset(AudioSource audioSource, 286 media::DeviceRole role) override; 287 binder::Status getDevicesForRoleAndCapturePreset( 288 AudioSource audioSource, 289 media::DeviceRole role, 290 std::vector<AudioDevice>* _aidl_return) override; 291 binder::Status registerSoundTriggerCaptureStateListener( 292 const sp<media::ICaptureStateListener>& listener, bool* _aidl_return) override; 293 294 binder::Status getSpatializer(const sp<media::INativeSpatializerCallback>& callback, 295 media::GetSpatializerResponse* _aidl_return) override; 296 binder::Status canBeSpatialized( 297 const std::optional<media::audio::common::AudioAttributes>& attr, 298 const std::optional<AudioConfig>& config, 299 const std::vector<AudioDevice>& devices, 300 bool* _aidl_return) override; 301 302 binder::Status getDirectPlaybackSupport(const media::audio::common::AudioAttributes& attr, 303 const AudioConfig& config, 304 media::AudioDirectMode* _aidl_return) override; 305 306 binder::Status getDirectProfilesForAttributes(const media::audio::common::AudioAttributes& attr, 307 std::vector<media::audio::common::AudioProfile>* _aidl_return) override; 308 309 binder::Status getSupportedMixerAttributes( 310 int32_t portId, 311 std::vector<media::AudioMixerAttributesInternal>* _aidl_return) override; 312 binder::Status setPreferredMixerAttributes( 313 const media::audio::common::AudioAttributes& attr, 314 int32_t portId, 315 int32_t uid, 316 const media::AudioMixerAttributesInternal& mixerAttr) override; 317 binder::Status getPreferredMixerAttributes( 318 const media::audio::common::AudioAttributes& attr, 319 int32_t portId, 320 std::optional<media::AudioMixerAttributesInternal>* _aidl_return) override; 321 binder::Status clearPreferredMixerAttributes(const media::audio::common::AudioAttributes& attr, 322 int32_t portId, 323 int32_t uid) override; 324 binder::Status getRegisteredPolicyMixes( 325 std::vector <::android::media::AudioMix>* mixes) override; 326 327 // Should only be called by AudioService to push permission data down to audioserver 328 binder::Status getPermissionController(sp<INativePermissionController>* out) override; 329 330 status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) override; 331 332 // -- IAudioPolicyLocal methods 333 const IPermissionProvider& getPermissionProvider() const override; 334 335 // IBinder::DeathRecipient 336 virtual void binderDied(const wp<IBinder>& who); 337 338 // RefBase 339 virtual void onFirstRef(); 340 341 // Commence initialization when AudioSystem is ready. 342 void onAudioSystemReady(); 343 344 // 345 // Helpers for the struct audio_policy_service_ops implementation. 346 // This is used by the audio policy manager for certain operations that 347 // are implemented by the policy service. 348 // 349 virtual void setParameters(audio_io_handle_t ioHandle, 350 const char *keyValuePairs, 351 int delayMs); 352 353 virtual status_t setStreamVolume(audio_stream_type_t stream, 354 float volume, 355 audio_io_handle_t output, 356 int delayMs = 0); 357 virtual status_t setVoiceVolume(float volume, int delayMs = 0); 358 359 void doOnNewAudioModulesAvailable(); 360 status_t doStopOutput(audio_port_handle_t portId); 361 void doReleaseOutput(audio_port_handle_t portId); 362 363 status_t clientCreateAudioPatch(const struct audio_patch *patch, 364 audio_patch_handle_t *handle, 365 int delayMs); 366 status_t clientReleaseAudioPatch(audio_patch_handle_t handle, 367 int delayMs); 368 virtual status_t clientSetAudioPortConfig(const struct audio_port_config *config, 369 int delayMs); 370 371 void removeNotificationClient(uid_t uid, pid_t pid); 372 void onAudioPortListUpdate(); 373 void doOnAudioPortListUpdate(); 374 void onAudioPatchListUpdate(); 375 void doOnAudioPatchListUpdate(); 376 377 void onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state); 378 void doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state); 379 void onRecordingConfigurationUpdate(int event, 380 const record_client_info_t *clientInfo, 381 const audio_config_base_t *clientConfig, 382 std::vector<effect_descriptor_t> clientEffects, 383 const audio_config_base_t *deviceConfig, 384 std::vector<effect_descriptor_t> effects, 385 audio_patch_handle_t patchHandle, 386 audio_source_t source); 387 void doOnRecordingConfigurationUpdate(int event, 388 const record_client_info_t *clientInfo, 389 const audio_config_base_t *clientConfig, 390 std::vector<effect_descriptor_t> clientEffects, 391 const audio_config_base_t *deviceConfig, 392 std::vector<effect_descriptor_t> effects, 393 audio_patch_handle_t patchHandle, 394 audio_source_t source); 395 396 void onAudioVolumeGroupChanged(volume_group_t group, int flags); 397 void doOnAudioVolumeGroupChanged(volume_group_t group, int flags); 398 399 void onRoutingUpdated(); 400 void doOnRoutingUpdated(); 401 402 void onVolumeRangeInitRequest(); 403 void doOnVolumeRangeInitRequest(); 404 405 /** 406 * Spatializer SpatializerPolicyCallback implementation. 407 * onCheckSpatializer() sends an event on mOutputCommandThread which executes 408 * doOnCheckSpatializer() to check if a Spatializer output must be opened or closed 409 * by audio policy manager and attach/detach the spatializer effect accordingly. 410 */ 411 void onCheckSpatializer() override; 412 void onCheckSpatializer_l() REQUIRES(mMutex); 413 void doOnCheckSpatializer(); 414 415 void onUpdateActiveSpatializerTracks_l() REQUIRES(mMutex); 416 void doOnUpdateActiveSpatializerTracks(); 417 418 419 void setEffectSuspended(int effectId, 420 audio_session_t sessionId, 421 bool suspended); 422 423 private: 424 AudioPolicyService() ANDROID_API; 425 virtual ~AudioPolicyService(); 426 427 status_t dumpInternals(int fd) REQUIRES(mMutex); 428 429 // Handles binder shell commands 430 virtual status_t shellCommand(int in, int out, int err, Vector<String16>& args); 431 432 433 // Sets whether the given UID records only silence 434 virtual void setAppState_l(sp<AudioRecordClient> client, app_state_t state) REQUIRES(mMutex); 435 436 // Overrides the UID state as if it is idle 437 status_t handleSetUidState(Vector<String16>& args, int err); 438 439 // Clears the override for the UID state 440 status_t handleResetUidState(Vector<String16>& args, int err); 441 442 // Gets the UID state 443 status_t handleGetUidState(Vector<String16>& args, int out, int err); 444 445 // Prints the shell command help 446 status_t printHelp(int out); 447 448 std::string getDeviceTypeStrForPortId(audio_port_handle_t portId); 449 450 status_t getAudioPolicyEffects(sp<AudioPolicyEffects>& audioPolicyEffects); 451 452 app_state_t apmStatFromAmState(int amState); 453 454 bool isSupportedSystemUsage(audio_usage_t usage); 455 status_t validateUsage(const audio_attributes_t& attr); 456 status_t validateUsage(const audio_attributes_t& attr, 457 const AttributionSourceState& attributionSource); 458 459 void updateUidStates(); 460 void updateUidStates_l() REQUIRES(mMutex); 461 462 void silenceAllRecordings_l() REQUIRES(mMutex); 463 464 static bool isVirtualSource(audio_source_t source); 465 466 /** returns true if the audio source must be silenced when the corresponding app op is denied. 467 * false if the audio source does not actually capture from the microphone while still 468 * being mapped to app op OP_RECORD_AUDIO and not a specialized op tracked separately. 469 * See getOpForSource(). 470 */ 471 static bool isAppOpSource(audio_source_t source); 472 473 status_t registerOutput(audio_io_handle_t output, 474 const audio_config_base_t& config, 475 const audio_output_flags_t flags); 476 status_t unregisterOutput(audio_io_handle_t output); 477 478 // If recording we need to make sure the UID is allowed to do that. If the UID is idle 479 // then it cannot record and gets buffers with zeros - silence. As soon as the UID 480 // transitions to an active state we will start reporting buffers with data. This approach 481 // transparently handles recording while the UID transitions between idle/active state 482 // avoiding to get stuck in a state receiving non-empty buffers while idle or in a state 483 // receiving empty buffers while active. 484 class UidPolicy : public BnUidObserver, public virtual IBinder::DeathRecipient { 485 public: UidPolicy(wp<AudioPolicyService> service)486 explicit UidPolicy(wp<AudioPolicyService> service) 487 : mService(service), mObserverRegistered(false), 488 mCurrentImeUid(0), 489 mRttEnabled(false) {} 490 491 void registerSelf(); 492 void unregisterSelf(); 493 494 // IBinder::DeathRecipient implementation 495 void binderDied(const wp<IBinder> &who) override; 496 497 bool isUidActive(uid_t uid); 498 int getUidState(uid_t uid); 499 void setAssistantUids(const std::vector<uid_t>& uids); 500 bool isAssistantUid(uid_t uid); 501 void setActiveAssistantUids(const std::vector<uid_t>& activeUids); 502 bool isActiveAssistantUid(uid_t uid); setA11yUids(const std::vector<uid_t> & uids)503 void setA11yUids(const std::vector<uid_t>& uids) { mA11yUids.clear(); mA11yUids = uids; } 504 bool isA11yUid(uid_t uid); 505 bool isA11yOnTop(); setCurrentImeUid(uid_t uid)506 void setCurrentImeUid(uid_t uid) { mCurrentImeUid = uid; } isCurrentImeUid(uid_t uid)507 bool isCurrentImeUid(uid_t uid) { return uid == mCurrentImeUid; } setRttEnabled(bool enabled)508 void setRttEnabled(bool enabled) { mRttEnabled = enabled; } isRttEnabled()509 bool isRttEnabled() { return mRttEnabled; } 510 511 // BnUidObserver implementation 512 void onUidActive(uid_t uid) override; 513 void onUidGone(uid_t uid, bool disabled) override; 514 void onUidIdle(uid_t uid, bool disabled) override; 515 void onUidStateChanged(uid_t uid, int32_t procState, int64_t procStateSeq, 516 int32_t capability) override; 517 void onUidProcAdjChanged(uid_t uid, int32_t adj) override; 518 519 520 void updateUid(std::unordered_map<uid_t, std::pair<bool, int>> *uids, 521 uid_t uid, bool active, int state, bool insert); 522 523 void dumpInternals(int fd); 524 525 private: 526 void notifyService(); 527 void updateUidLocked(std::unordered_map<uid_t, std::pair<bool, int>> *uids, 528 uid_t uid, bool active, int state, bool insert); 529 void checkRegistered(); 530 531 wp<AudioPolicyService> mService; 532 audio_utils::mutex mMutex{audio_utils::MutexOrder::kUidPolicy_Mutex}; 533 ActivityManager mAm; 534 bool mObserverRegistered = false; 535 std::unordered_map<uid_t, std::pair<bool, int>> mCachedUids GUARDED_BY(mMutex); 536 std::vector<uid_t> mAssistantUids; 537 std::vector<uid_t> mActiveAssistantUids; 538 std::vector<uid_t> mA11yUids; 539 uid_t mCurrentImeUid = -1; 540 bool mRttEnabled = false; 541 }; 542 543 // If sensor privacy is enabled then all apps, including those that are active, should be 544 // prevented from recording. This is handled similar to idle UIDs, any app that attempts 545 // to record while sensor privacy is enabled will receive buffers with zeros. As soon as 546 // sensor privacy is disabled active apps will receive the expected data when recording. 547 class SensorPrivacyPolicy : public hardware::BnSensorPrivacyListener { 548 public: SensorPrivacyPolicy(wp<AudioPolicyService> service)549 explicit SensorPrivacyPolicy(wp<AudioPolicyService> service) 550 : mService(service) {} 551 552 void registerSelf(); 553 void unregisterSelf(); 554 555 bool isSensorPrivacyEnabled(); 556 557 binder::Status onSensorPrivacyChanged(int toggleType, int sensor, 558 bool enabled); 559 onSensorPrivacyStateChanged(int,int,int)560 binder::Status onSensorPrivacyStateChanged(int, int, int) { 561 return binder::Status::ok(); 562 } 563 564 private: 565 wp<AudioPolicyService> mService; 566 std::atomic_bool mSensorPrivacyEnabled = false; 567 }; 568 569 // Thread used to send audio config commands to audio flinger 570 // For audio config commands, it is necessary because audio flinger requires that the calling 571 // process (user) has permission to modify audio settings. 572 public: 573 class AudioCommandThread : public Thread { 574 class AudioCommand; 575 public: 576 577 // commands for tone AudioCommand 578 enum { 579 SET_VOLUME, 580 SET_PARAMETERS, 581 SET_VOICE_VOLUME, 582 STOP_OUTPUT, 583 RELEASE_OUTPUT, 584 CREATE_AUDIO_PATCH, 585 RELEASE_AUDIO_PATCH, 586 UPDATE_AUDIOPORT_LIST, 587 UPDATE_AUDIOPATCH_LIST, 588 CHANGED_AUDIOVOLUMEGROUP, 589 SET_AUDIOPORT_CONFIG, 590 DYN_POLICY_MIX_STATE_UPDATE, 591 RECORDING_CONFIGURATION_UPDATE, 592 SET_EFFECT_SUSPENDED, 593 AUDIO_MODULES_UPDATE, 594 ROUTING_UPDATED, 595 UPDATE_UID_STATES, 596 CHECK_SPATIALIZER_OUTPUT, // verify if spatializer effect should be created or moved 597 UPDATE_ACTIVE_SPATIALIZER_TRACKS, // Update active track counts on spalializer output 598 VOL_RANGE_INIT_REQUEST, // request to reset the volume range indices 599 }; 600 601 AudioCommandThread (String8 name, const wp<AudioPolicyService>& service); 602 virtual ~AudioCommandThread(); 603 604 status_t dump(int fd); 605 606 // Thread virtuals 607 virtual void onFirstRef(); 608 virtual bool threadLoop(); 609 610 void exit(); 611 status_t volumeCommand(audio_stream_type_t stream, float volume, 612 audio_io_handle_t output, int delayMs = 0); 613 status_t parametersCommand(audio_io_handle_t ioHandle, 614 const char *keyValuePairs, int delayMs = 0); 615 status_t voiceVolumeCommand(float volume, int delayMs = 0); 616 void stopOutputCommand(audio_port_handle_t portId); 617 void releaseOutputCommand(audio_port_handle_t portId); 618 status_t sendCommand(sp<AudioCommand>& command, int delayMs = 0); 619 void insertCommand_l(sp<AudioCommand>& command, int delayMs = 0); 620 status_t createAudioPatchCommand(const struct audio_patch *patch, 621 audio_patch_handle_t *handle, 622 int delayMs); 623 status_t releaseAudioPatchCommand(audio_patch_handle_t handle, 624 int delayMs); 625 void updateAudioPortListCommand(); 626 void updateAudioPatchListCommand(); 627 void changeAudioVolumeGroupCommand(volume_group_t group, int flags); 628 status_t setAudioPortConfigCommand(const struct audio_port_config *config, 629 int delayMs); 630 void dynamicPolicyMixStateUpdateCommand(const String8& regId, 631 int32_t state); 632 void recordingConfigurationUpdateCommand( 633 int event, 634 const record_client_info_t *clientInfo, 635 const audio_config_base_t *clientConfig, 636 std::vector<effect_descriptor_t> clientEffects, 637 const audio_config_base_t *deviceConfig, 638 std::vector<effect_descriptor_t> effects, 639 audio_patch_handle_t patchHandle, 640 audio_source_t source); 641 void setEffectSuspendedCommand(int effectId, 642 audio_session_t sessionId, 643 bool suspended); 644 void audioModulesUpdateCommand(); 645 void routingChangedCommand(); 646 void updateUidStatesCommand(); 647 void checkSpatializerCommand(); 648 void updateActiveSpatializerTracksCommand(); 649 void volRangeInitReqCommand(); 650 651 void insertCommand_l(AudioCommand *command, int delayMs = 0); 652 private: 653 class AudioCommandData; 654 655 // descriptor for requested tone playback event 656 class AudioCommand: public RefBase { 657 658 public: AudioCommand()659 AudioCommand() 660 : mCommand(-1), mStatus(NO_ERROR), mWaitStatus(false) {} 661 662 void dump(char* buffer, size_t size); 663 664 int mCommand; // SET_VOLUME, SET_PARAMETERS... 665 nsecs_t mTime; // time stamp 666 audio_utils::mutex mMutex{audio_utils::MutexOrder::kAudioCommand_Mutex}; 667 audio_utils::condition_variable mCond; // condition for status return 668 status_t mStatus; // command status 669 bool mWaitStatus; // true if caller is waiting for status 670 sp<AudioCommandData> mParam; // command specific parameter data 671 }; 672 673 class AudioCommandData: public RefBase { 674 public: ~AudioCommandData()675 virtual ~AudioCommandData() {} 676 protected: AudioCommandData()677 AudioCommandData() {} 678 }; 679 680 class VolumeData : public AudioCommandData { 681 public: 682 audio_stream_type_t mStream; 683 float mVolume; 684 audio_io_handle_t mIO; 685 }; 686 687 class ParametersData : public AudioCommandData { 688 public: 689 audio_io_handle_t mIO; 690 String8 mKeyValuePairs; 691 }; 692 693 class VoiceVolumeData : public AudioCommandData { 694 public: 695 float mVolume; 696 }; 697 698 class StopOutputData : public AudioCommandData { 699 public: 700 audio_port_handle_t mPortId; 701 }; 702 703 class ReleaseOutputData : public AudioCommandData { 704 public: 705 audio_port_handle_t mPortId; 706 }; 707 708 class CreateAudioPatchData : public AudioCommandData { 709 public: 710 struct audio_patch mPatch; 711 audio_patch_handle_t mHandle; 712 }; 713 714 class ReleaseAudioPatchData : public AudioCommandData { 715 public: 716 audio_patch_handle_t mHandle; 717 }; 718 719 class AudioVolumeGroupData : public AudioCommandData { 720 public: 721 volume_group_t mGroup; 722 int mFlags; 723 }; 724 725 class SetAudioPortConfigData : public AudioCommandData { 726 public: 727 struct audio_port_config mConfig; 728 }; 729 730 class DynPolicyMixStateUpdateData : public AudioCommandData { 731 public: 732 String8 mRegId; 733 int32_t mState; 734 }; 735 736 class RecordingConfigurationUpdateData : public AudioCommandData { 737 public: 738 int mEvent; 739 record_client_info_t mClientInfo; 740 struct audio_config_base mClientConfig; 741 std::vector<effect_descriptor_t> mClientEffects; 742 struct audio_config_base mDeviceConfig; 743 std::vector<effect_descriptor_t> mEffects; 744 audio_patch_handle_t mPatchHandle; 745 audio_source_t mSource; 746 }; 747 748 class SetEffectSuspendedData : public AudioCommandData { 749 public: 750 int mEffectId; 751 audio_session_t mSessionId; 752 bool mSuspended; 753 }; 754 755 mutable audio_utils::mutex mMutex{audio_utils::MutexOrder::kCommandThread_Mutex}; 756 audio_utils::condition_variable mWaitWorkCV; 757 Vector < sp<AudioCommand> > mAudioCommands; // list of pending commands 758 sp<AudioCommand> mLastCommand; // last processed command (used by dump) 759 String8 mName; // string used by wake lock fo delayed commands 760 wp<AudioPolicyService> mService; 761 }; 762 763 private: 764 class AudioPolicyClient : public AudioPolicyClientInterface 765 { 766 public: AudioPolicyClient(AudioPolicyService * service)767 explicit AudioPolicyClient(AudioPolicyService *service) : mAudioPolicyService(service) {} ~AudioPolicyClient()768 virtual ~AudioPolicyClient() {} 769 770 virtual status_t getAudioPolicyConfig(media::AudioPolicyConfig *config); 771 772 // 773 // Audio HW module functions 774 // 775 776 // loads a HW module. 777 virtual audio_module_handle_t loadHwModule(const char *name); 778 779 // 780 // Audio output Control functions 781 // 782 783 // opens an audio output with the requested parameters. The parameter values can indicate to use the default values 784 // in case the audio policy manager has no specific requirements for the output being opened. 785 // When the function returns, the parameter values reflect the actual values used by the audio hardware output stream. 786 // The audio policy manager can check if the proposed parameters are suitable or not and act accordingly. 787 virtual status_t openOutput(audio_module_handle_t module, 788 audio_io_handle_t *output, 789 audio_config_t *halConfig, 790 audio_config_base_t *mixerConfig, 791 const sp<DeviceDescriptorBase>& device, 792 uint32_t *latencyMs, 793 audio_output_flags_t flags); 794 // creates a special output that is duplicated to the two outputs passed as arguments. The duplication is performed by 795 // a special mixer thread in the AudioFlinger. 796 virtual audio_io_handle_t openDuplicateOutput(audio_io_handle_t output1, audio_io_handle_t output2); 797 // closes the output stream 798 virtual status_t closeOutput(audio_io_handle_t output); 799 // suspends the output. When an output is suspended, the corresponding audio hardware output stream is placed in 800 // standby and the AudioTracks attached to the mixer thread are still processed but the output mix is discarded. 801 virtual status_t suspendOutput(audio_io_handle_t output); 802 // restores a suspended output. 803 virtual status_t restoreOutput(audio_io_handle_t output); 804 805 // 806 // Audio input Control functions 807 // 808 809 // opens an audio input 810 virtual audio_io_handle_t openInput(audio_module_handle_t module, 811 audio_io_handle_t *input, 812 audio_config_t *config, 813 audio_devices_t *devices, 814 const String8& address, 815 audio_source_t source, 816 audio_input_flags_t flags); 817 // closes an audio input 818 virtual status_t closeInput(audio_io_handle_t input); 819 // 820 // misc control functions 821 // 822 823 // set a stream volume for a particular output. For the same user setting, a given stream type can have different volumes 824 // for each output (destination device) it is attached to. 825 virtual status_t setStreamVolume(audio_stream_type_t stream, float volume, audio_io_handle_t output, int delayMs = 0); 826 827 // function enabling to send proprietary informations directly from audio policy manager to audio hardware interface. 828 virtual void setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs, int delayMs = 0); 829 // function enabling to receive proprietary informations directly from audio hardware interface to audio policy manager. 830 virtual String8 getParameters(audio_io_handle_t ioHandle, const String8& keys); 831 832 // set down link audio volume. 833 virtual status_t setVoiceVolume(float volume, int delayMs = 0); 834 835 // move effect to the specified output 836 virtual status_t moveEffects(audio_session_t session, 837 audio_io_handle_t srcOutput, 838 audio_io_handle_t dstOutput); 839 840 void setEffectSuspended(int effectId, 841 audio_session_t sessionId, 842 bool suspended) override; 843 844 /* Create a patch between several source and sink ports */ 845 virtual status_t createAudioPatch(const struct audio_patch *patch, 846 audio_patch_handle_t *handle, 847 int delayMs); 848 849 /* Release a patch */ 850 virtual status_t releaseAudioPatch(audio_patch_handle_t handle, 851 int delayMs); 852 853 /* Set audio port configuration */ 854 virtual status_t setAudioPortConfig(const struct audio_port_config *config, int delayMs); 855 856 virtual void onAudioPortListUpdate(); 857 virtual void onAudioPatchListUpdate(); 858 virtual void onDynamicPolicyMixStateUpdate(String8 regId, int32_t state); 859 virtual void onRecordingConfigurationUpdate(int event, 860 const record_client_info_t *clientInfo, 861 const audio_config_base_t *clientConfig, 862 std::vector<effect_descriptor_t> clientEffects, 863 const audio_config_base_t *deviceConfig, 864 std::vector<effect_descriptor_t> effects, 865 audio_patch_handle_t patchHandle, 866 audio_source_t source); 867 868 virtual void onAudioVolumeGroupChanged(volume_group_t group, int flags); 869 870 virtual void onRoutingUpdated(); 871 872 virtual void onVolumeRangeInitRequest(); 873 874 virtual audio_unique_id_t newAudioUniqueId(audio_unique_id_use_t use); 875 876 void setSoundTriggerCaptureState(bool active) override; 877 878 status_t getAudioPort(struct audio_port_v7 *port) override; 879 880 status_t updateSecondaryOutputs( 881 const TrackSecondaryOutputsMap& trackSecondaryOutputs) override; 882 883 status_t setDeviceConnectedState( 884 const struct audio_port_v7 *port, media::DeviceConnectedState state) override; 885 886 status_t invalidateTracks(const std::vector<audio_port_handle_t>& portIds) override; 887 888 status_t getAudioMixPort(const struct audio_port_v7 *devicePort, 889 struct audio_port_v7 *port) override; 890 891 status_t setTracksInternalMute( 892 const std::vector<media::TrackInternalMuteInfo>& tracksInternalMute) override; 893 894 private: 895 AudioPolicyService *mAudioPolicyService; 896 }; 897 898 // --- Notification Client --- 899 class NotificationClient : public IBinder::DeathRecipient { 900 public: 901 NotificationClient(const sp<AudioPolicyService>& service, 902 const sp<media::IAudioPolicyServiceClient>& client, 903 uid_t uid, pid_t pid); 904 virtual ~NotificationClient(); 905 906 void onAudioPortListUpdate(); 907 void onAudioPatchListUpdate(); 908 void onDynamicPolicyMixStateUpdate(const String8& regId, 909 int32_t state); 910 void onAudioVolumeGroupChanged(volume_group_t group, int flags); 911 void onRecordingConfigurationUpdate( 912 int event, 913 const record_client_info_t *clientInfo, 914 const audio_config_base_t *clientConfig, 915 std::vector<effect_descriptor_t> clientEffects, 916 const audio_config_base_t *deviceConfig, 917 std::vector<effect_descriptor_t> effects, 918 audio_patch_handle_t patchHandle, 919 audio_source_t source); 920 void onRoutingUpdated(); 921 void onVolumeRangeInitRequest(); 922 void setAudioPortCallbacksEnabled(bool enabled); 923 void setAudioVolumeGroupCallbacksEnabled(bool enabled); 924 uid()925 uid_t uid() { 926 return mUid; 927 } 928 929 // IBinder::DeathRecipient 930 virtual void binderDied(const wp<IBinder>& who); 931 932 private: 933 NotificationClient(const NotificationClient&); 934 NotificationClient& operator = (const NotificationClient&); 935 936 const wp<AudioPolicyService> mService; 937 const uid_t mUid; 938 const pid_t mPid; 939 const sp<media::IAudioPolicyServiceClient> mAudioPolicyServiceClient; 940 bool mAudioPortCallbacksEnabled; 941 bool mAudioVolumeGroupCallbacksEnabled; 942 }; 943 944 public: 945 class AudioClient : public virtual RefBase { 946 public: AudioClient(const audio_attributes_t attributes,const audio_io_handle_t io,const AttributionSourceState & attributionSource,const audio_session_t session,audio_port_handle_t portId,const audio_port_handle_t deviceId)947 AudioClient(const audio_attributes_t attributes, 948 const audio_io_handle_t io, 949 const AttributionSourceState& attributionSource, 950 const audio_session_t session, audio_port_handle_t portId, 951 const audio_port_handle_t deviceId) : 952 attributes(attributes), io(io), attributionSource( 953 attributionSource), session(session), portId(portId), 954 deviceId(deviceId), active(false) {} 955 ~AudioClient() override = default; 956 957 958 const audio_attributes_t attributes; // source, flags ... 959 const audio_io_handle_t io; // audio HAL stream IO handle 960 const AttributionSourceState attributionSource; //client attributionsource 961 const audio_session_t session; // audio session ID 962 const audio_port_handle_t portId; 963 const audio_port_handle_t deviceId; // selected input device port ID 964 bool active; // Playback/Capture is active or inactive 965 }; 966 private: 967 968 969 970 // --- AudioPlaybackClient --- 971 // Information about each registered AudioTrack client 972 // (between calls to getOutputForAttr() and releaseOutput()) 973 class AudioPlaybackClient : public AudioClient { 974 public: AudioPlaybackClient(const audio_attributes_t attributes,const audio_io_handle_t io,AttributionSourceState attributionSource,const audio_session_t session,audio_port_handle_t portId,audio_port_handle_t deviceId,audio_stream_type_t stream,bool isSpatialized)975 AudioPlaybackClient(const audio_attributes_t attributes, 976 const audio_io_handle_t io, AttributionSourceState attributionSource, 977 const audio_session_t session, audio_port_handle_t portId, 978 audio_port_handle_t deviceId, audio_stream_type_t stream, 979 bool isSpatialized) : 980 AudioClient(attributes, io, attributionSource, session, portId, 981 deviceId), stream(stream), isSpatialized(isSpatialized) {} 982 ~AudioPlaybackClient() override = default; 983 984 const audio_stream_type_t stream; 985 const bool isSpatialized; 986 }; 987 988 void getPlaybackClientAndEffects(audio_port_handle_t portId, 989 sp<AudioPlaybackClient>& client, 990 sp<AudioPolicyEffects>& effects, 991 const char *context); 992 993 994 // A class automatically clearing and restoring binder caller identity inside 995 // a code block (scoped variable) 996 // Declare one systematically before calling AudioPolicyManager methods so that they are 997 // executed with the same level of privilege as audioserver process. 998 class AutoCallerClear { 999 public: AutoCallerClear()1000 AutoCallerClear() : 1001 mToken(IPCThreadState::self()->clearCallingIdentity()) {} ~AutoCallerClear()1002 ~AutoCallerClear() { 1003 IPCThreadState::self()->restoreCallingIdentity(mToken); 1004 } 1005 1006 private: 1007 const int64_t mToken; 1008 }; 1009 1010 // Internal dump utilities. 1011 status_t dumpPermissionDenial(int fd); 1012 void loadAudioPolicyManager(); 1013 void unloadAudioPolicyManager(); 1014 1015 /** 1016 * Returns the number of active audio tracks on the specified output mixer. 1017 * The query can be specified to only include spatialized audio tracks or consider 1018 * all tracks. 1019 * @param output the I/O handle of the output mixer to consider 1020 * @param spatializedOnly true if only spatialized tracks should be considered 1021 * @return the number of active tracks. 1022 */ 1023 size_t countActiveClientsOnOutput_l( 1024 audio_io_handle_t output, bool spatializedOnly = true) REQUIRES(mMutex); 1025 1026 mutable audio_utils::mutex mMutex{audio_utils::MutexOrder::kAudioPolicyService_Mutex}; 1027 // prevents concurrent access to AudioPolicy manager functions changing 1028 // device connection state or routing. 1029 // mMutex protects AudioPolicyManager methods that can call into audio flinger 1030 // and possibly back in to audio policy service and acquire mEffectsLock. 1031 sp<AudioCommandThread> mAudioCommandThread; // audio commands thread 1032 sp<AudioCommandThread> mOutputCommandThread; // process stop and release output 1033 AudioPolicyInterface *mAudioPolicyManager; 1034 AudioPolicyClient *mAudioPolicyClient; 1035 std::vector<audio_usage_t> mSupportedSystemUsages; 1036 1037 mutable audio_utils::mutex mNotificationClientsMutex{ 1038 audio_utils::MutexOrder::kAudioPolicyService_NotificationClientsMutex}; 1039 DefaultKeyedVector<int64_t, sp<NotificationClient>> mNotificationClients 1040 GUARDED_BY(mNotificationClientsMutex); 1041 // Manage all effects configured in audio_effects.conf 1042 // never hold AudioPolicyService::mMutex when calling AudioPolicyEffects methods as 1043 // those can call back into AudioPolicyService methods and try to acquire the mutex 1044 sp<AudioPolicyEffects> mAudioPolicyEffects GUARDED_BY(mMutex); 1045 audio_mode_t mPhoneState GUARDED_BY(mMutex); 1046 uid_t mPhoneStateOwnerUid GUARDED_BY(mMutex); 1047 1048 sp<UidPolicy> mUidPolicy GUARDED_BY(mMutex); 1049 sp<SensorPrivacyPolicy> mSensorPrivacyPolicy GUARDED_BY(mMutex); 1050 1051 DefaultKeyedVector<audio_port_handle_t, sp<AudioRecordClient>> mAudioRecordClients 1052 GUARDED_BY(mMutex); 1053 DefaultKeyedVector<audio_port_handle_t, sp<AudioPlaybackClient>> mAudioPlaybackClients 1054 GUARDED_BY(mMutex); 1055 1056 MediaPackageManager mPackageManager; // To check allowPlaybackCapture 1057 1058 CaptureStateNotifier mCaptureStateNotifier; 1059 1060 // created in onFirstRef() and never cleared: does not need to be guarded by mMutex 1061 sp<Spatializer> mSpatializer; 1062 1063 void *mLibraryHandle = nullptr; 1064 CreateAudioPolicyManagerInstance mCreateAudioPolicyManager; 1065 DestroyAudioPolicyManagerInstance mDestroyAudioPolicyManager; 1066 std::unique_ptr<media::UsecaseValidator> mUsecaseValidator; 1067 const sp<NativePermissionController> mPermissionController; 1068 }; 1069 1070 } // namespace android 1071 1072 #endif // ANDROID_AUDIOPOLICYSERVICE_H 1073