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 #define LOG_TAG "AudioPolicyService"
18 //#define LOG_NDEBUG 0
19 
20 #include "Configuration.h"
21 #include <stdint.h>
22 #include <sys/time.h>
23 #include <dlfcn.h>
24 
25 #include <audio_utils/clock.h>
26 #include <binder/IServiceManager.h>
27 #include <utils/Log.h>
28 #include <cutils/properties.h>
29 #include <binder/IPCThreadState.h>
30 #include <binder/PermissionController.h>
31 #include <binder/IResultReceiver.h>
32 #include <utils/String16.h>
33 #include <utils/threads.h>
34 #include "AudioRecordClient.h"
35 #include "AudioPolicyService.h"
36 #include <hardware_legacy/power.h>
37 #include <media/AidlConversion.h>
38 #include <media/AudioEffect.h>
39 #include <media/AudioParameter.h>
40 #include <mediautils/MethodStatistics.h>
41 #include <mediautils/ServiceUtilities.h>
42 #include <mediautils/TimeCheck.h>
43 #include <sensorprivacy/SensorPrivacyManager.h>
44 
45 #include <system/audio.h>
46 #include <system/audio_policy.h>
47 #include <AudioPolicyConfig.h>
48 #include <AudioPolicyManager.h>
49 
50 namespace android {
51 using binder::Status;
52 using media::audio::common::Spatialization;
53 
54 static const char kDeadlockedString[] = "AudioPolicyService may be deadlocked\n";
55 static const char kCmdDeadlockedString[] = "AudioPolicyService command thread may be deadlocked\n";
56 static const char kAudioPolicyManagerCustomPath[] = "libaudiopolicymanagercustom.so";
57 
58 static const int kDumpLockTimeoutNs = 1 * NANOS_PER_SECOND;
59 
60 static const nsecs_t kAudioCommandTimeoutNs = seconds(3); // 3 seconds
61 
62 static const String16 sManageAudioPolicyPermission("android.permission.MANAGE_AUDIO_POLICY");
63 
64 // Creates an association between Binder code to name for IAudioPolicyService.
65 #define IAUDIOPOLICYSERVICE_BINDER_METHOD_MACRO_LIST \
66 BINDER_METHOD_ENTRY(onNewAudioModulesAvailable) \
67 BINDER_METHOD_ENTRY(setDeviceConnectionState) \
68 BINDER_METHOD_ENTRY(getDeviceConnectionState) \
69 BINDER_METHOD_ENTRY(handleDeviceConfigChange) \
70 BINDER_METHOD_ENTRY(setPhoneState) \
71 BINDER_METHOD_ENTRY(setForceUse) \
72 BINDER_METHOD_ENTRY(getForceUse) \
73 BINDER_METHOD_ENTRY(getOutput) \
74 BINDER_METHOD_ENTRY(getOutputForAttr) \
75 BINDER_METHOD_ENTRY(startOutput) \
76 BINDER_METHOD_ENTRY(stopOutput) \
77 BINDER_METHOD_ENTRY(releaseOutput) \
78 BINDER_METHOD_ENTRY(getInputForAttr) \
79 BINDER_METHOD_ENTRY(startInput) \
80 BINDER_METHOD_ENTRY(stopInput) \
81 BINDER_METHOD_ENTRY(releaseInput) \
82 BINDER_METHOD_ENTRY(setDeviceAbsoluteVolumeEnabled) \
83 BINDER_METHOD_ENTRY(initStreamVolume) \
84 BINDER_METHOD_ENTRY(setStreamVolumeIndex) \
85 BINDER_METHOD_ENTRY(getStreamVolumeIndex) \
86 BINDER_METHOD_ENTRY(setVolumeIndexForAttributes) \
87 BINDER_METHOD_ENTRY(getVolumeIndexForAttributes) \
88 BINDER_METHOD_ENTRY(getMaxVolumeIndexForAttributes) \
89 BINDER_METHOD_ENTRY(getMinVolumeIndexForAttributes) \
90 BINDER_METHOD_ENTRY(getStrategyForStream) \
91 BINDER_METHOD_ENTRY(getDevicesForAttributes) \
92 BINDER_METHOD_ENTRY(getOutputForEffect) \
93 BINDER_METHOD_ENTRY(registerEffect) \
94 BINDER_METHOD_ENTRY(unregisterEffect) \
95 BINDER_METHOD_ENTRY(setEffectEnabled) \
96 BINDER_METHOD_ENTRY(moveEffectsToIo) \
97 BINDER_METHOD_ENTRY(isStreamActive) \
98 BINDER_METHOD_ENTRY(isStreamActiveRemotely) \
99 BINDER_METHOD_ENTRY(isSourceActive) \
100 BINDER_METHOD_ENTRY(queryDefaultPreProcessing) \
101 BINDER_METHOD_ENTRY(addSourceDefaultEffect) \
102 BINDER_METHOD_ENTRY(addStreamDefaultEffect) \
103 BINDER_METHOD_ENTRY(removeSourceDefaultEffect) \
104 BINDER_METHOD_ENTRY(removeStreamDefaultEffect) \
105 BINDER_METHOD_ENTRY(setSupportedSystemUsages) \
106 BINDER_METHOD_ENTRY(setAllowedCapturePolicy) \
107 BINDER_METHOD_ENTRY(getOffloadSupport) \
108 BINDER_METHOD_ENTRY(isDirectOutputSupported) \
109 BINDER_METHOD_ENTRY(listAudioPorts) \
110 BINDER_METHOD_ENTRY(getAudioPort) \
111 BINDER_METHOD_ENTRY(createAudioPatch) \
112 BINDER_METHOD_ENTRY(releaseAudioPatch) \
113 BINDER_METHOD_ENTRY(listAudioPatches) \
114 BINDER_METHOD_ENTRY(setAudioPortConfig) \
115 BINDER_METHOD_ENTRY(registerClient) \
116 BINDER_METHOD_ENTRY(setAudioPortCallbacksEnabled) \
117 BINDER_METHOD_ENTRY(setAudioVolumeGroupCallbacksEnabled) \
118 BINDER_METHOD_ENTRY(acquireSoundTriggerSession) \
119 BINDER_METHOD_ENTRY(releaseSoundTriggerSession) \
120 BINDER_METHOD_ENTRY(getPhoneState) \
121 BINDER_METHOD_ENTRY(registerPolicyMixes) \
122 BINDER_METHOD_ENTRY(updatePolicyMixes) \
123 BINDER_METHOD_ENTRY(setUidDeviceAffinities) \
124 BINDER_METHOD_ENTRY(removeUidDeviceAffinities) \
125 BINDER_METHOD_ENTRY(setUserIdDeviceAffinities) \
126 BINDER_METHOD_ENTRY(removeUserIdDeviceAffinities) \
127 BINDER_METHOD_ENTRY(startAudioSource) \
128 BINDER_METHOD_ENTRY(stopAudioSource) \
129 BINDER_METHOD_ENTRY(setMasterMono) \
130 BINDER_METHOD_ENTRY(getMasterMono) \
131 BINDER_METHOD_ENTRY(getStreamVolumeDB) \
132 BINDER_METHOD_ENTRY(getSurroundFormats) \
133 BINDER_METHOD_ENTRY(getReportedSurroundFormats) \
134 BINDER_METHOD_ENTRY(getHwOffloadFormatsSupportedForBluetoothMedia) \
135 BINDER_METHOD_ENTRY(setSurroundFormatEnabled) \
136 BINDER_METHOD_ENTRY(setAssistantServicesUids) \
137 BINDER_METHOD_ENTRY(setActiveAssistantServicesUids) \
138 BINDER_METHOD_ENTRY(setA11yServicesUids) \
139 BINDER_METHOD_ENTRY(setCurrentImeUid) \
140 BINDER_METHOD_ENTRY(isHapticPlaybackSupported) \
141 BINDER_METHOD_ENTRY(isUltrasoundSupported) \
142 BINDER_METHOD_ENTRY(isHotwordStreamSupported) \
143 BINDER_METHOD_ENTRY(listAudioProductStrategies) \
144 BINDER_METHOD_ENTRY(getProductStrategyFromAudioAttributes) \
145 BINDER_METHOD_ENTRY(listAudioVolumeGroups) \
146 BINDER_METHOD_ENTRY(getVolumeGroupFromAudioAttributes) \
147 BINDER_METHOD_ENTRY(setRttEnabled) \
148 BINDER_METHOD_ENTRY(isCallScreenModeSupported) \
149 BINDER_METHOD_ENTRY(setDevicesRoleForStrategy) \
150 BINDER_METHOD_ENTRY(removeDevicesRoleForStrategy) \
151 BINDER_METHOD_ENTRY(clearDevicesRoleForStrategy) \
152 BINDER_METHOD_ENTRY(getDevicesForRoleAndStrategy) \
153 BINDER_METHOD_ENTRY(setDevicesRoleForCapturePreset) \
154 BINDER_METHOD_ENTRY(addDevicesRoleForCapturePreset) \
155 BINDER_METHOD_ENTRY(removeDevicesRoleForCapturePreset) \
156 BINDER_METHOD_ENTRY(clearDevicesRoleForCapturePreset) \
157 BINDER_METHOD_ENTRY(getDevicesForRoleAndCapturePreset) \
158 BINDER_METHOD_ENTRY(registerSoundTriggerCaptureStateListener) \
159 BINDER_METHOD_ENTRY(getSpatializer) \
160 BINDER_METHOD_ENTRY(canBeSpatialized) \
161 BINDER_METHOD_ENTRY(getDirectPlaybackSupport) \
162 BINDER_METHOD_ENTRY(getDirectProfilesForAttributes)  \
163 BINDER_METHOD_ENTRY(getSupportedMixerAttributes) \
164 BINDER_METHOD_ENTRY(setPreferredMixerAttributes) \
165 BINDER_METHOD_ENTRY(getPreferredMixerAttributes) \
166 BINDER_METHOD_ENTRY(clearPreferredMixerAttributes) \
167 BINDER_METHOD_ENTRY(getRegisteredPolicyMixes) \
168 BINDER_METHOD_ENTRY(getPermissionController) \
169                                                      \
170 // singleton for Binder Method Statistics for IAudioPolicyService
getIAudioPolicyServiceStatistics()171 static auto& getIAudioPolicyServiceStatistics() {
172     using Code = int;
173 
174 #pragma push_macro("BINDER_METHOD_ENTRY")
175 #undef BINDER_METHOD_ENTRY
176 #define BINDER_METHOD_ENTRY(ENTRY) \
177         {(Code)media::BnAudioPolicyService::TRANSACTION_##ENTRY, #ENTRY},
178 
179     static mediautils::MethodStatistics<Code> methodStatistics{
180         IAUDIOPOLICYSERVICE_BINDER_METHOD_MACRO_LIST
181         METHOD_STATISTICS_BINDER_CODE_NAMES(Code)
182     };
183 #pragma pop_macro("BINDER_METHOD_ENTRY")
184 
185     return methodStatistics;
186 }
187 
188 // ----------------------------------------------------------------------------
189 
createAudioPolicyManager(AudioPolicyClientInterface * clientInterface)190 static AudioPolicyInterface* createAudioPolicyManager(AudioPolicyClientInterface *clientInterface)
191 {
192     AudioPolicyManager *apm = nullptr;
193     media::AudioPolicyConfig apmConfig;
194     if (status_t status = clientInterface->getAudioPolicyConfig(&apmConfig); status == OK) {
195         auto config = AudioPolicyConfig::loadFromApmAidlConfigWithFallback(apmConfig);
196         LOG_ALWAYS_FATAL_IF(config->getEngineLibraryNameSuffix() !=
197                 AudioPolicyConfig::kDefaultEngineLibraryNameSuffix,
198                 "Only default engine is currently supported with the AIDL HAL");
199         apm = new AudioPolicyManager(config,
200                 loadApmEngineLibraryAndCreateEngine(
201                         config->getEngineLibraryNameSuffix(), apmConfig.engineConfig),
202                 clientInterface);
203     } else {
204         auto config = AudioPolicyConfig::loadFromApmXmlConfigWithFallback();  // This can't fail.
205         apm = new AudioPolicyManager(config,
206                 loadApmEngineLibraryAndCreateEngine(config->getEngineLibraryNameSuffix()),
207                 clientInterface);
208     }
209     status_t status = apm->initialize();
210     if (status != NO_ERROR) {
211         delete apm;
212         apm = nullptr;
213     }
214     return apm;
215 }
216 
destroyAudioPolicyManager(AudioPolicyInterface * interface)217 static void destroyAudioPolicyManager(AudioPolicyInterface *interface)
218 {
219     delete interface;
220 }
221 // ----------------------------------------------------------------------------
222 
AudioPolicyService()223 AudioPolicyService::AudioPolicyService()
224     : BnAudioPolicyService(),
225       mAudioPolicyManager(NULL),
226       mAudioPolicyClient(NULL),
227       mPhoneState(AUDIO_MODE_INVALID),
228       mCaptureStateNotifier(false),
229       mCreateAudioPolicyManager(createAudioPolicyManager),
230       mDestroyAudioPolicyManager(destroyAudioPolicyManager),
231       mUsecaseValidator(media::createUsecaseValidator()),
232       mPermissionController(sp<NativePermissionController>::make())
233 {
234       setMinSchedulerPolicy(SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
235       setInheritRt(true);
236 }
237 
loadAudioPolicyManager()238 void AudioPolicyService::loadAudioPolicyManager()
239 {
240     mLibraryHandle = dlopen(kAudioPolicyManagerCustomPath, RTLD_NOW);
241     if (mLibraryHandle != nullptr) {
242         ALOGI("%s loading %s", __func__, kAudioPolicyManagerCustomPath);
243         mCreateAudioPolicyManager = reinterpret_cast<CreateAudioPolicyManagerInstance>
244                                             (dlsym(mLibraryHandle, "createAudioPolicyManager"));
245         const char *lastError = dlerror();
246         ALOGW_IF(mCreateAudioPolicyManager == nullptr, "%s createAudioPolicyManager is null %s",
247                     __func__, lastError != nullptr ? lastError : "no error");
248 
249         mDestroyAudioPolicyManager = reinterpret_cast<DestroyAudioPolicyManagerInstance>(
250                                         dlsym(mLibraryHandle, "destroyAudioPolicyManager"));
251         lastError = dlerror();
252         ALOGW_IF(mDestroyAudioPolicyManager == nullptr, "%s destroyAudioPolicyManager is null %s",
253                     __func__, lastError != nullptr ? lastError : "no error");
254         if (mCreateAudioPolicyManager == nullptr || mDestroyAudioPolicyManager == nullptr){
255             unloadAudioPolicyManager();
256             LOG_ALWAYS_FATAL("could not find audiopolicymanager interface methods");
257         }
258     }
259 }
260 
onFirstRef()261 void AudioPolicyService::onFirstRef()
262 {
263     // Log an AudioPolicy "constructor" mediametrics event on first ref.
264     // This records the time it takes to load the audio modules and devices.
265     mediametrics::Defer defer([beginNs = systemTime()] {
266         mediametrics::LogItem(AMEDIAMETRICS_KEY_AUDIO_POLICY)
267             .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CTOR)
268             .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
269             .record(); });
270     {
271         audio_utils::lock_guard _l(mMutex);
272 
273         // start audio commands thread
274         mAudioCommandThread = new AudioCommandThread(String8("ApmAudio"), this);
275         // start output activity command thread
276         mOutputCommandThread = new AudioCommandThread(String8("ApmOutput"), this);
277 
278         mAudioPolicyClient = new AudioPolicyClient(this);
279 
280         loadAudioPolicyManager();
281         mAudioPolicyManager = mCreateAudioPolicyManager(mAudioPolicyClient);
282     }
283 
284     // load audio processing modules
285     const sp<EffectsFactoryHalInterface> effectsFactoryHal = EffectsFactoryHalInterface::create();
286     auto audioPolicyEffects = sp<AudioPolicyEffects>::make(effectsFactoryHal);
287     auto uidPolicy = sp<UidPolicy>::make(this);
288     auto sensorPrivacyPolicy = sp<SensorPrivacyPolicy>::make(this);
289     {
290         audio_utils::lock_guard _l(mMutex);
291         mAudioPolicyEffects = audioPolicyEffects;
292         mUidPolicy = uidPolicy;
293         mSensorPrivacyPolicy = sensorPrivacyPolicy;
294     }
295     uidPolicy->registerSelf();
296     sensorPrivacyPolicy->registerSelf();
297 
298     // Create spatializer if supported
299     if (mAudioPolicyManager != nullptr) {
300         audio_utils::lock_guard _l(mMutex);
301         const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
302         AudioDeviceTypeAddrVector devices;
303         bool hasSpatializer = mAudioPolicyManager->canBeSpatialized(&attr, nullptr, devices);
304         if (hasSpatializer) {
305             // Unlock as Spatializer::create() will use the callback and acquire the
306             // AudioPolicyService_Mutex.
307             mMutex.unlock();
308             mSpatializer = Spatializer::create(this, effectsFactoryHal);
309             mMutex.lock();
310         }
311         if (mSpatializer == nullptr) {
312             // No spatializer created, signal the reason: NO_INIT a failure, OK means intended.
313             const status_t createStatus = hasSpatializer ? NO_INIT : OK;
314             Spatializer::sendEmptyCreateSpatializerMetricWithStatus(createStatus);
315         }
316     }
317     AudioSystem::audioPolicyReady();
318 }
319 
getPermissionProvider() const320 const IPermissionProvider& AudioPolicyService::getPermissionProvider() const {
321     return *mPermissionController;
322 }
323 
onAudioSystemReady()324 void AudioPolicyService::onAudioSystemReady() {
325     sp<AudioPolicyEffects> audioPolicyEffects;
326     {
327         audio_utils::lock_guard _l(mMutex);
328 
329         audioPolicyEffects = mAudioPolicyEffects;
330     }
331     audioPolicyEffects->initDefaultDeviceEffects();
332 }
333 
unloadAudioPolicyManager()334 void AudioPolicyService::unloadAudioPolicyManager()
335 {
336     ALOGV("%s ", __func__);
337     if (mLibraryHandle != nullptr) {
338         dlclose(mLibraryHandle);
339     }
340     mLibraryHandle = nullptr;
341     mCreateAudioPolicyManager = nullptr;
342     mDestroyAudioPolicyManager = nullptr;
343 }
344 
~AudioPolicyService()345 AudioPolicyService::~AudioPolicyService()
346 {
347     mAudioCommandThread->exit();
348     mOutputCommandThread->exit();
349 
350     mDestroyAudioPolicyManager(mAudioPolicyManager);
351     unloadAudioPolicyManager();
352 
353     delete mAudioPolicyClient;
354 
355     mNotificationClients.clear();
356     mAudioPolicyEffects.clear();
357 
358     mUidPolicy->unregisterSelf();
359     mSensorPrivacyPolicy->unregisterSelf();
360 
361     mUidPolicy.clear();
362     mSensorPrivacyPolicy.clear();
363 }
364 
365 // A notification client is always registered by AudioSystem when the client process
366 // connects to AudioPolicyService.
registerClient(const sp<media::IAudioPolicyServiceClient> & client)367 Status AudioPolicyService::registerClient(const sp<media::IAudioPolicyServiceClient>& client)
368 {
369     if (client == 0) {
370         ALOGW("%s got NULL client", __FUNCTION__);
371         return Status::ok();
372     }
373     audio_utils::lock_guard _l(mNotificationClientsMutex);
374 
375     uid_t uid = IPCThreadState::self()->getCallingUid();
376     pid_t pid = IPCThreadState::self()->getCallingPid();
377     int64_t token = ((int64_t)uid<<32) | pid;
378 
379     if (mNotificationClients.indexOfKey(token) < 0) {
380         sp<NotificationClient> notificationClient = new NotificationClient(this,
381                                                                            client,
382                                                                            uid,
383                                                                            pid);
384         ALOGV("registerClient() client %p, uid %d pid %d", client.get(), uid, pid);
385 
386         mNotificationClients.add(token, notificationClient);
387 
388         sp<IBinder> binder = IInterface::asBinder(client);
389         binder->linkToDeath(notificationClient);
390     }
391         return Status::ok();
392 }
393 
setAudioPortCallbacksEnabled(bool enabled)394 Status AudioPolicyService::setAudioPortCallbacksEnabled(bool enabled)
395 {
396     audio_utils::lock_guard _l(mNotificationClientsMutex);
397 
398     uid_t uid = IPCThreadState::self()->getCallingUid();
399     pid_t pid = IPCThreadState::self()->getCallingPid();
400     int64_t token = ((int64_t)uid<<32) | pid;
401 
402     if (mNotificationClients.indexOfKey(token) < 0) {
403         return Status::ok();
404     }
405     mNotificationClients.valueFor(token)->setAudioPortCallbacksEnabled(enabled);
406     return Status::ok();
407 }
408 
setAudioVolumeGroupCallbacksEnabled(bool enabled)409 Status AudioPolicyService::setAudioVolumeGroupCallbacksEnabled(bool enabled)
410 {
411     audio_utils::lock_guard _l(mNotificationClientsMutex);
412 
413     uid_t uid = IPCThreadState::self()->getCallingUid();
414     pid_t pid = IPCThreadState::self()->getCallingPid();
415     int64_t token = ((int64_t)uid<<32) | pid;
416 
417     if (mNotificationClients.indexOfKey(token) < 0) {
418         return Status::ok();
419     }
420     mNotificationClients.valueFor(token)->setAudioVolumeGroupCallbacksEnabled(enabled);
421     return Status::ok();
422 }
423 
424 // removeNotificationClient() is called when the client process dies.
removeNotificationClient(uid_t uid,pid_t pid)425 void AudioPolicyService::removeNotificationClient(uid_t uid, pid_t pid)
426 {
427     bool hasSameUid = false;
428     {
429         audio_utils::lock_guard _l(mNotificationClientsMutex);
430         int64_t token = ((int64_t)uid<<32) | pid;
431         mNotificationClients.removeItem(token);
432         for (size_t i = 0; i < mNotificationClients.size(); i++) {
433             if (mNotificationClients.valueAt(i)->uid() == uid) {
434                 hasSameUid = true;
435                 break;
436             }
437         }
438     }
439     {
440         audio_utils::lock_guard _l(mMutex);
441         if (mAudioPolicyManager && !hasSameUid) {
442             // called from binder death notification: no need to clear caller identity
443             mAudioPolicyManager->releaseResourcesForUid(uid);
444         }
445     }
446 }
447 
onAudioPortListUpdate()448 void AudioPolicyService::onAudioPortListUpdate()
449 {
450     mOutputCommandThread->updateAudioPortListCommand();
451 }
452 
doOnAudioPortListUpdate()453 void AudioPolicyService::doOnAudioPortListUpdate()
454 {
455     audio_utils::lock_guard _l(mNotificationClientsMutex);
456     for (size_t i = 0; i < mNotificationClients.size(); i++) {
457         mNotificationClients.valueAt(i)->onAudioPortListUpdate();
458     }
459 }
460 
onAudioPatchListUpdate()461 void AudioPolicyService::onAudioPatchListUpdate()
462 {
463     mOutputCommandThread->updateAudioPatchListCommand();
464 }
465 
doOnAudioPatchListUpdate()466 void AudioPolicyService::doOnAudioPatchListUpdate()
467 {
468     audio_utils::lock_guard _l(mNotificationClientsMutex);
469     for (size_t i = 0; i < mNotificationClients.size(); i++) {
470         mNotificationClients.valueAt(i)->onAudioPatchListUpdate();
471     }
472 }
473 
onAudioVolumeGroupChanged(volume_group_t group,int flags)474 void AudioPolicyService::onAudioVolumeGroupChanged(volume_group_t group, int flags)
475 {
476     mOutputCommandThread->changeAudioVolumeGroupCommand(group, flags);
477 }
478 
doOnAudioVolumeGroupChanged(volume_group_t group,int flags)479 void AudioPolicyService::doOnAudioVolumeGroupChanged(volume_group_t group, int flags)
480 {
481     audio_utils::lock_guard _l(mNotificationClientsMutex);
482     for (size_t i = 0; i < mNotificationClients.size(); i++) {
483         mNotificationClients.valueAt(i)->onAudioVolumeGroupChanged(group, flags);
484     }
485 }
486 
onDynamicPolicyMixStateUpdate(const String8 & regId,int32_t state)487 void AudioPolicyService::onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
488 {
489     ALOGV("AudioPolicyService::onDynamicPolicyMixStateUpdate(%s, %d)",
490             regId.c_str(), state);
491     mOutputCommandThread->dynamicPolicyMixStateUpdateCommand(regId, state);
492 }
493 
doOnDynamicPolicyMixStateUpdate(const String8 & regId,int32_t state)494 void AudioPolicyService::doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
495 {
496     audio_utils::lock_guard _l(mNotificationClientsMutex);
497     for (size_t i = 0; i < mNotificationClients.size(); i++) {
498         mNotificationClients.valueAt(i)->onDynamicPolicyMixStateUpdate(regId, state);
499     }
500 }
501 
onRecordingConfigurationUpdate(int event,const record_client_info_t * clientInfo,const audio_config_base_t * clientConfig,std::vector<effect_descriptor_t> clientEffects,const audio_config_base_t * deviceConfig,std::vector<effect_descriptor_t> effects,audio_patch_handle_t patchHandle,audio_source_t source)502 void AudioPolicyService::onRecordingConfigurationUpdate(
503                                                     int event,
504                                                     const record_client_info_t *clientInfo,
505                                                     const audio_config_base_t *clientConfig,
506                                                     std::vector<effect_descriptor_t> clientEffects,
507                                                     const audio_config_base_t *deviceConfig,
508                                                     std::vector<effect_descriptor_t> effects,
509                                                     audio_patch_handle_t patchHandle,
510                                                     audio_source_t source)
511 {
512     mOutputCommandThread->recordingConfigurationUpdateCommand(event, clientInfo,
513             clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
514 }
515 
doOnRecordingConfigurationUpdate(int event,const record_client_info_t * clientInfo,const audio_config_base_t * clientConfig,std::vector<effect_descriptor_t> clientEffects,const audio_config_base_t * deviceConfig,std::vector<effect_descriptor_t> effects,audio_patch_handle_t patchHandle,audio_source_t source)516 void AudioPolicyService::doOnRecordingConfigurationUpdate(
517                                                   int event,
518                                                   const record_client_info_t *clientInfo,
519                                                   const audio_config_base_t *clientConfig,
520                                                   std::vector<effect_descriptor_t> clientEffects,
521                                                   const audio_config_base_t *deviceConfig,
522                                                   std::vector<effect_descriptor_t> effects,
523                                                   audio_patch_handle_t patchHandle,
524                                                   audio_source_t source)
525 {
526     audio_utils::lock_guard _l(mNotificationClientsMutex);
527     for (size_t i = 0; i < mNotificationClients.size(); i++) {
528         mNotificationClients.valueAt(i)->onRecordingConfigurationUpdate(event, clientInfo,
529                 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
530     }
531 }
532 
onRoutingUpdated()533 void AudioPolicyService::onRoutingUpdated()
534 {
535     mOutputCommandThread->routingChangedCommand();
536 }
537 
doOnRoutingUpdated()538 void AudioPolicyService::doOnRoutingUpdated()
539 {
540   audio_utils::lock_guard _l(mNotificationClientsMutex);
541     for (size_t i = 0; i < mNotificationClients.size(); i++) {
542         mNotificationClients.valueAt(i)->onRoutingUpdated();
543     }
544 }
545 
onVolumeRangeInitRequest()546 void AudioPolicyService::onVolumeRangeInitRequest()
547 {
548     mOutputCommandThread->volRangeInitReqCommand();
549 }
550 
doOnVolumeRangeInitRequest()551 void AudioPolicyService::doOnVolumeRangeInitRequest()
552 {
553     audio_utils::lock_guard _l(mNotificationClientsMutex);
554     for (size_t i = 0; i < mNotificationClients.size(); i++) {
555         mNotificationClients.valueAt(i)->onVolumeRangeInitRequest();
556     }
557 }
558 
onCheckSpatializer()559 void AudioPolicyService::onCheckSpatializer()
560 {
561     audio_utils::lock_guard _l(mMutex);
562     onCheckSpatializer_l();
563 }
564 
onCheckSpatializer_l()565 void AudioPolicyService::onCheckSpatializer_l()
566 {
567     if (mSpatializer != nullptr) {
568         mOutputCommandThread->checkSpatializerCommand();
569     }
570 }
571 
doOnCheckSpatializer()572 void AudioPolicyService::doOnCheckSpatializer()
573 {
574     ALOGV("%s mSpatializer %p level %d",
575         __func__, mSpatializer.get(), (int)mSpatializer->getLevel());
576 
577     if (mSpatializer != nullptr) {
578         // Note: mSpatializer != nullptr =>  mAudioPolicyManager != nullptr
579         if (mSpatializer->getLevel() != Spatialization::Level::NONE) {
580             audio_io_handle_t currentOutput = mSpatializer->getOutput();
581             audio_io_handle_t newOutput;
582             const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
583             audio_config_base_t config = mSpatializer->getAudioInConfig();
584 
585             audio_utils::lock_guard _l(mMutex);
586             status_t status =
587                     mAudioPolicyManager->getSpatializerOutput(&config, &attr, &newOutput);
588             ALOGV("%s currentOutput %d newOutput %d channel_mask %#x",
589                     __func__, currentOutput, newOutput, config.channel_mask);
590             if (status == NO_ERROR && currentOutput == newOutput) {
591                 return;
592             }
593             size_t numActiveTracks = countActiveClientsOnOutput_l(newOutput);
594             mMutex.unlock();
595             // It is OK to call detachOutput() is none is already attached.
596             mSpatializer->detachOutput();
597             if (status == NO_ERROR && newOutput != AUDIO_IO_HANDLE_NONE) {
598                 status = mSpatializer->attachOutput(newOutput, numActiveTracks);
599             }
600             mMutex.lock();
601             if (status != NO_ERROR) {
602                 mAudioPolicyManager->releaseSpatializerOutput(newOutput);
603             }
604         } else if (mSpatializer->getLevel() == Spatialization::Level::NONE &&
605                    mSpatializer->getOutput() != AUDIO_IO_HANDLE_NONE) {
606             audio_io_handle_t output = mSpatializer->detachOutput();
607 
608             if (output != AUDIO_IO_HANDLE_NONE) {
609                 audio_utils::lock_guard _l(mMutex);
610                 mAudioPolicyManager->releaseSpatializerOutput(output);
611             }
612         }
613     }
614 }
615 
countActiveClientsOnOutput_l(audio_io_handle_t output,bool spatializedOnly)616 size_t AudioPolicyService::countActiveClientsOnOutput_l(
617         audio_io_handle_t output, bool spatializedOnly) {
618     size_t count = 0;
619     for (size_t i = 0; i < mAudioPlaybackClients.size(); i++) {
620         auto client = mAudioPlaybackClients.valueAt(i);
621         if (client->io == output && client->active
622                 && (!spatializedOnly || client->isSpatialized)) {
623             count++;
624         }
625     }
626     return count;
627 }
628 
onUpdateActiveSpatializerTracks_l()629 void AudioPolicyService::onUpdateActiveSpatializerTracks_l() {
630     if (mSpatializer == nullptr) {
631         return;
632     }
633     mOutputCommandThread->updateActiveSpatializerTracksCommand();
634 }
635 
doOnUpdateActiveSpatializerTracks()636 void AudioPolicyService::doOnUpdateActiveSpatializerTracks()
637 {
638     if (mSpatializer == nullptr) {
639         return;
640     }
641     audio_io_handle_t output = mSpatializer->getOutput();
642     size_t activeClients;
643     {
644         audio_utils::lock_guard _l(mMutex);
645         activeClients = countActiveClientsOnOutput_l(output);
646     }
647     mSpatializer->updateActiveTracks(activeClients);
648 }
649 
clientCreateAudioPatch(const struct audio_patch * patch,audio_patch_handle_t * handle,int delayMs)650 status_t AudioPolicyService::clientCreateAudioPatch(const struct audio_patch *patch,
651                                                 audio_patch_handle_t *handle,
652                                                 int delayMs)
653 {
654     return mAudioCommandThread->createAudioPatchCommand(patch, handle, delayMs);
655 }
656 
clientReleaseAudioPatch(audio_patch_handle_t handle,int delayMs)657 status_t AudioPolicyService::clientReleaseAudioPatch(audio_patch_handle_t handle,
658                                                  int delayMs)
659 {
660     return mAudioCommandThread->releaseAudioPatchCommand(handle, delayMs);
661 }
662 
clientSetAudioPortConfig(const struct audio_port_config * config,int delayMs)663 status_t AudioPolicyService::clientSetAudioPortConfig(const struct audio_port_config *config,
664                                                       int delayMs)
665 {
666     return mAudioCommandThread->setAudioPortConfigCommand(config, delayMs);
667 }
668 
NotificationClient(const sp<AudioPolicyService> & service,const sp<media::IAudioPolicyServiceClient> & client,uid_t uid,pid_t pid)669 AudioPolicyService::NotificationClient::NotificationClient(
670         const sp<AudioPolicyService>& service,
671         const sp<media::IAudioPolicyServiceClient>& client,
672         uid_t uid,
673         pid_t pid)
674     : mService(service), mUid(uid), mPid(pid), mAudioPolicyServiceClient(client),
675       mAudioPortCallbacksEnabled(false), mAudioVolumeGroupCallbacksEnabled(false)
676 {
677 }
678 
~NotificationClient()679 AudioPolicyService::NotificationClient::~NotificationClient()
680 {
681 }
682 
binderDied(const wp<IBinder> & who __unused)683 void AudioPolicyService::NotificationClient::binderDied(const wp<IBinder>& who __unused)
684 {
685     sp<NotificationClient> keep(this);
686     sp<AudioPolicyService> service = mService.promote();
687     if (service != 0) {
688         service->removeNotificationClient(mUid, mPid);
689     }
690 }
691 
onAudioPortListUpdate()692 void AudioPolicyService::NotificationClient::onAudioPortListUpdate()
693 {
694     if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
695         mAudioPolicyServiceClient->onAudioPortListUpdate();
696     }
697 }
698 
onAudioPatchListUpdate()699 void AudioPolicyService::NotificationClient::onAudioPatchListUpdate()
700 {
701     if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
702         mAudioPolicyServiceClient->onAudioPatchListUpdate();
703     }
704 }
705 
onAudioVolumeGroupChanged(volume_group_t group,int flags)706 void AudioPolicyService::NotificationClient::onAudioVolumeGroupChanged(volume_group_t group,
707                                                                       int flags)
708 {
709     if (mAudioPolicyServiceClient != 0 && mAudioVolumeGroupCallbacksEnabled) {
710         mAudioPolicyServiceClient->onAudioVolumeGroupChanged(group, flags);
711     }
712 }
713 
714 
onDynamicPolicyMixStateUpdate(const String8 & regId,int32_t state)715 void AudioPolicyService::NotificationClient::onDynamicPolicyMixStateUpdate(
716         const String8& regId, int32_t state)
717 {
718     if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
719         mAudioPolicyServiceClient->onDynamicPolicyMixStateUpdate(
720                 legacy2aidl_String8_string(regId).value(), state);
721     }
722 }
723 
onRecordingConfigurationUpdate(int event,const record_client_info_t * clientInfo,const audio_config_base_t * clientConfig,std::vector<effect_descriptor_t> clientEffects,const audio_config_base_t * deviceConfig,std::vector<effect_descriptor_t> effects,audio_patch_handle_t patchHandle,audio_source_t source)724 void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate(
725                                             int event,
726                                             const record_client_info_t *clientInfo,
727                                             const audio_config_base_t *clientConfig,
728                                             std::vector<effect_descriptor_t> clientEffects,
729                                             const audio_config_base_t *deviceConfig,
730                                             std::vector<effect_descriptor_t> effects,
731                                             audio_patch_handle_t patchHandle,
732                                             audio_source_t source)
733 {
734     if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
735         status_t status = [&]() -> status_t {
736             int32_t eventAidl = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(event));
737             media::RecordClientInfo clientInfoAidl = VALUE_OR_RETURN_STATUS(
738                     legacy2aidl_record_client_info_t_RecordClientInfo(*clientInfo));
739             AudioConfigBase clientConfigAidl = VALUE_OR_RETURN_STATUS(
740                     legacy2aidl_audio_config_base_t_AudioConfigBase(
741                             *clientConfig, true /*isInput*/));
742             std::vector<media::EffectDescriptor> clientEffectsAidl = VALUE_OR_RETURN_STATUS(
743                     convertContainer<std::vector<media::EffectDescriptor>>(
744                             clientEffects,
745                             legacy2aidl_effect_descriptor_t_EffectDescriptor));
746             AudioConfigBase deviceConfigAidl = VALUE_OR_RETURN_STATUS(
747                     legacy2aidl_audio_config_base_t_AudioConfigBase(
748                             *deviceConfig, true /*isInput*/));
749             std::vector<media::EffectDescriptor> effectsAidl = VALUE_OR_RETURN_STATUS(
750                     convertContainer<std::vector<media::EffectDescriptor>>(
751                             effects,
752                             legacy2aidl_effect_descriptor_t_EffectDescriptor));
753             int32_t patchHandleAidl = VALUE_OR_RETURN_STATUS(
754                     legacy2aidl_audio_patch_handle_t_int32_t(patchHandle));
755             media::audio::common::AudioSource sourceAidl = VALUE_OR_RETURN_STATUS(
756                     legacy2aidl_audio_source_t_AudioSource(source));
757             return aidl_utils::statusTFromBinderStatus(
758                     mAudioPolicyServiceClient->onRecordingConfigurationUpdate(eventAidl,
759                                                                               clientInfoAidl,
760                                                                               clientConfigAidl,
761                                                                               clientEffectsAidl,
762                                                                               deviceConfigAidl,
763                                                                               effectsAidl,
764                                                                               patchHandleAidl,
765                                                                               sourceAidl));
766         }();
767         ALOGW_IF(status != OK, "onRecordingConfigurationUpdate() failed: %d", status);
768     }
769 }
770 
setAudioPortCallbacksEnabled(bool enabled)771 void AudioPolicyService::NotificationClient::setAudioPortCallbacksEnabled(bool enabled)
772 {
773     mAudioPortCallbacksEnabled = enabled;
774 }
775 
setAudioVolumeGroupCallbacksEnabled(bool enabled)776 void AudioPolicyService::NotificationClient::setAudioVolumeGroupCallbacksEnabled(bool enabled)
777 {
778     mAudioVolumeGroupCallbacksEnabled = enabled;
779 }
780 
onRoutingUpdated()781 void AudioPolicyService::NotificationClient::onRoutingUpdated()
782 {
783     if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
784         mAudioPolicyServiceClient->onRoutingUpdated();
785     }
786 }
787 
onVolumeRangeInitRequest()788 void AudioPolicyService::NotificationClient::onVolumeRangeInitRequest()
789 {
790     if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
791         mAudioPolicyServiceClient->onVolumeRangeInitRequest();
792     }
793 }
794 
binderDied(const wp<IBinder> & who)795 void AudioPolicyService::binderDied(const wp<IBinder>& who) {
796     ALOGW("binderDied() %p, calling pid %d", who.unsafe_get(),
797             IPCThreadState::self()->getCallingPid());
798 }
799 
dumpReleaseLock(audio_utils::mutex & mutex,bool locked)800 static void dumpReleaseLock(audio_utils::mutex& mutex, bool locked)
801         RELEASE(mutex) NO_THREAD_SAFETY_ANALYSIS
802 {
803     if (locked) mutex.unlock();
804 }
805 
dumpInternals(int fd)806 status_t AudioPolicyService::dumpInternals(int fd)
807 {
808     const size_t SIZE = 256;
809     char buffer[SIZE];
810     String8 result;
811 
812     snprintf(buffer, SIZE, "Supported System Usages:\n  ");
813     result.append(buffer);
814     std::stringstream msg;
815     size_t i = 0;
816     for (auto usage : mSupportedSystemUsages) {
817         if (i++ != 0) msg << ", ";
818         if (const char* strUsage = audio_usage_to_string(usage); strUsage) {
819             msg << strUsage;
820         } else {
821             msg << usage << " (unknown)";
822         }
823     }
824     if (i == 0) {
825         msg << "None";
826     }
827     msg << std::endl;
828     result.append(msg.str().c_str());
829 
830     write(fd, result.c_str(), result.size());
831 
832     mUidPolicy->dumpInternals(fd);
833     return NO_ERROR;
834 }
835 
updateUidStates()836 void AudioPolicyService::updateUidStates()
837 {
838     audio_utils::lock_guard _l(mMutex);
839     updateUidStates_l();
840 }
841 
updateUidStates_l()842 void AudioPolicyService::updateUidStates_l()
843 {
844 //    Go over all active clients and allow capture (does not force silence) in the
845 //    following cases:
846 //    The client is in the active assistant list
847 //         AND is TOP
848 //               AND an accessibility service is TOP
849 //                  AND source is either VOICE_RECOGNITION OR HOTWORD
850 //               OR there is no active privacy sensitive capture or call
851 //                          OR client has CAPTURE_AUDIO_OUTPUT privileged permission
852 //                  AND source is VOICE_RECOGNITION OR HOTWORD
853 //    The client is an assistant AND active assistant is not being used
854 //        AND an accessibility service is on TOP or a RTT call is active
855 //                AND the source is VOICE_RECOGNITION or HOTWORD
856 //        OR there is no active privacy sensitive capture or call
857 //                OR client has CAPTURE_AUDIO_OUTPUT privileged permission
858 //            AND is TOP most recent assistant and uses VOICE_RECOGNITION or HOTWORD
859 //                OR there is no top recent assistant and source is HOTWORD
860 //    OR The client is an accessibility service
861 //        AND Is on TOP
862 //                AND the source is VOICE_RECOGNITION or HOTWORD
863 //            OR The assistant is not on TOP
864 //                AND there is no active privacy sensitive capture or call
865 //                    OR client has CAPTURE_AUDIO_OUTPUT privileged permission
866 //        AND is on TOP
867 //        AND the source is VOICE_RECOGNITION or HOTWORD
868 //    OR the client source is virtual (remote submix, call audio TX or RX...)
869 //    OR the client source is HOTWORD
870 //        AND is on TOP
871 //            OR all active clients are using HOTWORD source
872 //        AND no call is active
873 //            OR client has CAPTURE_AUDIO_OUTPUT privileged permission
874 //    OR the client is the current InputMethodService
875 //        AND a RTT call is active AND the source is VOICE_RECOGNITION
876 //    OR The client is an active communication owner
877 //        AND is on TOP or latest started
878 //    OR Any client
879 //        AND The assistant is not on TOP
880 //        AND is on TOP or latest started
881 //        AND there is no active privacy sensitive capture or call
882 //            OR client has CAPTURE_AUDIO_OUTPUT privileged permission
883 
884 
885     sp<AudioRecordClient> topActive;
886     sp<AudioRecordClient> latestActive;
887     sp<AudioRecordClient> topSensitiveActive;
888     sp<AudioRecordClient> latestSensitiveActiveOrComm;
889     sp<AudioRecordClient> latestActiveAssistant;
890 
891     nsecs_t topStartNs = 0;
892     nsecs_t latestStartNs = 0;
893     nsecs_t topSensitiveStartNs = 0;
894     nsecs_t latestSensitiveStartNs = 0;
895     nsecs_t latestAssistantStartNs = 0;
896     bool isA11yOnTop = mUidPolicy->isA11yOnTop();
897     bool isAssistantOnTop = false;
898     bool useActiveAssistantList = false;
899     bool isSensitiveActive = false;
900     bool isInCall = mPhoneState == AUDIO_MODE_IN_CALL;
901     bool isInCommunication = mPhoneState == AUDIO_MODE_IN_COMMUNICATION;
902     bool rttCallActive = (isInCall || isInCommunication)
903             && mUidPolicy->isRttEnabled();
904     bool onlyHotwordActive = true;
905     bool isPhoneStateOwnerActive = false;
906 
907     // if Sensor Privacy is enabled then all recordings should be silenced.
908     if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
909         silenceAllRecordings_l();
910         return;
911     }
912 
913     for (size_t i =0; i < mAudioRecordClients.size(); i++) {
914         sp<AudioRecordClient> current = mAudioRecordClients[i];
915         uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
916                 current->attributionSource.uid));
917         if (!current->active) {
918             continue;
919         }
920 
921         app_state_t appState = apmStatFromAmState(mUidPolicy->getUidState(currentUid));
922         // clients which app is in IDLE state are not eligible for top active or
923         // latest active
924         if (appState == APP_STATE_IDLE) {
925             continue;
926         }
927 
928         bool isAccessibility = mUidPolicy->isA11yUid(currentUid);
929         // Clients capturing for Accessibility services or virtual sources are not considered
930         // for top or latest active to avoid masking regular clients started before
931         if (!isAccessibility && !isVirtualSource(current->attributes.source)) {
932             bool isAssistant = mUidPolicy->isAssistantUid(currentUid);
933             bool isActiveAssistant = mUidPolicy->isActiveAssistantUid(currentUid);
934             bool isPrivacySensitive =
935                     (current->attributes.flags & AUDIO_FLAG_CAPTURE_PRIVATE) != 0;
936 
937             if (appState == APP_STATE_TOP) {
938                 if (isPrivacySensitive) {
939                     if (current->startTimeNs > topSensitiveStartNs) {
940                         topSensitiveActive = current;
941                         topSensitiveStartNs = current->startTimeNs;
942                     }
943                 } else {
944                     if (current->startTimeNs > topStartNs) {
945                         topActive = current;
946                         topStartNs = current->startTimeNs;
947                     }
948                 }
949                 if (isAssistant) {
950                     isAssistantOnTop = true;
951                     if (isActiveAssistant) {
952                         useActiveAssistantList = true;
953                     } else if (!useActiveAssistantList) {
954                         if (current->startTimeNs > latestAssistantStartNs) {
955                             latestActiveAssistant = current;
956                             latestAssistantStartNs = current->startTimeNs;
957                         }
958                     }
959                 }
960             }
961             // Clients capturing for HOTWORD are not considered
962             // for latest active to avoid masking regular clients started before
963             if (!(current->attributes.source == AUDIO_SOURCE_HOTWORD
964                     || ((isA11yOnTop || rttCallActive) && isAssistant))) {
965                 if (isPrivacySensitive) {
966                     // if audio mode is IN_COMMUNICATION, make sure the audio mode owner
967                     // is marked latest sensitive active even if another app qualifies.
968                     if (current->startTimeNs > latestSensitiveStartNs
969                             || (isInCommunication && currentUid == mPhoneStateOwnerUid)) {
970                         if (!isInCommunication || latestSensitiveActiveOrComm == nullptr
971                                 || VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
972                                     latestSensitiveActiveOrComm->attributionSource.uid))
973                                         != mPhoneStateOwnerUid) {
974                             latestSensitiveActiveOrComm = current;
975                             latestSensitiveStartNs = current->startTimeNs;
976                         }
977                     }
978                     isSensitiveActive = true;
979                 } else {
980                     if (current->startTimeNs > latestStartNs) {
981                         latestActive = current;
982                         latestStartNs = current->startTimeNs;
983                     }
984                 }
985             }
986         }
987         if (current->attributes.source != AUDIO_SOURCE_HOTWORD &&
988                 !isVirtualSource(current->attributes.source)) {
989             onlyHotwordActive = false;
990         }
991         if (currentUid == mPhoneStateOwnerUid &&
992                 !isVirtualSource(current->attributes.source)) {
993             isPhoneStateOwnerActive = true;
994         }
995     }
996 
997     // if no active client with UI on Top, consider latest active as top
998     if (topActive == nullptr) {
999         topActive = latestActive;
1000         topStartNs = latestStartNs;
1001     }
1002     if (topSensitiveActive == nullptr) {
1003         topSensitiveActive = latestSensitiveActiveOrComm;
1004         topSensitiveStartNs = latestSensitiveStartNs;
1005     } else if (latestSensitiveActiveOrComm != nullptr) {
1006         // if audio mode is IN_COMMUNICATION, favor audio mode owner over an app with
1007         // foreground UI in case both are capturing with privacy sensitive flag.
1008         uid_t latestActiveUid = VALUE_OR_FATAL(
1009             aidl2legacy_int32_t_uid_t(latestSensitiveActiveOrComm->attributionSource.uid));
1010         if (isInCommunication && latestActiveUid == mPhoneStateOwnerUid) {
1011             topSensitiveActive = latestSensitiveActiveOrComm;
1012             topSensitiveStartNs = latestSensitiveStartNs;
1013         }
1014     }
1015 
1016     // If both privacy sensitive and regular capture are active:
1017     //  if the regular capture is privileged
1018     //    allow concurrency
1019     //  else
1020     //    favor the privacy sensitive case
1021     if (topActive != nullptr && topSensitiveActive != nullptr
1022             && !topActive->canCaptureOutput) {
1023         topActive = nullptr;
1024     }
1025 
1026     for (size_t i =0; i < mAudioRecordClients.size(); i++) {
1027         sp<AudioRecordClient> current = mAudioRecordClients[i];
1028         uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
1029             current->attributionSource.uid));
1030         if (!current->active) {
1031             continue;
1032         }
1033 
1034         audio_source_t source = current->attributes.source;
1035         bool isTopOrLatestActive = topActive == nullptr ? false :
1036             current->attributionSource.uid == topActive->attributionSource.uid;
1037         bool isTopOrLatestSensitive = topSensitiveActive == nullptr ? false :
1038             current->attributionSource.uid == topSensitiveActive->attributionSource.uid;
1039         bool isTopOrLatestAssistant = latestActiveAssistant == nullptr ? false :
1040             current->attributionSource.uid == latestActiveAssistant->attributionSource.uid;
1041 
1042         // TODO: b/339112720
1043         // Refine this logic when we have the correct phone state owner UID. The current issue is
1044         // when a VOIP APP use Telecom API to manage calls, the mPhoneStateOwnerUid is AID_SYSTEM
1045         // instead of the actual VOIP APP UID, so isPhoneStateOwnerActive here is not accurate.
1046         const bool canCaptureIfInCallOrCommunication = [&](const auto& recordClient) REQUIRES(
1047                                                                mMutex) {
1048             uid_t recordUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
1049                 recordClient->attributionSource.uid));
1050             bool canCaptureCall = recordClient->canCaptureOutput;
1051             bool canCaptureCommunication = recordClient->canCaptureOutput
1052                 || !isPhoneStateOwnerActive
1053                 || recordUid == mPhoneStateOwnerUid;
1054             return !(isInCall && !canCaptureCall)
1055                 && !(isInCommunication && !canCaptureCommunication);
1056         }(current);
1057 
1058         // By default allow capture if:
1059         //     The assistant is not on TOP
1060         //         AND is on TOP or latest started
1061         //         AND there is no active privacy sensitive capture or call
1062         //             OR client has CAPTURE_AUDIO_OUTPUT privileged permission
1063         //     The assistant is on TOP
1064         //         AND is ongoing communication owner
1065         //         AND is on TOP or latest started
1066         const bool allowSensitiveCapture =
1067             !isSensitiveActive || isTopOrLatestSensitive || current->canCaptureOutput;
1068         bool allowCapture = false;
1069         if (!isAssistantOnTop) {
1070             allowCapture = (isTopOrLatestActive || isTopOrLatestSensitive) &&
1071                            allowSensitiveCapture && canCaptureIfInCallOrCommunication;
1072         } else {
1073             allowCapture = isInCommunication && isTopOrLatestSensitive &&
1074                            canCaptureIfInCallOrCommunication;
1075         }
1076 
1077         if (!current->hasOp()) {
1078             // Never allow capture if app op is denied
1079             allowCapture = false;
1080         } else if (isVirtualSource(source)) {
1081             // Allow capture for virtual (remote submix, call audio TX or RX...) sources
1082             allowCapture = true;
1083         } else if (!useActiveAssistantList && mUidPolicy->isAssistantUid(currentUid)) {
1084             // For assistant allow capture if:
1085             //     Active assistant list is not being used
1086             //     AND accessibility service is on TOP or a RTT call is active
1087             //            AND the source is VOICE_RECOGNITION or HOTWORD
1088             //     OR there is no active privacy sensitive capture or call
1089             //          OR client has CAPTURE_AUDIO_OUTPUT privileged permission
1090             //            AND is latest TOP assistant AND
1091             //               uses VOICE_RECOGNITION OR uses HOTWORD
1092             //            OR there is no TOP assistant and uses HOTWORD
1093             if (isA11yOnTop || rttCallActive) {
1094                 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
1095                     allowCapture = true;
1096                 }
1097             } else if (allowSensitiveCapture
1098                     && canCaptureIfInCallOrCommunication) {
1099                 if (isTopOrLatestAssistant
1100                     && (source == AUDIO_SOURCE_VOICE_RECOGNITION
1101                         || source == AUDIO_SOURCE_HOTWORD)) {
1102                         allowCapture = true;
1103                 } else if (!isAssistantOnTop && (source == AUDIO_SOURCE_HOTWORD)) {
1104                     allowCapture = true;
1105                 }
1106             }
1107         } else if (useActiveAssistantList && mUidPolicy->isActiveAssistantUid(currentUid)) {
1108             // For assistant on active list and on top allow capture if:
1109             //     An accessibility service is on TOP
1110             //         AND the source is VOICE_RECOGNITION or HOTWORD
1111             //     OR there is no active privacy sensitive capture or call
1112             //             OR client has CAPTURE_AUDIO_OUTPUT privileged permission
1113             //         AND uses VOICE_RECOGNITION OR uses HOTWORD
1114             if (isA11yOnTop) {
1115                 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
1116                     allowCapture = true;
1117                 }
1118             } else if (allowSensitiveCapture
1119                         && canCaptureIfInCallOrCommunication) {
1120                 if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) || (source == AUDIO_SOURCE_HOTWORD))
1121                 {
1122                     allowCapture = true;
1123                 }
1124             }
1125         } else if (mUidPolicy->isA11yUid(currentUid)) {
1126             // For accessibility service allow capture if:
1127             //     The assistant is not on TOP
1128             //         AND there is no active privacy sensitive capture or call
1129             //             OR client has CAPTURE_AUDIO_OUTPUT privileged permission
1130             //     OR
1131             //         Is on TOP AND the source is VOICE_RECOGNITION or HOTWORD
1132             if (!isAssistantOnTop
1133                     && allowSensitiveCapture
1134                     && canCaptureIfInCallOrCommunication) {
1135                 allowCapture = true;
1136             }
1137             if (isA11yOnTop) {
1138                 if (source == AUDIO_SOURCE_VOICE_RECOGNITION || source == AUDIO_SOURCE_HOTWORD) {
1139                     allowCapture = true;
1140                 }
1141             }
1142         } else if (source == AUDIO_SOURCE_HOTWORD) {
1143             // For HOTWORD source allow capture when not on TOP if:
1144             //     All active clients are using HOTWORD source
1145             //     AND no call is active
1146             //         OR client has CAPTURE_AUDIO_OUTPUT privileged permission
1147             if (onlyHotwordActive
1148                     && canCaptureIfInCallOrCommunication) {
1149                 allowCapture = true;
1150             }
1151         } else if (mUidPolicy->isCurrentImeUid(currentUid)) {
1152             // For current InputMethodService allow capture if:
1153             //     A RTT call is active AND the source is VOICE_RECOGNITION
1154             if (rttCallActive && source == AUDIO_SOURCE_VOICE_RECOGNITION) {
1155                 allowCapture = true;
1156             }
1157         }
1158         setAppState_l(current,
1159                       allowCapture ? apmStatFromAmState(mUidPolicy->getUidState(currentUid)) :
1160                                 APP_STATE_IDLE);
1161     }
1162 }
1163 
silenceAllRecordings_l()1164 void AudioPolicyService::silenceAllRecordings_l() {
1165     for (size_t i = 0; i < mAudioRecordClients.size(); i++) {
1166         sp<AudioRecordClient> current = mAudioRecordClients[i];
1167         if (!isVirtualSource(current->attributes.source)) {
1168             setAppState_l(current, APP_STATE_IDLE);
1169         }
1170     }
1171 }
1172 
1173 /* static */
apmStatFromAmState(int amState)1174 app_state_t AudioPolicyService::apmStatFromAmState(int amState) {
1175 
1176     if (amState == ActivityManager::PROCESS_STATE_UNKNOWN) {
1177         return APP_STATE_IDLE;
1178     } else if (amState <= ActivityManager::PROCESS_STATE_TOP) {
1179       // include persistent services
1180       return APP_STATE_TOP;
1181     }
1182     return APP_STATE_FOREGROUND;
1183 }
1184 
1185 /* static */
isVirtualSource(audio_source_t source)1186 bool AudioPolicyService::isVirtualSource(audio_source_t source)
1187 {
1188     switch (source) {
1189         case AUDIO_SOURCE_VOICE_UPLINK:
1190         case AUDIO_SOURCE_VOICE_DOWNLINK:
1191         case AUDIO_SOURCE_VOICE_CALL:
1192         case AUDIO_SOURCE_REMOTE_SUBMIX:
1193         case AUDIO_SOURCE_FM_TUNER:
1194         case AUDIO_SOURCE_ECHO_REFERENCE:
1195             return true;
1196         default:
1197             break;
1198     }
1199     return false;
1200 }
1201 
setAppState_l(sp<AudioRecordClient> client,app_state_t state)1202 void AudioPolicyService::setAppState_l(sp<AudioRecordClient> client, app_state_t state)
1203 {
1204     AutoCallerClear acc;
1205 
1206     if (mAudioPolicyManager) {
1207         mAudioPolicyManager->setAppState(client->portId, state);
1208     }
1209     sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1210     if (af) {
1211         bool silenced = state == APP_STATE_IDLE;
1212         if (client->silenced != silenced) {
1213             if (client->active) {
1214                 if (silenced) {
1215                     finishRecording(client->attributionSource, client->virtualDeviceId,
1216                                     client->attributes.source);
1217                 } else {
1218                     std::stringstream msg;
1219                     msg << "Audio recording un-silenced on session " << client->session;
1220                     if (!startRecording(client->attributionSource, client->virtualDeviceId,
1221                                         String16(msg.str().c_str()), client->attributes.source)) {
1222                         silenced = true;
1223                     }
1224                 }
1225             }
1226             af->setRecordSilenced(client->portId, silenced);
1227             client->silenced = silenced;
1228         }
1229     }
1230 }
1231 
dump(int fd,const Vector<String16> & args __unused)1232 status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
1233 NO_THREAD_SAFETY_ANALYSIS  // update for trylock.
1234 {
1235     if (!dumpAllowed()) {
1236         dumpPermissionDenial(fd);
1237     } else {
1238         const bool locked = mMutex.try_lock(kDumpLockTimeoutNs);
1239         if (!locked) {
1240             String8 result(kDeadlockedString);
1241             write(fd, result.c_str(), result.size());
1242         }
1243 
1244         dumpInternals(fd);
1245 
1246         String8 actPtr = String8::format("AudioCommandThread: %p\n", mAudioCommandThread.get());
1247         write(fd, actPtr.c_str(), actPtr.size());
1248         if (mAudioCommandThread != 0) {
1249             mAudioCommandThread->dump(fd);
1250         }
1251 
1252         String8 octPtr = String8::format("OutputCommandThread: %p\n", mOutputCommandThread.get());
1253         write(fd, octPtr.c_str(), octPtr.size());
1254         if (mOutputCommandThread != 0) {
1255             mOutputCommandThread->dump(fd);
1256         }
1257 
1258         if (mAudioPolicyManager) {
1259             mAudioPolicyManager->dump(fd);
1260         } else {
1261             String8 apmPtr = String8::format("AudioPolicyManager: %p\n", mAudioPolicyManager);
1262             write(fd, apmPtr.c_str(), apmPtr.size());
1263         }
1264 
1265         mPackageManager.dump(fd);
1266 
1267         dumpReleaseLock(mMutex, locked);
1268 
1269         if (mSpatializer != nullptr) {
1270             std::string dumpString = mSpatializer->toString(1 /* level */);
1271             write(fd, dumpString.c_str(), dumpString.size());
1272         } else {
1273             String8 spatializerPtr = String8::format("Spatializer no supportted on this device\n");
1274             write(fd, spatializerPtr.c_str(), spatializerPtr.size());
1275         }
1276 
1277         {
1278             std::string timeCheckStats = getIAudioPolicyServiceStatistics().dump();
1279             dprintf(fd, "\nIAudioPolicyService binder call profile\n");
1280             write(fd, timeCheckStats.c_str(), timeCheckStats.size());
1281         }
1282     }
1283     return NO_ERROR;
1284 }
1285 
dumpPermissionDenial(int fd)1286 status_t AudioPolicyService::dumpPermissionDenial(int fd)
1287 {
1288     const size_t SIZE = 256;
1289     char buffer[SIZE];
1290     String8 result;
1291     snprintf(buffer, SIZE, "Permission Denial: "
1292             "can't dump AudioPolicyService from pid=%d, uid=%d\n",
1293             IPCThreadState::self()->getCallingPid(),
1294             IPCThreadState::self()->getCallingUid());
1295     result.append(buffer);
1296     write(fd, result.c_str(), result.size());
1297     return NO_ERROR;
1298 }
1299 
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)1300 status_t AudioPolicyService::onTransact(
1301         uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
1302     // make sure transactions reserved to AudioFlinger do not come from other processes
1303     switch (code) {
1304         case TRANSACTION_startOutput:
1305         case TRANSACTION_stopOutput:
1306         case TRANSACTION_releaseOutput:
1307         case TRANSACTION_getInputForAttr:
1308         case TRANSACTION_startInput:
1309         case TRANSACTION_stopInput:
1310         case TRANSACTION_releaseInput:
1311         case TRANSACTION_getOutputForEffect:
1312         case TRANSACTION_registerEffect:
1313         case TRANSACTION_unregisterEffect:
1314         case TRANSACTION_setEffectEnabled:
1315         case TRANSACTION_getStrategyForStream:
1316         case TRANSACTION_getOutputForAttr:
1317         case TRANSACTION_moveEffectsToIo:
1318             ALOGW("%s: transaction %d received from PID %d",
1319                   __func__, code, IPCThreadState::self()->getCallingPid());
1320             return INVALID_OPERATION;
1321         default:
1322             break;
1323     }
1324 
1325     // make sure the following transactions come from system components
1326     switch (code) {
1327         case TRANSACTION_setDeviceConnectionState:
1328         case TRANSACTION_handleDeviceConfigChange:
1329         case TRANSACTION_setPhoneState:
1330 //FIXME: Allow setForceUse calls from system apps until a better use case routing API is available
1331 //      case TRANSACTION_setForceUse:
1332         case TRANSACTION_setDeviceAbsoluteVolumeEnabled:
1333         case TRANSACTION_initStreamVolume:
1334         case TRANSACTION_setStreamVolumeIndex:
1335         case TRANSACTION_setVolumeIndexForAttributes:
1336         case TRANSACTION_getStreamVolumeIndex:
1337         case TRANSACTION_getVolumeIndexForAttributes:
1338         case TRANSACTION_getMinVolumeIndexForAttributes:
1339         case TRANSACTION_getMaxVolumeIndexForAttributes:
1340         case TRANSACTION_isStreamActive:
1341         case TRANSACTION_isStreamActiveRemotely:
1342         case TRANSACTION_isSourceActive:
1343         case TRANSACTION_registerPolicyMixes:
1344         case TRANSACTION_updatePolicyMixes:
1345         case TRANSACTION_setMasterMono:
1346         case TRANSACTION_getSurroundFormats:
1347         case TRANSACTION_getReportedSurroundFormats:
1348         case TRANSACTION_setSurroundFormatEnabled:
1349         case TRANSACTION_setAssistantServicesUids:
1350         case TRANSACTION_setActiveAssistantServicesUids:
1351         case TRANSACTION_setA11yServicesUids:
1352         case TRANSACTION_setUidDeviceAffinities:
1353         case TRANSACTION_removeUidDeviceAffinities:
1354         case TRANSACTION_setUserIdDeviceAffinities:
1355         case TRANSACTION_removeUserIdDeviceAffinities:
1356         case TRANSACTION_getHwOffloadFormatsSupportedForBluetoothMedia:
1357         case TRANSACTION_listAudioVolumeGroups:
1358         case TRANSACTION_getVolumeGroupFromAudioAttributes:
1359         case TRANSACTION_acquireSoundTriggerSession:
1360         case TRANSACTION_releaseSoundTriggerSession:
1361         case TRANSACTION_isHotwordStreamSupported:
1362         case TRANSACTION_setRttEnabled:
1363         case TRANSACTION_isCallScreenModeSupported:
1364         case TRANSACTION_setDevicesRoleForStrategy:
1365         case TRANSACTION_setSupportedSystemUsages:
1366         case TRANSACTION_removeDevicesRoleForStrategy:
1367         case TRANSACTION_clearDevicesRoleForStrategy:
1368         case TRANSACTION_getDevicesForRoleAndStrategy:
1369         case TRANSACTION_getDevicesForAttributes:
1370         case TRANSACTION_setAllowedCapturePolicy:
1371         case TRANSACTION_onNewAudioModulesAvailable:
1372         case TRANSACTION_setCurrentImeUid:
1373         case TRANSACTION_registerSoundTriggerCaptureStateListener:
1374         case TRANSACTION_setDevicesRoleForCapturePreset:
1375         case TRANSACTION_addDevicesRoleForCapturePreset:
1376         case TRANSACTION_removeDevicesRoleForCapturePreset:
1377         case TRANSACTION_clearDevicesRoleForCapturePreset:
1378         case TRANSACTION_getDevicesForRoleAndCapturePreset:
1379         case TRANSACTION_getSpatializer:
1380         case TRANSACTION_setPreferredMixerAttributes:
1381         case TRANSACTION_clearPreferredMixerAttributes:
1382         case TRANSACTION_getRegisteredPolicyMixes: {
1383             if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
1384                 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
1385                       __func__, code, IPCThreadState::self()->getCallingPid(),
1386                       IPCThreadState::self()->getCallingUid());
1387                 return INVALID_OPERATION;
1388             }
1389         } break;
1390         default:
1391             break;
1392     }
1393 
1394     switch (code) {
1395         case TRANSACTION_getPermissionController: {
1396             if (!isAudioServerOrSystemServerUid(IPCThreadState::self()->getCallingUid())) {
1397                 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
1398                       __func__, code, IPCThreadState::self()->getCallingPid(),
1399                       IPCThreadState::self()->getCallingUid());
1400                 return INVALID_OPERATION;
1401             }
1402         }
1403     }
1404 
1405     const std::string methodName = getIAudioPolicyServiceStatistics().getMethodForCode(code);
1406     mediautils::TimeCheck check(
1407             std::string("IAudioPolicyService::").append(methodName),
1408             [code, methodName](bool timeout, float elapsedMs) { // don't move methodName.
1409         if (timeout) {
1410             mediametrics::LogItem(AMEDIAMETRICS_KEY_AUDIO_POLICY)
1411                 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_TIMEOUT)
1412                 .set(AMEDIAMETRICS_PROP_METHODCODE, int64_t(code))
1413                 .set(AMEDIAMETRICS_PROP_METHODNAME, methodName.c_str())
1414                 .record();
1415         } else {
1416             getIAudioPolicyServiceStatistics().event(code, elapsedMs);
1417         }
1418     }, mediautils::TimeCheck::kDefaultTimeoutDuration,
1419     mediautils::TimeCheck::kDefaultSecondChanceDuration,
1420     true /* crashOnTimeout */);
1421 
1422     switch (code) {
1423         case SHELL_COMMAND_TRANSACTION: {
1424             int in = data.readFileDescriptor();
1425             int out = data.readFileDescriptor();
1426             int err = data.readFileDescriptor();
1427             int argc = data.readInt32();
1428             Vector<String16> args;
1429             for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
1430                args.add(data.readString16());
1431             }
1432             sp<IBinder> unusedCallback;
1433             sp<IResultReceiver> resultReceiver;
1434             status_t status;
1435             if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
1436                 return status;
1437             }
1438             if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
1439                 return status;
1440             }
1441             status = shellCommand(in, out, err, args);
1442             if (resultReceiver != nullptr) {
1443                 resultReceiver->send(status);
1444             }
1445             return NO_ERROR;
1446         }
1447     }
1448 
1449     return BnAudioPolicyService::onTransact(code, data, reply, flags);
1450 }
1451 
1452 // ------------------- Shell command implementation -------------------
1453 
1454 // NOTE: This is a remote API - make sure all args are validated
shellCommand(int in,int out,int err,Vector<String16> & args)1455 status_t AudioPolicyService::shellCommand(int in, int out, int err, Vector<String16>& args) {
1456     if (!checkCallingPermission(sManageAudioPolicyPermission, nullptr, nullptr)) {
1457         return PERMISSION_DENIED;
1458     }
1459     if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
1460         return BAD_VALUE;
1461     }
1462     if (args.size() >= 1 && args[0] == String16("purge_permission-cache")) {
1463         purgePermissionCache();
1464         return NO_ERROR;
1465     }
1466     return BAD_VALUE;
1467 }
1468 
registerOutput(audio_io_handle_t output,const audio_config_base_t & config,const audio_output_flags_t flags)1469 status_t AudioPolicyService::registerOutput(audio_io_handle_t output,
1470                         const audio_config_base_t& config,
1471                         const audio_output_flags_t flags) {
1472     return mUsecaseValidator->registerStream(output, config, flags);
1473 }
1474 
unregisterOutput(audio_io_handle_t output)1475 status_t AudioPolicyService::unregisterOutput(audio_io_handle_t output) {
1476     return mUsecaseValidator->unregisterStream(output);
1477 }
1478 
1479 // -----------  AudioPolicyService::UidPolicy implementation ----------
1480 
registerSelf()1481 void AudioPolicyService::UidPolicy::registerSelf() {
1482     status_t res = mAm.linkToDeath(this);
1483     mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
1484             | ActivityManager::UID_OBSERVER_IDLE
1485             | ActivityManager::UID_OBSERVER_ACTIVE
1486             | ActivityManager::UID_OBSERVER_PROCSTATE,
1487             ActivityManager::PROCESS_STATE_UNKNOWN,
1488             String16("audioserver"));
1489     if (!res) {
1490         audio_utils::lock_guard _l(mMutex);
1491         mObserverRegistered = true;
1492     } else {
1493         ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
1494 
1495         mAm.unregisterUidObserver(this);
1496     }
1497 }
1498 
unregisterSelf()1499 void AudioPolicyService::UidPolicy::unregisterSelf() {
1500     mAm.unlinkToDeath(this);
1501     mAm.unregisterUidObserver(this);
1502     audio_utils::lock_guard _l(mMutex);
1503     mObserverRegistered = false;
1504 }
1505 
binderDied(__unused const wp<IBinder> & who)1506 void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
1507     audio_utils::lock_guard _l(mMutex);
1508     mCachedUids.clear();
1509     mObserverRegistered = false;
1510 }
1511 
checkRegistered()1512 void AudioPolicyService::UidPolicy::checkRegistered() {
1513     bool needToReregister = false;
1514     {
1515         audio_utils::lock_guard _l(mMutex);
1516         needToReregister = !mObserverRegistered;
1517     }
1518     if (needToReregister) {
1519         // Looks like ActivityManager has died previously, attempt to re-register.
1520         registerSelf();
1521     }
1522 }
1523 
isUidActive(uid_t uid)1524 bool AudioPolicyService::UidPolicy::isUidActive(uid_t uid) {
1525     if (isServiceUid(uid)) return true;
1526     checkRegistered();
1527     {
1528         audio_utils::lock_guard _l(mMutex);
1529         // In an absense of the ActivityManager, assume everything to be active.
1530         if (!mObserverRegistered) return true;
1531         auto cacheIter = mCachedUids.find(uid);
1532         if (cacheIter != mCachedUids.end()) {
1533             return cacheIter->second.first;
1534         }
1535     }
1536     ActivityManager am;
1537     bool active = am.isUidActive(uid, String16("audioserver"));
1538     {
1539         audio_utils::lock_guard _l(mMutex);
1540         mCachedUids.insert(std::pair<uid_t,
1541                            std::pair<bool, int>>(uid, std::pair<bool, int>(active,
1542                                                       ActivityManager::PROCESS_STATE_UNKNOWN)));
1543     }
1544     return active;
1545 }
1546 
getUidState(uid_t uid)1547 int AudioPolicyService::UidPolicy::getUidState(uid_t uid) {
1548     if (isServiceUid(uid)) {
1549         return ActivityManager::PROCESS_STATE_TOP;
1550     }
1551     checkRegistered();
1552     {
1553         audio_utils::lock_guard _l(mMutex);
1554         // In an absense of the ActivityManager, assume everything to be active.
1555         if (!mObserverRegistered) {
1556             return ActivityManager::PROCESS_STATE_TOP;
1557         }
1558         auto cacheIter = mCachedUids.find(uid);
1559         if (cacheIter != mCachedUids.end()) {
1560             if (cacheIter->second.first) {
1561                 return cacheIter->second.second;
1562             } else {
1563                 return ActivityManager::PROCESS_STATE_UNKNOWN;
1564             }
1565         }
1566     }
1567     ActivityManager am;
1568     bool active = am.isUidActive(uid, String16("audioserver"));
1569     int state = ActivityManager::PROCESS_STATE_UNKNOWN;
1570     if (active) {
1571         state = am.getUidProcessState(uid, String16("audioserver"));
1572     }
1573     {
1574         audio_utils::lock_guard _l(mMutex);
1575         mCachedUids.insert(std::pair<uid_t,
1576                            std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
1577     }
1578 
1579     return state;
1580 }
1581 
onUidActive(uid_t uid)1582 void AudioPolicyService::UidPolicy::onUidActive(uid_t uid) {
1583     updateUid(&mCachedUids, uid, true, ActivityManager::PROCESS_STATE_UNKNOWN, true);
1584 }
1585 
onUidGone(uid_t uid,__unused bool disabled)1586 void AudioPolicyService::UidPolicy::onUidGone(uid_t uid, __unused bool disabled) {
1587     updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, false);
1588 }
1589 
onUidIdle(uid_t uid,__unused bool disabled)1590 void AudioPolicyService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
1591     updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, true);
1592 }
1593 
onUidStateChanged(uid_t uid,int32_t procState,int64_t procStateSeq __unused,int32_t capability __unused)1594 void AudioPolicyService::UidPolicy::onUidStateChanged(uid_t uid,
1595                                                       int32_t procState,
1596                                                       int64_t procStateSeq __unused,
1597                                                       int32_t capability __unused) {
1598     if (procState != ActivityManager::PROCESS_STATE_UNKNOWN) {
1599         updateUid(&mCachedUids, uid, true, procState, true);
1600     }
1601 }
1602 
onUidProcAdjChanged(uid_t uid __unused,int32_t adj __unused)1603 void AudioPolicyService::UidPolicy::onUidProcAdjChanged(uid_t uid __unused, int32_t adj __unused) {
1604 }
1605 
notifyService()1606 void AudioPolicyService::UidPolicy::notifyService() {
1607     sp<AudioPolicyService> service = mService.promote();
1608     if (service != nullptr) {
1609         service->updateUidStates();
1610     }
1611 }
1612 
updateUid(std::unordered_map<uid_t,std::pair<bool,int>> * uids,uid_t uid,bool active,int state,bool insert)1613 void AudioPolicyService::UidPolicy::updateUid(std::unordered_map<uid_t,
1614                                               std::pair<bool, int>> *uids,
1615                                               uid_t uid,
1616                                               bool active,
1617                                               int state,
1618                                               bool insert) {
1619     if (isServiceUid(uid)) {
1620         return;
1621     }
1622     bool wasActive = isUidActive(uid);
1623     int previousState = getUidState(uid);
1624     {
1625         audio_utils::lock_guard _l(mMutex);
1626         updateUidLocked(uids, uid, active, state, insert);
1627     }
1628     if (wasActive != isUidActive(uid) || state != previousState) {
1629         notifyService();
1630     }
1631 }
1632 
updateUidLocked(std::unordered_map<uid_t,std::pair<bool,int>> * uids,uid_t uid,bool active,int state,bool insert)1633 void AudioPolicyService::UidPolicy::updateUidLocked(std::unordered_map<uid_t,
1634                                                     std::pair<bool, int>> *uids,
1635                                                     uid_t uid,
1636                                                     bool active,
1637                                                     int state,
1638                                                     bool insert) {
1639     auto it = uids->find(uid);
1640     if (it != uids->end()) {
1641         if (insert) {
1642             if (state == ActivityManager::PROCESS_STATE_UNKNOWN) {
1643                 it->second.first = active;
1644             }
1645             if (it->second.first) {
1646                 it->second.second = state;
1647             } else {
1648                 it->second.second = ActivityManager::PROCESS_STATE_UNKNOWN;
1649             }
1650         } else {
1651             uids->erase(it);
1652         }
1653     } else if (insert && (state == ActivityManager::PROCESS_STATE_UNKNOWN)) {
1654         uids->insert(std::pair<uid_t, std::pair<bool, int>>(uid,
1655                                       std::pair<bool, int>(active, state)));
1656     }
1657 }
1658 
isA11yOnTop()1659 bool AudioPolicyService::UidPolicy::isA11yOnTop() {
1660     audio_utils::lock_guard _l(mMutex);
1661     for (const auto &uid : mCachedUids) {
1662         if (!isA11yUid(uid.first)) {
1663             continue;
1664         }
1665         if (uid.second.second >= ActivityManager::PROCESS_STATE_TOP
1666                 && uid.second.second <= ActivityManager::PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
1667             return true;
1668         }
1669     }
1670     return false;
1671 }
1672 
isA11yUid(uid_t uid)1673 bool AudioPolicyService::UidPolicy::isA11yUid(uid_t uid)
1674 {
1675     std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid);
1676     return it != mA11yUids.end();
1677 }
1678 
setAssistantUids(const std::vector<uid_t> & uids)1679 void AudioPolicyService::UidPolicy::setAssistantUids(const std::vector<uid_t>& uids) {
1680     mAssistantUids.clear();
1681     mAssistantUids = uids;
1682 }
1683 
isAssistantUid(uid_t uid)1684 bool AudioPolicyService::UidPolicy::isAssistantUid(uid_t uid)
1685 {
1686     std::vector<uid_t>::iterator it = find(mAssistantUids.begin(), mAssistantUids.end(), uid);
1687     return it != mAssistantUids.end();
1688 }
1689 
setActiveAssistantUids(const std::vector<uid_t> & activeUids)1690 void AudioPolicyService::UidPolicy::setActiveAssistantUids(const std::vector<uid_t>& activeUids) {
1691     mActiveAssistantUids = activeUids;
1692 }
1693 
isActiveAssistantUid(uid_t uid)1694 bool AudioPolicyService::UidPolicy::isActiveAssistantUid(uid_t uid)
1695 {
1696     std::vector<uid_t>::iterator it = find(mActiveAssistantUids.begin(),
1697             mActiveAssistantUids.end(), uid);
1698     return it != mActiveAssistantUids.end();
1699 }
1700 
dumpInternals(int fd)1701 void AudioPolicyService::UidPolicy::dumpInternals(int fd) {
1702     const size_t SIZE = 256;
1703     char buffer[SIZE];
1704     String8 result;
1705     auto appendUidsToResult = [&](const char* title, const std::vector<uid_t> &uids) {
1706         snprintf(buffer, SIZE, "\t%s: \n", title);
1707         result.append(buffer);
1708         int counter = 0;
1709         if (uids.empty()) {
1710             snprintf(buffer, SIZE, "\t\tNo UIDs present.\n");
1711             result.append(buffer);
1712             return;
1713         }
1714         for (const auto &uid : uids) {
1715             snprintf(buffer, SIZE, "\t\tUID[%d]=%d\n", counter++, uid);
1716             result.append(buffer);
1717         }
1718     };
1719 
1720     snprintf(buffer, SIZE, "UID Policy:\n");
1721     result.append(buffer);
1722     snprintf(buffer, SIZE, "\tmObserverRegistered=%s\n",(mObserverRegistered ? "True":"False"));
1723     result.append(buffer);
1724 
1725     appendUidsToResult("Assistants UIDs", mAssistantUids);
1726     appendUidsToResult("Active Assistants UIDs", mActiveAssistantUids);
1727 
1728     appendUidsToResult("Accessibility UIDs", mA11yUids);
1729 
1730     snprintf(buffer, SIZE, "\tInput Method Service UID=%d\n", mCurrentImeUid);
1731     result.append(buffer);
1732 
1733     snprintf(buffer, SIZE, "\tIs RTT Enabled: %s\n", (mRttEnabled ? "True":"False"));
1734     result.append(buffer);
1735 
1736     write(fd, result.c_str(), result.size());
1737 }
1738 
1739 // -----------  AudioPolicyService::SensorPrivacyService implementation ----------
registerSelf()1740 void AudioPolicyService::SensorPrivacyPolicy::registerSelf() {
1741     SensorPrivacyManager spm;
1742     mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1743     spm.addSensorPrivacyListener(this);
1744 }
1745 
unregisterSelf()1746 void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
1747     SensorPrivacyManager spm;
1748     spm.removeSensorPrivacyListener(this);
1749 }
1750 
isSensorPrivacyEnabled()1751 bool AudioPolicyService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1752     return mSensorPrivacyEnabled;
1753 }
1754 
onSensorPrivacyChanged(int toggleType __unused,int sensor __unused,bool enabled)1755 binder::Status AudioPolicyService::SensorPrivacyPolicy::onSensorPrivacyChanged(
1756     int toggleType __unused, int sensor __unused, bool enabled) {
1757     mSensorPrivacyEnabled = enabled;
1758     sp<AudioPolicyService> service = mService.promote();
1759     if (service != nullptr) {
1760         service->updateUidStates();
1761     }
1762     return binder::Status::ok();
1763 }
1764 
1765 // -----------  AudioPolicyService::AudioCommandThread implementation ----------
1766 
AudioCommandThread(String8 name,const wp<AudioPolicyService> & service)1767 AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
1768                                                            const wp<AudioPolicyService>& service)
1769     : Thread(false), mName(name), mService(service)
1770 {
1771 }
1772 
1773 
~AudioCommandThread()1774 AudioPolicyService::AudioCommandThread::~AudioCommandThread()
1775 {
1776     if (!mAudioCommands.isEmpty()) {
1777         release_wake_lock(mName.c_str());
1778     }
1779     mAudioCommands.clear();
1780 }
1781 
onFirstRef()1782 void AudioPolicyService::AudioCommandThread::onFirstRef()
1783 {
1784     run(mName.c_str(), ANDROID_PRIORITY_AUDIO);
1785 }
1786 
threadLoop()1787 bool AudioPolicyService::AudioCommandThread::threadLoop()
1788 {
1789     nsecs_t waitTime = -1;
1790 
1791     audio_utils::unique_lock ul(mMutex);
1792     while (!exitPending())
1793     {
1794         sp<AudioPolicyService> svc;
1795         int numTimesBecameEmpty = 0;
1796         while (!mAudioCommands.isEmpty() && !exitPending()) {
1797             nsecs_t curTime = systemTime();
1798             // commands are sorted by increasing time stamp: execute them from index 0 and up
1799             if (mAudioCommands[0]->mTime <= curTime) {
1800                 sp<AudioCommand> command = mAudioCommands[0];
1801                 mAudioCommands.removeAt(0);
1802                 if (mAudioCommands.isEmpty()) {
1803                   ++numTimesBecameEmpty;
1804                 }
1805                 mLastCommand = command;
1806 
1807                 switch (command->mCommand) {
1808                 case SET_VOLUME: {
1809                     VolumeData *data = (VolumeData *)command->mParam.get();
1810                     ALOGV("AudioCommandThread() processing set volume stream %d, \
1811                             volume %f, output %d", data->mStream, data->mVolume, data->mIO);
1812                     ul.unlock();
1813                     command->mStatus = AudioSystem::setStreamVolume(data->mStream,
1814                                                                     data->mVolume,
1815                                                                     data->mIO);
1816                     ul.lock();
1817                     }break;
1818                 case SET_PARAMETERS: {
1819                     ParametersData *data = (ParametersData *)command->mParam.get();
1820                     ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
1821                             data->mKeyValuePairs.c_str(), data->mIO);
1822                     ul.unlock();
1823                     command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
1824                     ul.lock();
1825                     }break;
1826                 case SET_VOICE_VOLUME: {
1827                     VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
1828                     ALOGV("AudioCommandThread() processing set voice volume volume %f",
1829                             data->mVolume);
1830                     ul.unlock();
1831                     command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
1832                     ul.lock();
1833                     }break;
1834                 case STOP_OUTPUT: {
1835                     StopOutputData *data = (StopOutputData *)command->mParam.get();
1836                     ALOGV("AudioCommandThread() processing stop output portId %d",
1837                             data->mPortId);
1838                     svc = mService.promote();
1839                     if (svc == 0) {
1840                         break;
1841                     }
1842                     ul.unlock();
1843                     svc->doStopOutput(data->mPortId);
1844                     ul.lock();
1845                     }break;
1846                 case RELEASE_OUTPUT: {
1847                     ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
1848                     ALOGV("AudioCommandThread() processing release output portId %d",
1849                             data->mPortId);
1850                     svc = mService.promote();
1851                     if (svc == 0) {
1852                         break;
1853                     }
1854                     ul.unlock();
1855                     svc->doReleaseOutput(data->mPortId);
1856                     ul.lock();
1857                     }break;
1858                 case CREATE_AUDIO_PATCH: {
1859                     CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
1860                     ALOGV("AudioCommandThread() processing create audio patch");
1861                     sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1862                     if (af == 0) {
1863                         command->mStatus = PERMISSION_DENIED;
1864                     } else {
1865                         ul.unlock();
1866                         command->mStatus = af->createAudioPatch(&data->mPatch, &data->mHandle);
1867                         ul.lock();
1868                     }
1869                     } break;
1870                 case RELEASE_AUDIO_PATCH: {
1871                     ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
1872                     ALOGV("AudioCommandThread() processing release audio patch");
1873                     sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1874                     if (af == 0) {
1875                         command->mStatus = PERMISSION_DENIED;
1876                     } else {
1877                         ul.unlock();
1878                         command->mStatus = af->releaseAudioPatch(data->mHandle);
1879                         ul.lock();
1880                     }
1881                     } break;
1882                 case UPDATE_AUDIOPORT_LIST: {
1883                     ALOGV("AudioCommandThread() processing update audio port list");
1884                     svc = mService.promote();
1885                     if (svc == 0) {
1886                         break;
1887                     }
1888                     ul.unlock();
1889                     svc->doOnAudioPortListUpdate();
1890                     ul.lock();
1891                     }break;
1892                 case UPDATE_AUDIOPATCH_LIST: {
1893                     ALOGV("AudioCommandThread() processing update audio patch list");
1894                     svc = mService.promote();
1895                     if (svc == 0) {
1896                         break;
1897                     }
1898                     ul.unlock();
1899                     svc->doOnAudioPatchListUpdate();
1900                     ul.lock();
1901                     }break;
1902                 case CHANGED_AUDIOVOLUMEGROUP: {
1903                     AudioVolumeGroupData *data =
1904                             static_cast<AudioVolumeGroupData *>(command->mParam.get());
1905                     ALOGV("AudioCommandThread() processing update audio volume group");
1906                     svc = mService.promote();
1907                     if (svc == 0) {
1908                         break;
1909                     }
1910                     ul.unlock();
1911                     svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
1912                     ul.lock();
1913                     }break;
1914                 case SET_AUDIOPORT_CONFIG: {
1915                     SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
1916                     ALOGV("AudioCommandThread() processing set port config");
1917                     sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1918                     if (af == 0) {
1919                         command->mStatus = PERMISSION_DENIED;
1920                     } else {
1921                         ul.unlock();
1922                         command->mStatus = af->setAudioPortConfig(&data->mConfig);
1923                         ul.lock();
1924                     }
1925                     } break;
1926                 case DYN_POLICY_MIX_STATE_UPDATE: {
1927                     DynPolicyMixStateUpdateData *data =
1928                             (DynPolicyMixStateUpdateData *)command->mParam.get();
1929                     ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
1930                             data->mRegId.c_str(), data->mState);
1931                     svc = mService.promote();
1932                     if (svc == 0) {
1933                         break;
1934                     }
1935                     ul.unlock();
1936                     svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
1937                     ul.lock();
1938                     } break;
1939                 case RECORDING_CONFIGURATION_UPDATE: {
1940                     RecordingConfigurationUpdateData *data =
1941                             (RecordingConfigurationUpdateData *)command->mParam.get();
1942                     ALOGV("AudioCommandThread() processing recording configuration update");
1943                     svc = mService.promote();
1944                     if (svc == 0) {
1945                         break;
1946                     }
1947                     ul.unlock();
1948                     svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
1949                             &data->mClientConfig, data->mClientEffects,
1950                             &data->mDeviceConfig, data->mEffects,
1951                             data->mPatchHandle, data->mSource);
1952                     ul.lock();
1953                     } break;
1954                 case SET_EFFECT_SUSPENDED: {
1955                     SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
1956                     ALOGV("AudioCommandThread() processing set effect suspended");
1957                     sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1958                     if (af != 0) {
1959                         ul.unlock();
1960                         af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
1961                         ul.lock();
1962                     }
1963                     } break;
1964                 case AUDIO_MODULES_UPDATE: {
1965                     ALOGV("AudioCommandThread() processing audio modules update");
1966                     svc = mService.promote();
1967                     if (svc == 0) {
1968                         break;
1969                     }
1970                     ul.unlock();
1971                     svc->doOnNewAudioModulesAvailable();
1972                     ul.lock();
1973                     } break;
1974                 case ROUTING_UPDATED: {
1975                     ALOGV("AudioCommandThread() processing routing update");
1976                     svc = mService.promote();
1977                     if (svc == 0) {
1978                         break;
1979                     }
1980                     ul.unlock();
1981                     svc->doOnRoutingUpdated();
1982                     ul.lock();
1983                     } break;
1984 
1985                 case UPDATE_UID_STATES: {
1986                     ALOGV("AudioCommandThread() processing updateUID states");
1987                     svc = mService.promote();
1988                     if (svc == 0) {
1989                         break;
1990                     }
1991                     ul.unlock();
1992                     svc->updateUidStates();
1993                     ul.lock();
1994                     } break;
1995 
1996                 case CHECK_SPATIALIZER_OUTPUT: {
1997                     ALOGV("AudioCommandThread() processing check spatializer");
1998                     svc = mService.promote();
1999                     if (svc == 0) {
2000                         break;
2001                     }
2002                     ul.unlock();
2003                     svc->doOnCheckSpatializer();
2004                     ul.lock();
2005                     } break;
2006 
2007                 case UPDATE_ACTIVE_SPATIALIZER_TRACKS: {
2008                     ALOGV("AudioCommandThread() processing update spatializer tracks");
2009                     svc = mService.promote();
2010                     if (svc == 0) {
2011                         break;
2012                     }
2013                     ul.unlock();
2014                     svc->doOnUpdateActiveSpatializerTracks();
2015                     ul.lock();
2016                     } break;
2017 
2018                 case VOL_RANGE_INIT_REQUEST: {
2019                     ALOGV("AudioCommandThread() processing volume range init request");
2020                     svc = mService.promote();
2021                     if (svc == 0) {
2022                         break;
2023                     }
2024                     ul.unlock();
2025                     svc->doOnVolumeRangeInitRequest();
2026                     ul.lock();
2027                     } break;
2028 
2029                 default:
2030                     ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
2031                 }
2032                 {
2033                     audio_utils::lock_guard _l(command->mMutex);
2034                     if (command->mWaitStatus) {
2035                         command->mWaitStatus = false;
2036                         command->mCond.notify_one();
2037                     }
2038                 }
2039                 waitTime = -1;
2040                 // release ul before releasing strong reference on the service as
2041                 // AudioPolicyService destructor calls AudioCommandThread::exit() which
2042                 // acquires ul.
2043                 ul.unlock();
2044                 svc.clear();
2045                 ul.lock();
2046             } else {
2047                 waitTime = mAudioCommands[0]->mTime - curTime;
2048                 break;
2049             }
2050         }
2051 
2052         // release delayed commands wake lock as many times as we made the  queue is
2053         // empty during popping.
2054         while (numTimesBecameEmpty--) {
2055             release_wake_lock(mName.c_str());
2056         }
2057 
2058         // At this stage we have either an empty command queue or the first command in the queue
2059         // has a finite delay. So unless we are exiting it is safe to wait.
2060         if (!exitPending()) {
2061             ALOGV("AudioCommandThread() going to sleep");
2062             if (waitTime == -1) {
2063                 mWaitWorkCV.wait(ul);
2064             } else {
2065                 // discard return value.
2066                 mWaitWorkCV.wait_for(ul, std::chrono::nanoseconds(waitTime));
2067             }
2068         }
2069     }
2070     // release delayed commands wake lock before quitting
2071     if (!mAudioCommands.isEmpty()) {
2072         release_wake_lock(mName.c_str());
2073     }
2074     return false;
2075 }
2076 
dump(int fd)2077 status_t AudioPolicyService::AudioCommandThread::dump(int fd)
2078 NO_THREAD_SAFETY_ANALYSIS  // trylock
2079 {
2080     const size_t SIZE = 256;
2081     char buffer[SIZE];
2082     String8 result;
2083 
2084     const bool locked = mMutex.try_lock(kDumpLockTimeoutNs);
2085     if (!locked) {
2086         String8 result2(kCmdDeadlockedString);
2087         write(fd, result2.c_str(), result2.size());
2088     }
2089 
2090     snprintf(buffer, SIZE, "- Commands:\n");
2091     result = String8(buffer);
2092     result.append("   Command Time        Wait pParam\n");
2093     for (size_t i = 0; i < mAudioCommands.size(); i++) {
2094         mAudioCommands[i]->dump(buffer, SIZE);
2095         result.append(buffer);
2096     }
2097     result.append("  Last Command\n");
2098     if (mLastCommand != 0) {
2099         mLastCommand->dump(buffer, SIZE);
2100         result.append(buffer);
2101     } else {
2102         result.append("     none\n");
2103     }
2104 
2105     write(fd, result.c_str(), result.size());
2106 
2107     dumpReleaseLock(mMutex, locked);
2108 
2109     return NO_ERROR;
2110 }
2111 
volumeCommand(audio_stream_type_t stream,float volume,audio_io_handle_t output,int delayMs)2112 status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
2113                                                                float volume,
2114                                                                audio_io_handle_t output,
2115                                                                int delayMs)
2116 {
2117     sp<AudioCommand> command = new AudioCommand();
2118     command->mCommand = SET_VOLUME;
2119     sp<VolumeData> data = new VolumeData();
2120     data->mStream = stream;
2121     data->mVolume = volume;
2122     data->mIO = output;
2123     command->mParam = data;
2124     command->mWaitStatus = true;
2125     ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
2126             stream, volume, output);
2127     return sendCommand(command, delayMs);
2128 }
2129 
parametersCommand(audio_io_handle_t ioHandle,const char * keyValuePairs,int delayMs)2130 status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
2131                                                                    const char *keyValuePairs,
2132                                                                    int delayMs)
2133 {
2134     sp<AudioCommand> command = new AudioCommand();
2135     command->mCommand = SET_PARAMETERS;
2136     sp<ParametersData> data = new ParametersData();
2137     data->mIO = ioHandle;
2138     data->mKeyValuePairs = String8(keyValuePairs);
2139     command->mParam = data;
2140     command->mWaitStatus = true;
2141     ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
2142             keyValuePairs, ioHandle, delayMs);
2143     return sendCommand(command, delayMs);
2144 }
2145 
voiceVolumeCommand(float volume,int delayMs)2146 status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
2147 {
2148     sp<AudioCommand> command = new AudioCommand();
2149     command->mCommand = SET_VOICE_VOLUME;
2150     sp<VoiceVolumeData> data = new VoiceVolumeData();
2151     data->mVolume = volume;
2152     command->mParam = data;
2153     command->mWaitStatus = true;
2154     ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
2155     return sendCommand(command, delayMs);
2156 }
2157 
setEffectSuspendedCommand(int effectId,audio_session_t sessionId,bool suspended)2158 void AudioPolicyService::AudioCommandThread::setEffectSuspendedCommand(int effectId,
2159                                                                        audio_session_t sessionId,
2160                                                                        bool suspended)
2161 {
2162     sp<AudioCommand> command = new AudioCommand();
2163     command->mCommand = SET_EFFECT_SUSPENDED;
2164     sp<SetEffectSuspendedData> data = new SetEffectSuspendedData();
2165     data->mEffectId = effectId;
2166     data->mSessionId = sessionId;
2167     data->mSuspended = suspended;
2168     command->mParam = data;
2169     ALOGV("AudioCommandThread() adding set suspended effectId %d sessionId %d suspended %d",
2170         effectId, sessionId, suspended);
2171     sendCommand(command);
2172 }
2173 
2174 
stopOutputCommand(audio_port_handle_t portId)2175 void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_port_handle_t portId)
2176 {
2177     sp<AudioCommand> command = new AudioCommand();
2178     command->mCommand = STOP_OUTPUT;
2179     sp<StopOutputData> data = new StopOutputData();
2180     data->mPortId = portId;
2181     command->mParam = data;
2182     ALOGV("AudioCommandThread() adding stop output portId %d", portId);
2183     sendCommand(command);
2184 }
2185 
releaseOutputCommand(audio_port_handle_t portId)2186 void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_port_handle_t portId)
2187 {
2188     sp<AudioCommand> command = new AudioCommand();
2189     command->mCommand = RELEASE_OUTPUT;
2190     sp<ReleaseOutputData> data = new ReleaseOutputData();
2191     data->mPortId = portId;
2192     command->mParam = data;
2193     ALOGV("AudioCommandThread() adding release output portId %d", portId);
2194     sendCommand(command);
2195 }
2196 
createAudioPatchCommand(const struct audio_patch * patch,audio_patch_handle_t * handle,int delayMs)2197 status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
2198                                                 const struct audio_patch *patch,
2199                                                 audio_patch_handle_t *handle,
2200                                                 int delayMs)
2201 {
2202     status_t status = NO_ERROR;
2203 
2204     sp<AudioCommand> command = new AudioCommand();
2205     command->mCommand = CREATE_AUDIO_PATCH;
2206     CreateAudioPatchData *data = new CreateAudioPatchData();
2207     data->mPatch = *patch;
2208     data->mHandle = *handle;
2209     command->mParam = data;
2210     command->mWaitStatus = true;
2211     ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
2212     status = sendCommand(command, delayMs);
2213     if (status == NO_ERROR) {
2214         *handle = data->mHandle;
2215     }
2216     return status;
2217 }
2218 
releaseAudioPatchCommand(audio_patch_handle_t handle,int delayMs)2219 status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
2220                                                  int delayMs)
2221 {
2222     sp<AudioCommand> command = new AudioCommand();
2223     command->mCommand = RELEASE_AUDIO_PATCH;
2224     ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
2225     data->mHandle = handle;
2226     command->mParam = data;
2227     command->mWaitStatus = true;
2228     ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
2229     return sendCommand(command, delayMs);
2230 }
2231 
updateAudioPortListCommand()2232 void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
2233 {
2234     sp<AudioCommand> command = new AudioCommand();
2235     command->mCommand = UPDATE_AUDIOPORT_LIST;
2236     ALOGV("AudioCommandThread() adding update audio port list");
2237     sendCommand(command);
2238 }
2239 
updateUidStatesCommand()2240 void AudioPolicyService::AudioCommandThread::updateUidStatesCommand()
2241 {
2242     sp<AudioCommand> command = new AudioCommand();
2243     command->mCommand = UPDATE_UID_STATES;
2244     ALOGV("AudioCommandThread() adding update UID states");
2245     sendCommand(command);
2246 }
2247 
updateAudioPatchListCommand()2248 void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
2249 {
2250     sp<AudioCommand>command = new AudioCommand();
2251     command->mCommand = UPDATE_AUDIOPATCH_LIST;
2252     ALOGV("AudioCommandThread() adding update audio patch list");
2253     sendCommand(command);
2254 }
2255 
changeAudioVolumeGroupCommand(volume_group_t group,int flags)2256 void AudioPolicyService::AudioCommandThread::changeAudioVolumeGroupCommand(volume_group_t group,
2257                                                                            int flags)
2258 {
2259     sp<AudioCommand>command = new AudioCommand();
2260     command->mCommand = CHANGED_AUDIOVOLUMEGROUP;
2261     AudioVolumeGroupData *data= new AudioVolumeGroupData();
2262     data->mGroup = group;
2263     data->mFlags = flags;
2264     command->mParam = data;
2265     ALOGV("AudioCommandThread() adding audio volume group changed");
2266     sendCommand(command);
2267 }
2268 
setAudioPortConfigCommand(const struct audio_port_config * config,int delayMs)2269 status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
2270                                             const struct audio_port_config *config, int delayMs)
2271 {
2272     sp<AudioCommand> command = new AudioCommand();
2273     command->mCommand = SET_AUDIOPORT_CONFIG;
2274     SetAudioPortConfigData *data = new SetAudioPortConfigData();
2275     data->mConfig = *config;
2276     command->mParam = data;
2277     command->mWaitStatus = true;
2278     ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
2279     return sendCommand(command, delayMs);
2280 }
2281 
dynamicPolicyMixStateUpdateCommand(const String8 & regId,int32_t state)2282 void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
2283         const String8& regId, int32_t state)
2284 {
2285     sp<AudioCommand> command = new AudioCommand();
2286     command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
2287     DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
2288     data->mRegId = regId;
2289     data->mState = state;
2290     command->mParam = data;
2291     ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
2292             regId.c_str(), state);
2293     sendCommand(command);
2294 }
2295 
recordingConfigurationUpdateCommand(int event,const record_client_info_t * clientInfo,const audio_config_base_t * clientConfig,std::vector<effect_descriptor_t> clientEffects,const audio_config_base_t * deviceConfig,std::vector<effect_descriptor_t> effects,audio_patch_handle_t patchHandle,audio_source_t source)2296 void AudioPolicyService::AudioCommandThread::recordingConfigurationUpdateCommand(
2297                                                 int event,
2298                                                 const record_client_info_t *clientInfo,
2299                                                 const audio_config_base_t *clientConfig,
2300                                                 std::vector<effect_descriptor_t> clientEffects,
2301                                                 const audio_config_base_t *deviceConfig,
2302                                                 std::vector<effect_descriptor_t> effects,
2303                                                 audio_patch_handle_t patchHandle,
2304                                                 audio_source_t source)
2305 {
2306     sp<AudioCommand>command = new AudioCommand();
2307     command->mCommand = RECORDING_CONFIGURATION_UPDATE;
2308     RecordingConfigurationUpdateData *data = new RecordingConfigurationUpdateData();
2309     data->mEvent = event;
2310     data->mClientInfo = *clientInfo;
2311     data->mClientConfig = *clientConfig;
2312     data->mClientEffects = clientEffects;
2313     data->mDeviceConfig = *deviceConfig;
2314     data->mEffects = effects;
2315     data->mPatchHandle = patchHandle;
2316     data->mSource = source;
2317     command->mParam = data;
2318     ALOGV("AudioCommandThread() adding recording configuration update event %d, source %d uid %u",
2319             event, clientInfo->source, clientInfo->uid);
2320     sendCommand(command);
2321 }
2322 
audioModulesUpdateCommand()2323 void AudioPolicyService::AudioCommandThread::audioModulesUpdateCommand()
2324 {
2325     sp<AudioCommand> command = new AudioCommand();
2326     command->mCommand = AUDIO_MODULES_UPDATE;
2327     sendCommand(command);
2328 }
2329 
routingChangedCommand()2330 void AudioPolicyService::AudioCommandThread::routingChangedCommand()
2331 {
2332     sp<AudioCommand>command = new AudioCommand();
2333     command->mCommand = ROUTING_UPDATED;
2334     ALOGV("AudioCommandThread() adding routing update");
2335     sendCommand(command);
2336 }
2337 
checkSpatializerCommand()2338 void AudioPolicyService::AudioCommandThread::checkSpatializerCommand()
2339 {
2340     sp<AudioCommand>command = new AudioCommand();
2341     command->mCommand = CHECK_SPATIALIZER_OUTPUT;
2342     ALOGV("AudioCommandThread() adding check spatializer");
2343     sendCommand(command);
2344 }
2345 
updateActiveSpatializerTracksCommand()2346 void AudioPolicyService::AudioCommandThread::updateActiveSpatializerTracksCommand()
2347 {
2348     sp<AudioCommand>command = new AudioCommand();
2349     command->mCommand = UPDATE_ACTIVE_SPATIALIZER_TRACKS;
2350     ALOGV("AudioCommandThread() adding update active spatializer tracks");
2351     sendCommand(command);
2352 }
2353 
volRangeInitReqCommand()2354 void AudioPolicyService::AudioCommandThread::volRangeInitReqCommand()
2355 {
2356     sp<AudioCommand>command = new AudioCommand();
2357     command->mCommand = VOL_RANGE_INIT_REQUEST;
2358     ALOGV("AudioCommandThread() adding volume range init request");
2359     sendCommand(command);
2360 }
2361 
sendCommand(sp<AudioCommand> & command,int delayMs)2362 status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
2363 {
2364     {
2365         audio_utils::lock_guard _l(mMutex);
2366         insertCommand_l(command, delayMs);
2367         mWaitWorkCV.notify_one();
2368     }
2369     audio_utils::unique_lock ul(command->mMutex);
2370     while (command->mWaitStatus) {
2371         nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
2372         if (command->mCond.wait_for(
2373                 ul, std::chrono::nanoseconds(timeOutNs), getTid()) == std::cv_status::timeout) {
2374             command->mStatus = TIMED_OUT;
2375             command->mWaitStatus = false;
2376         }
2377     }
2378     return command->mStatus;
2379 }
2380 
2381 // insertCommand_l() must be called with mMutex held
insertCommand_l(sp<AudioCommand> & command,int delayMs)2382 void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
2383 {
2384     ssize_t i;  // not size_t because i will count down to -1
2385     Vector < sp<AudioCommand> > removedCommands;
2386     command->mTime = systemTime() + milliseconds(delayMs);
2387 
2388     // acquire wake lock to make sure delayed commands are processed
2389     if (mAudioCommands.isEmpty()) {
2390         acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.c_str());
2391     }
2392 
2393     // check same pending commands with later time stamps and eliminate them
2394     for (i = (ssize_t)mAudioCommands.size()-1; i >= 0; i--) {
2395         sp<AudioCommand> command2 = mAudioCommands[i];
2396         // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
2397         if (command2->mTime <= command->mTime) break;
2398 
2399         // create audio patch or release audio patch commands are equivalent
2400         // with regard to filtering
2401         if ((command->mCommand == CREATE_AUDIO_PATCH) ||
2402                 (command->mCommand == RELEASE_AUDIO_PATCH)) {
2403             if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
2404                     (command2->mCommand != RELEASE_AUDIO_PATCH)) {
2405                 continue;
2406             }
2407         } else if (command2->mCommand != command->mCommand) continue;
2408 
2409         switch (command->mCommand) {
2410         case SET_PARAMETERS: {
2411             ParametersData *data = (ParametersData *)command->mParam.get();
2412             ParametersData *data2 = (ParametersData *)command2->mParam.get();
2413             if (data->mIO != data2->mIO) break;
2414             ALOGV("Comparing parameter command %s to new command %s",
2415                     data2->mKeyValuePairs.c_str(), data->mKeyValuePairs.c_str());
2416             AudioParameter param = AudioParameter(data->mKeyValuePairs);
2417             AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
2418             for (size_t j = 0; j < param.size(); j++) {
2419                 String8 key;
2420                 String8 value;
2421                 param.getAt(j, key, value);
2422                 for (size_t k = 0; k < param2.size(); k++) {
2423                     String8 key2;
2424                     String8 value2;
2425                     param2.getAt(k, key2, value2);
2426                     if (key2 == key) {
2427                         param2.remove(key2);
2428                         ALOGV("Filtering out parameter %s", key2.c_str());
2429                         break;
2430                     }
2431                 }
2432             }
2433             // if all keys have been filtered out, remove the command.
2434             // otherwise, update the key value pairs
2435             if (param2.size() == 0) {
2436                 removedCommands.add(command2);
2437             } else {
2438                 data2->mKeyValuePairs = param2.toString();
2439             }
2440             command->mTime = command2->mTime;
2441             // force delayMs to non 0 so that code below does not request to wait for
2442             // command status as the command is now delayed
2443             delayMs = 1;
2444         } break;
2445 
2446         case SET_VOLUME: {
2447             VolumeData *data = (VolumeData *)command->mParam.get();
2448             VolumeData *data2 = (VolumeData *)command2->mParam.get();
2449             if (data->mIO != data2->mIO) break;
2450             if (data->mStream != data2->mStream) break;
2451             ALOGV("Filtering out volume command on output %d for stream %d",
2452                     data->mIO, data->mStream);
2453             removedCommands.add(command2);
2454             command->mTime = command2->mTime;
2455             // force delayMs to non 0 so that code below does not request to wait for
2456             // command status as the command is now delayed
2457             delayMs = 1;
2458         } break;
2459 
2460         case SET_VOICE_VOLUME: {
2461             VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
2462             VoiceVolumeData *data2 = (VoiceVolumeData *)command2->mParam.get();
2463             ALOGV("Filtering out voice volume command value %f replaced by %f",
2464                   data2->mVolume, data->mVolume);
2465             removedCommands.add(command2);
2466             command->mTime = command2->mTime;
2467             // force delayMs to non 0 so that code below does not request to wait for
2468             // command status as the command is now delayed
2469             delayMs = 1;
2470         } break;
2471 
2472         case CREATE_AUDIO_PATCH:
2473         case RELEASE_AUDIO_PATCH: {
2474             audio_patch_handle_t handle;
2475             struct audio_patch patch;
2476             if (command->mCommand == CREATE_AUDIO_PATCH) {
2477                 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
2478                 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
2479             } else {
2480                 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
2481                 memset(&patch, 0, sizeof(patch));
2482             }
2483             audio_patch_handle_t handle2;
2484             struct audio_patch patch2;
2485             if (command2->mCommand == CREATE_AUDIO_PATCH) {
2486                 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
2487                 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
2488             } else {
2489                 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
2490                 memset(&patch2, 0, sizeof(patch2));
2491             }
2492             if (handle != handle2) break;
2493             /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
2494                same output. */
2495             if( (command->mCommand == CREATE_AUDIO_PATCH) &&
2496                 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
2497                 bool isOutputDiff = false;
2498                 if (patch.num_sources == patch2.num_sources) {
2499                     for (unsigned count = 0; count < patch.num_sources; count++) {
2500                         if (patch.sources[count].id != patch2.sources[count].id) {
2501                             isOutputDiff = true;
2502                             break;
2503                         }
2504                     }
2505                     if (isOutputDiff)
2506                        break;
2507                 }
2508             }
2509             ALOGV("Filtering out %s audio patch command for handle %d",
2510                   (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
2511             removedCommands.add(command2);
2512             command->mTime = command2->mTime;
2513             // force delayMs to non 0 so that code below does not request to wait for
2514             // command status as the command is now delayed
2515             delayMs = 1;
2516         } break;
2517 
2518         case DYN_POLICY_MIX_STATE_UPDATE: {
2519 
2520         } break;
2521 
2522         case RECORDING_CONFIGURATION_UPDATE: {
2523 
2524         } break;
2525 
2526         case ROUTING_UPDATED: {
2527 
2528         } break;
2529 
2530         case VOL_RANGE_INIT_REQUEST: {
2531             // command may come from different requests, do not filter
2532         } break;
2533 
2534         default:
2535             break;
2536         }
2537     }
2538 
2539     // remove filtered commands
2540     for (size_t j = 0; j < removedCommands.size(); j++) {
2541         // removed commands always have time stamps greater than current command
2542         for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
2543             if (mAudioCommands[k].get() == removedCommands[j].get()) {
2544                 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
2545                 mAudioCommands.removeAt(k);
2546                 break;
2547             }
2548         }
2549     }
2550     removedCommands.clear();
2551 
2552     // Disable wait for status if delay is not 0.
2553     // Except for create audio patch command because the returned patch handle
2554     // is needed by audio policy manager
2555     if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
2556         command->mWaitStatus = false;
2557     }
2558 
2559     // insert command at the right place according to its time stamp
2560     ALOGV("inserting command: %d at index %zd, num commands %zu",
2561             command->mCommand, i+1, mAudioCommands.size());
2562     mAudioCommands.insertAt(command, i + 1);
2563 }
2564 
exit()2565 void AudioPolicyService::AudioCommandThread::exit()
2566 {
2567     ALOGV("AudioCommandThread::exit");
2568     {
2569         audio_utils::lock_guard _l(mMutex);
2570         requestExit();
2571         mWaitWorkCV.notify_one();
2572     }
2573     // Note that we can call it from the thread loop if all other references have been released
2574     // but it will safely return WOULD_BLOCK in this case
2575     requestExitAndWait();
2576 }
2577 
dump(char * buffer,size_t size)2578 void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
2579 {
2580     snprintf(buffer, size, "   %02d      %06d.%03d  %01u    %p\n",
2581             mCommand,
2582             (int)ns2s(mTime),
2583             (int)ns2ms(mTime)%1000,
2584             mWaitStatus,
2585             mParam.get());
2586 }
2587 
2588 /******* helpers for the service_ops callbacks defined below *********/
setParameters(audio_io_handle_t ioHandle,const char * keyValuePairs,int delayMs)2589 void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
2590                                        const char *keyValuePairs,
2591                                        int delayMs)
2592 {
2593     mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
2594                                            delayMs);
2595 }
2596 
setStreamVolume(audio_stream_type_t stream,float volume,audio_io_handle_t output,int delayMs)2597 int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
2598                                         float volume,
2599                                         audio_io_handle_t output,
2600                                         int delayMs)
2601 {
2602     return (int)mAudioCommandThread->volumeCommand(stream, volume,
2603                                                    output, delayMs);
2604 }
2605 
setVoiceVolume(float volume,int delayMs)2606 int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
2607 {
2608     return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
2609 }
2610 
setEffectSuspended(int effectId,audio_session_t sessionId,bool suspended)2611 void AudioPolicyService::setEffectSuspended(int effectId,
2612                                             audio_session_t sessionId,
2613                                             bool suspended)
2614 {
2615     mAudioCommandThread->setEffectSuspendedCommand(effectId, sessionId, suspended);
2616 }
2617 
onNewAudioModulesAvailable()2618 Status AudioPolicyService::onNewAudioModulesAvailable()
2619 {
2620     mOutputCommandThread->audioModulesUpdateCommand();
2621     return Status::ok();
2622 }
2623 
2624 
2625 extern "C" {
2626 audio_module_handle_t aps_load_hw_module(void *service __unused,
2627                                              const char *name);
2628 audio_io_handle_t aps_open_output(void *service __unused,
2629                                          audio_devices_t *pDevices,
2630                                          uint32_t *pSamplingRate,
2631                                          audio_format_t *pFormat,
2632                                          audio_channel_mask_t *pChannelMask,
2633                                          uint32_t *pLatencyMs,
2634                                          audio_output_flags_t flags);
2635 
2636 audio_io_handle_t aps_open_output_on_module(void *service __unused,
2637                                                    audio_module_handle_t module,
2638                                                    audio_devices_t *pDevices,
2639                                                    uint32_t *pSamplingRate,
2640                                                    audio_format_t *pFormat,
2641                                                    audio_channel_mask_t *pChannelMask,
2642                                                    uint32_t *pLatencyMs,
2643                                                    audio_output_flags_t flags,
2644                                                    const audio_offload_info_t *offloadInfo);
2645 audio_io_handle_t aps_open_dup_output(void *service __unused,
2646                                                  audio_io_handle_t output1,
2647                                                  audio_io_handle_t output2);
2648 int aps_close_output(void *service __unused, audio_io_handle_t output);
2649 int aps_suspend_output(void *service __unused, audio_io_handle_t output);
2650 int aps_restore_output(void *service __unused, audio_io_handle_t output);
2651 audio_io_handle_t aps_open_input(void *service __unused,
2652                                         audio_devices_t *pDevices,
2653                                         uint32_t *pSamplingRate,
2654                                         audio_format_t *pFormat,
2655                                         audio_channel_mask_t *pChannelMask,
2656                                         audio_in_acoustics_t acoustics __unused);
2657 audio_io_handle_t aps_open_input_on_module(void *service __unused,
2658                                                   audio_module_handle_t module,
2659                                                   audio_devices_t *pDevices,
2660                                                   uint32_t *pSamplingRate,
2661                                                   audio_format_t *pFormat,
2662                                                   audio_channel_mask_t *pChannelMask);
2663 int aps_close_input(void *service __unused, audio_io_handle_t input);
2664 int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
2665 int aps_move_effects(void *service __unused, audio_session_t session,
2666                                 audio_io_handle_t src_output,
2667                                 audio_io_handle_t dst_output);
2668 char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
2669                                      const char *keys);
2670 void aps_set_parameters(void *service, audio_io_handle_t io_handle,
2671                                    const char *kv_pairs, int delay_ms);
2672 int aps_set_stream_volume(void *service, audio_stream_type_t stream,
2673                                      float volume, audio_io_handle_t output,
2674                                      int delay_ms);
2675 int aps_set_voice_volume(void *service, float volume, int delay_ms);
2676 };
2677 
2678 } // namespace android
2679