blob: 5fbbc3026e402c17fa7b4530004bf67aa26b1e76 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
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
Glenn Kasten153b9fe2013-07-15 11:23:36 -070020#include "Configuration.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070021#undef __STRICT_ANSI__
22#define __STDINT_LIMITS
23#define __STDC_LIMIT_MACROS
24#include <stdint.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070025#include <sys/time.h>
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053026#include <dlfcn.h>
Mikhail Naganov959e2d02019-03-28 11:08:19 -070027
Atneya Nairdc4f3752023-08-09 16:21:48 -070028#include <android/content/pm/IPackageManagerNative.h>
Mikhail Naganov959e2d02019-03-28 11:08:19 -070029#include <audio_utils/clock.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <binder/IServiceManager.h>
31#include <utils/Log.h>
32#include <cutils/properties.h>
33#include <binder/IPCThreadState.h>
Svet Ganovf4ddfef2018-01-16 07:37:58 -080034#include <binder/PermissionController.h>
35#include <binder/IResultReceiver.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070036#include <utils/String16.h>
37#include <utils/threads.h>
38#include "AudioPolicyService.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070039#include <hardware_legacy/power.h>
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -080040#include <media/AidlConversion.h>
Eric Laurent7c7f10b2011-06-17 21:29:58 -070041#include <media/AudioEffect.h>
Chih-Hung Hsiehc84d9d22014-11-14 13:33:34 -080042#include <media/AudioParameter.h>
Andy Hungc747c532022-03-07 21:41:14 -080043#include <mediautils/MethodStatistics.h>
Andy Hungab7ef302018-05-15 19:35:29 -070044#include <mediautils/ServiceUtilities.h>
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -080045#include <mediautils/TimeCheck.h>
Michael Groovercfd28302018-12-11 19:16:46 -080046#include <sensorprivacy/SensorPrivacyManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070047
Dima Zavin64760242011-05-11 14:15:23 -070048#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070049#include <system/audio_policy.h>
Mikhail Naganov68e3f642023-04-28 13:06:32 -070050#include <AudioPolicyConfig.h>
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053051#include <AudioPolicyManager.h>
Mikhail Naganov61a4fac2016-10-13 14:44:18 -070052
Mathias Agopian65ab4712010-07-14 17:59:35 -070053namespace android {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -080054using binder::Status;
Shunkai Yao79882032023-10-10 19:31:10 +000055using media::audio::common::Spatialization;
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Glenn Kasten8dad0e32012-01-09 08:41:22 -080057static const char kDeadlockedString[] = "AudioPolicyService may be deadlocked\n";
58static const char kCmdDeadlockedString[] = "AudioPolicyService command thread may be deadlocked\n";
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053059static const char kAudioPolicyManagerCustomPath[] = "libaudiopolicymanagercustom.so";
Mathias Agopian65ab4712010-07-14 17:59:35 -070060
Mikhail Naganov959e2d02019-03-28 11:08:19 -070061static const int kDumpLockTimeoutNs = 1 * NANOS_PER_SECOND;
Mathias Agopian65ab4712010-07-14 17:59:35 -070062
Eric Laurent0ede8922014-05-09 18:04:42 -070063static const nsecs_t kAudioCommandTimeoutNs = seconds(3); // 3 seconds
Christer Fletcher5fa8c4b2013-01-18 15:27:03 +010064
Svet Ganovf4ddfef2018-01-16 07:37:58 -080065static const String16 sManageAudioPolicyPermission("android.permission.MANAGE_AUDIO_POLICY");
Dima Zavinfce7a472011-04-19 22:30:36 -070066
Andy Hungc747c532022-03-07 21:41:14 -080067// Creates an association between Binder code to name for IAudioPolicyService.
68#define IAUDIOPOLICYSERVICE_BINDER_METHOD_MACRO_LIST \
69BINDER_METHOD_ENTRY(onNewAudioModulesAvailable) \
70BINDER_METHOD_ENTRY(setDeviceConnectionState) \
71BINDER_METHOD_ENTRY(getDeviceConnectionState) \
72BINDER_METHOD_ENTRY(handleDeviceConfigChange) \
73BINDER_METHOD_ENTRY(setPhoneState) \
74BINDER_METHOD_ENTRY(setForceUse) \
75BINDER_METHOD_ENTRY(getForceUse) \
76BINDER_METHOD_ENTRY(getOutput) \
77BINDER_METHOD_ENTRY(getOutputForAttr) \
78BINDER_METHOD_ENTRY(startOutput) \
79BINDER_METHOD_ENTRY(stopOutput) \
80BINDER_METHOD_ENTRY(releaseOutput) \
81BINDER_METHOD_ENTRY(getInputForAttr) \
82BINDER_METHOD_ENTRY(startInput) \
83BINDER_METHOD_ENTRY(stopInput) \
84BINDER_METHOD_ENTRY(releaseInput) \
85BINDER_METHOD_ENTRY(initStreamVolume) \
86BINDER_METHOD_ENTRY(setStreamVolumeIndex) \
87BINDER_METHOD_ENTRY(getStreamVolumeIndex) \
88BINDER_METHOD_ENTRY(setVolumeIndexForAttributes) \
89BINDER_METHOD_ENTRY(getVolumeIndexForAttributes) \
90BINDER_METHOD_ENTRY(getMaxVolumeIndexForAttributes) \
91BINDER_METHOD_ENTRY(getMinVolumeIndexForAttributes) \
92BINDER_METHOD_ENTRY(getStrategyForStream) \
93BINDER_METHOD_ENTRY(getDevicesForAttributes) \
94BINDER_METHOD_ENTRY(getOutputForEffect) \
95BINDER_METHOD_ENTRY(registerEffect) \
96BINDER_METHOD_ENTRY(unregisterEffect) \
97BINDER_METHOD_ENTRY(setEffectEnabled) \
98BINDER_METHOD_ENTRY(moveEffectsToIo) \
99BINDER_METHOD_ENTRY(isStreamActive) \
100BINDER_METHOD_ENTRY(isStreamActiveRemotely) \
101BINDER_METHOD_ENTRY(isSourceActive) \
102BINDER_METHOD_ENTRY(queryDefaultPreProcessing) \
103BINDER_METHOD_ENTRY(addSourceDefaultEffect) \
104BINDER_METHOD_ENTRY(addStreamDefaultEffect) \
105BINDER_METHOD_ENTRY(removeSourceDefaultEffect) \
106BINDER_METHOD_ENTRY(removeStreamDefaultEffect) \
107BINDER_METHOD_ENTRY(setSupportedSystemUsages) \
108BINDER_METHOD_ENTRY(setAllowedCapturePolicy) \
109BINDER_METHOD_ENTRY(getOffloadSupport) \
110BINDER_METHOD_ENTRY(isDirectOutputSupported) \
111BINDER_METHOD_ENTRY(listAudioPorts) \
112BINDER_METHOD_ENTRY(getAudioPort) \
113BINDER_METHOD_ENTRY(createAudioPatch) \
114BINDER_METHOD_ENTRY(releaseAudioPatch) \
115BINDER_METHOD_ENTRY(listAudioPatches) \
116BINDER_METHOD_ENTRY(setAudioPortConfig) \
117BINDER_METHOD_ENTRY(registerClient) \
118BINDER_METHOD_ENTRY(setAudioPortCallbacksEnabled) \
119BINDER_METHOD_ENTRY(setAudioVolumeGroupCallbacksEnabled) \
120BINDER_METHOD_ENTRY(acquireSoundTriggerSession) \
121BINDER_METHOD_ENTRY(releaseSoundTriggerSession) \
122BINDER_METHOD_ENTRY(getPhoneState) \
123BINDER_METHOD_ENTRY(registerPolicyMixes) \
124BINDER_METHOD_ENTRY(setUidDeviceAffinities) \
125BINDER_METHOD_ENTRY(removeUidDeviceAffinities) \
126BINDER_METHOD_ENTRY(setUserIdDeviceAffinities) \
127BINDER_METHOD_ENTRY(removeUserIdDeviceAffinities) \
128BINDER_METHOD_ENTRY(startAudioSource) \
129BINDER_METHOD_ENTRY(stopAudioSource) \
130BINDER_METHOD_ENTRY(setMasterMono) \
131BINDER_METHOD_ENTRY(getMasterMono) \
132BINDER_METHOD_ENTRY(getStreamVolumeDB) \
133BINDER_METHOD_ENTRY(getSurroundFormats) \
134BINDER_METHOD_ENTRY(getReportedSurroundFormats) \
135BINDER_METHOD_ENTRY(getHwOffloadFormatsSupportedForBluetoothMedia) \
136BINDER_METHOD_ENTRY(setSurroundFormatEnabled) \
137BINDER_METHOD_ENTRY(setAssistantServicesUids) \
138BINDER_METHOD_ENTRY(setActiveAssistantServicesUids) \
139BINDER_METHOD_ENTRY(setA11yServicesUids) \
140BINDER_METHOD_ENTRY(setCurrentImeUid) \
141BINDER_METHOD_ENTRY(isHapticPlaybackSupported) \
142BINDER_METHOD_ENTRY(isUltrasoundSupported) \
Atneya Nair698f5ef2022-12-15 16:15:09 -0800143BINDER_METHOD_ENTRY(isHotwordStreamSupported) \
Andy Hungc747c532022-03-07 21:41:14 -0800144BINDER_METHOD_ENTRY(listAudioProductStrategies) \
145BINDER_METHOD_ENTRY(getProductStrategyFromAudioAttributes) \
146BINDER_METHOD_ENTRY(listAudioVolumeGroups) \
147BINDER_METHOD_ENTRY(getVolumeGroupFromAudioAttributes) \
148BINDER_METHOD_ENTRY(setRttEnabled) \
149BINDER_METHOD_ENTRY(isCallScreenModeSupported) \
150BINDER_METHOD_ENTRY(setDevicesRoleForStrategy) \
151BINDER_METHOD_ENTRY(removeDevicesRoleForStrategy) \
Paul Wang5d7cdb52022-11-22 09:45:06 +0000152BINDER_METHOD_ENTRY(clearDevicesRoleForStrategy) \
Andy Hungc747c532022-03-07 21:41:14 -0800153BINDER_METHOD_ENTRY(getDevicesForRoleAndStrategy) \
154BINDER_METHOD_ENTRY(setDevicesRoleForCapturePreset) \
155BINDER_METHOD_ENTRY(addDevicesRoleForCapturePreset) \
156BINDER_METHOD_ENTRY(removeDevicesRoleForCapturePreset) \
157BINDER_METHOD_ENTRY(clearDevicesRoleForCapturePreset) \
158BINDER_METHOD_ENTRY(getDevicesForRoleAndCapturePreset) \
159BINDER_METHOD_ENTRY(registerSoundTriggerCaptureStateListener) \
160BINDER_METHOD_ENTRY(getSpatializer) \
161BINDER_METHOD_ENTRY(canBeSpatialized) \
162BINDER_METHOD_ENTRY(getDirectPlaybackSupport) \
jiabina84c3d32022-12-02 18:59:55 +0000163BINDER_METHOD_ENTRY(getDirectProfilesForAttributes) \
164BINDER_METHOD_ENTRY(getSupportedMixerAttributes) \
165BINDER_METHOD_ENTRY(setPreferredMixerAttributes) \
166BINDER_METHOD_ENTRY(getPreferredMixerAttributes) \
167BINDER_METHOD_ENTRY(clearPreferredMixerAttributes) \
Andy Hungc747c532022-03-07 21:41:14 -0800168
169// singleton for Binder Method Statistics for IAudioPolicyService
170static auto& getIAudioPolicyServiceStatistics() {
171 using Code = int;
172
173#pragma push_macro("BINDER_METHOD_ENTRY")
174#undef BINDER_METHOD_ENTRY
175#define BINDER_METHOD_ENTRY(ENTRY) \
176 {(Code)media::BnAudioPolicyService::TRANSACTION_##ENTRY, #ENTRY},
177
178 static mediautils::MethodStatistics<Code> methodStatistics{
179 IAUDIOPOLICYSERVICE_BINDER_METHOD_MACRO_LIST
180 METHOD_STATISTICS_BINDER_CODE_NAMES(Code)
181 };
182#pragma pop_macro("BINDER_METHOD_ENTRY")
183
184 return methodStatistics;
185}
186
Mathias Agopian65ab4712010-07-14 17:59:35 -0700187// ----------------------------------------------------------------------------
188
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530189static AudioPolicyInterface* createAudioPolicyManager(AudioPolicyClientInterface *clientInterface)
190{
Mikhail Naganov741c3472023-05-05 17:36:39 -0700191 AudioPolicyManager *apm = nullptr;
192 media::AudioPolicyConfig apmConfig;
193 if (status_t status = clientInterface->getAudioPolicyConfig(&apmConfig); status == OK) {
194 auto config = AudioPolicyConfig::loadFromApmAidlConfigWithFallback(apmConfig);
195 LOG_ALWAYS_FATAL_IF(config->getEngineLibraryNameSuffix() !=
196 AudioPolicyConfig::kDefaultEngineLibraryNameSuffix,
197 "Only default engine is currently supported with the AIDL HAL");
198 apm = new AudioPolicyManager(config,
199 loadApmEngineLibraryAndCreateEngine(
200 config->getEngineLibraryNameSuffix(), apmConfig.engineConfig),
201 clientInterface);
202 } else {
203 auto config = AudioPolicyConfig::loadFromApmXmlConfigWithFallback(); // This can't fail.
204 apm = new AudioPolicyManager(config,
205 loadApmEngineLibraryAndCreateEngine(config->getEngineLibraryNameSuffix()),
206 clientInterface);
207 }
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530208 status_t status = apm->initialize();
209 if (status != NO_ERROR) {
210 delete apm;
211 apm = nullptr;
212 }
213 return apm;
214}
215
216static void destroyAudioPolicyManager(AudioPolicyInterface *interface)
217{
218 delete interface;
219}
Atneya Nairdc4f3752023-08-09 16:21:48 -0700220
221namespace {
222int getTargetSdkForPackageName(std::string_view packageName) {
223 const auto binder = defaultServiceManager()->checkService(String16{"package_native"});
224 int targetSdk = -1;
225 if (binder != nullptr) {
226 const auto pm = interface_cast<content::pm::IPackageManagerNative>(binder);
227 if (pm != nullptr) {
228 const auto status = pm->getTargetSdkVersionForPackage(
229 String16{packageName.data(), packageName.size()}, &targetSdk);
230 ALOGI("Capy check package %s, sdk %d", packageName.data(), targetSdk);
231 return status.isOk() ? targetSdk : -1;
232 }
233 }
234 return targetSdk;
235}
236
237bool doesPackageTargetAtLeastU(std::string_view packageName) {
238 return getTargetSdkForPackageName(packageName) >= __ANDROID_API_U__;
239}
240} // anonymous
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530241// ----------------------------------------------------------------------------
242
Mathias Agopian65ab4712010-07-14 17:59:35 -0700243AudioPolicyService::AudioPolicyService()
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -0700244 : BnAudioPolicyService(),
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -0700245 mAudioPolicyManager(NULL),
246 mAudioPolicyClient(NULL),
247 mPhoneState(AUDIO_MODE_INVALID),
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530248 mCaptureStateNotifier(false),
249 mCreateAudioPolicyManager(createAudioPolicyManager),
Eric Laurent0d13fea2022-11-04 17:12:08 +0100250 mDestroyAudioPolicyManager(destroyAudioPolicyManager),
251 mUsecaseValidator(media::createUsecaseValidator()) {
Andy Hung225aef62022-12-06 16:33:20 -0800252 setMinSchedulerPolicy(SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530253}
254
255void AudioPolicyService::loadAudioPolicyManager()
256{
257 mLibraryHandle = dlopen(kAudioPolicyManagerCustomPath, RTLD_NOW);
258 if (mLibraryHandle != nullptr) {
259 ALOGI("%s loading %s", __func__, kAudioPolicyManagerCustomPath);
260 mCreateAudioPolicyManager = reinterpret_cast<CreateAudioPolicyManagerInstance>
261 (dlsym(mLibraryHandle, "createAudioPolicyManager"));
262 const char *lastError = dlerror();
263 ALOGW_IF(mCreateAudioPolicyManager == nullptr, "%s createAudioPolicyManager is null %s",
264 __func__, lastError != nullptr ? lastError : "no error");
265
266 mDestroyAudioPolicyManager = reinterpret_cast<DestroyAudioPolicyManagerInstance>(
267 dlsym(mLibraryHandle, "destroyAudioPolicyManager"));
268 lastError = dlerror();
269 ALOGW_IF(mDestroyAudioPolicyManager == nullptr, "%s destroyAudioPolicyManager is null %s",
270 __func__, lastError != nullptr ? lastError : "no error");
271 if (mCreateAudioPolicyManager == nullptr || mDestroyAudioPolicyManager == nullptr){
272 unloadAudioPolicyManager();
273 LOG_ALWAYS_FATAL("could not find audiopolicymanager interface methods");
274 }
275 }
Eric Laurentf5ada6e2014-10-09 17:49:00 -0700276}
277
278void AudioPolicyService::onFirstRef()
279{
Andy Hungd47aca22022-03-15 11:50:51 -0700280 // Log an AudioPolicy "constructor" mediametrics event on first ref.
281 // This records the time it takes to load the audio modules and devices.
282 mediametrics::Defer defer([beginNs = systemTime()] {
283 mediametrics::LogItem(AMEDIAMETRICS_KEY_AUDIO_POLICY)
284 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CTOR)
285 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
286 .record(); });
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700287 {
288 Mutex::Autolock _l(mLock);
Eric Laurent93575202011-01-18 18:39:02 -0800289
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700290 // start audio commands thread
291 mAudioCommandThread = new AudioCommandThread(String8("ApmAudio"), this);
292 // start output activity command thread
293 mOutputCommandThread = new AudioCommandThread(String8("ApmOutput"), this);
Eric Laurentdce54a12014-03-10 12:19:46 -0700294
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700295 mAudioPolicyClient = new AudioPolicyClient(this);
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530296
297 loadAudioPolicyManager();
298 mAudioPolicyManager = mCreateAudioPolicyManager(mAudioPolicyClient);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700299 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200300
bryant_liuba2b4392014-06-11 16:49:30 +0800301 // load audio processing modules
Shunkai Yao8d6489a2023-04-18 23:14:25 +0000302 const sp<EffectsFactoryHalInterface> effectsFactoryHal = EffectsFactoryHalInterface::create();
303 sp<AudioPolicyEffects> audioPolicyEffects = new AudioPolicyEffects(effectsFactoryHal);
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000304 sp<UidPolicy> uidPolicy = new UidPolicy(this);
305 sp<SensorPrivacyPolicy> sensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700306 {
307 Mutex::Autolock _l(mLock);
308 mAudioPolicyEffects = audioPolicyEffects;
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000309 mUidPolicy = uidPolicy;
310 mSensorPrivacyPolicy = sensorPrivacyPolicy;
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700311 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000312 uidPolicy->registerSelf();
313 sensorPrivacyPolicy->registerSelf();
Eric Laurentd66d7a12021-07-13 13:35:32 +0200314
Eric Laurent81dd0f52021-07-05 11:54:40 +0200315 // Create spatializer if supported
Eric Laurent52b0bd52021-09-27 15:25:40 +0200316 if (mAudioPolicyManager != nullptr) {
317 Mutex::Autolock _l(mLock);
318 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
319 AudioDeviceTypeAddrVector devices;
320 bool hasSpatializer = mAudioPolicyManager->canBeSpatialized(&attr, nullptr, devices);
321 if (hasSpatializer) {
Shunkai Yao8d6489a2023-04-18 23:14:25 +0000322 mSpatializer = Spatializer::create(this, effectsFactoryHal);
Eric Laurent52b0bd52021-09-27 15:25:40 +0200323 }
Andy Hung8aa43c02022-09-13 18:53:06 -0700324 if (mSpatializer == nullptr) {
325 // No spatializer created, signal the reason: NO_INIT a failure, OK means intended.
326 const status_t createStatus = hasSpatializer ? NO_INIT : OK;
327 Spatializer::sendEmptyCreateSpatializerMetricWithStatus(createStatus);
328 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200329 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200330 AudioSystem::audioPolicyReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700331}
332
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530333void AudioPolicyService::unloadAudioPolicyManager()
334{
335 ALOGV("%s ", __func__);
336 if (mLibraryHandle != nullptr) {
337 dlclose(mLibraryHandle);
338 }
339 mLibraryHandle = nullptr;
340 mCreateAudioPolicyManager = nullptr;
341 mDestroyAudioPolicyManager = nullptr;
342}
343
Mathias Agopian65ab4712010-07-14 17:59:35 -0700344AudioPolicyService::~AudioPolicyService()
345{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700346 mAudioCommandThread->exit();
Eric Laurent657ff612014-05-07 11:58:24 -0700347 mOutputCommandThread->exit();
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700348
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530349 mDestroyAudioPolicyManager(mAudioPolicyManager);
350 unloadAudioPolicyManager();
351
Eric Laurentdce54a12014-03-10 12:19:46 -0700352 delete mAudioPolicyClient;
Eric Laurentb52c1522014-05-20 11:27:36 -0700353
354 mNotificationClients.clear();
bryant_liuba2b4392014-06-11 16:49:30 +0800355 mAudioPolicyEffects.clear();
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800356
357 mUidPolicy->unregisterSelf();
Michael Groovercfd28302018-12-11 19:16:46 -0800358 mSensorPrivacyPolicy->unregisterSelf();
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000359
360 mUidPolicy.clear();
Michael Groovercfd28302018-12-11 19:16:46 -0800361 mSensorPrivacyPolicy.clear();
Eric Laurentb52c1522014-05-20 11:27:36 -0700362}
363
364// A notification client is always registered by AudioSystem when the client process
365// connects to AudioPolicyService.
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800366Status AudioPolicyService::registerClient(const sp<media::IAudioPolicyServiceClient>& client)
Eric Laurentb52c1522014-05-20 11:27:36 -0700367{
Eric Laurent12590252015-08-21 18:40:20 -0700368 if (client == 0) {
369 ALOGW("%s got NULL client", __FUNCTION__);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800370 return Status::ok();
Eric Laurent12590252015-08-21 18:40:20 -0700371 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800372 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700373
374 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800375 pid_t pid = IPCThreadState::self()->getCallingPid();
376 int64_t token = ((int64_t)uid<<32) | pid;
377
378 if (mNotificationClients.indexOfKey(token) < 0) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700379 sp<NotificationClient> notificationClient = new NotificationClient(this,
380 client,
luochaojiang908c7d72018-06-21 14:58:04 +0800381 uid,
382 pid);
383 ALOGV("registerClient() client %p, uid %d pid %d", client.get(), uid, pid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700384
luochaojiang908c7d72018-06-21 14:58:04 +0800385 mNotificationClients.add(token, notificationClient);
Eric Laurentb52c1522014-05-20 11:27:36 -0700386
Marco Nelissenf8880202014-11-14 07:58:25 -0800387 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurentb52c1522014-05-20 11:27:36 -0700388 binder->linkToDeath(notificationClient);
389 }
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800390 return Status::ok();
Eric Laurentb52c1522014-05-20 11:27:36 -0700391}
392
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800393Status AudioPolicyService::setAudioPortCallbacksEnabled(bool enabled)
Eric Laurente8726fe2015-06-26 09:39:24 -0700394{
395 Mutex::Autolock _l(mNotificationClientsLock);
396
397 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800398 pid_t pid = IPCThreadState::self()->getCallingPid();
399 int64_t token = ((int64_t)uid<<32) | pid;
400
401 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800402 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700403 }
luochaojiang908c7d72018-06-21 14:58:04 +0800404 mNotificationClients.valueFor(token)->setAudioPortCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800405 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700406}
407
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800408Status AudioPolicyService::setAudioVolumeGroupCallbacksEnabled(bool enabled)
François Gaffiecfe17322018-11-07 13:41:29 +0100409{
410 Mutex::Autolock _l(mNotificationClientsLock);
411
412 uid_t uid = IPCThreadState::self()->getCallingUid();
413 pid_t pid = IPCThreadState::self()->getCallingPid();
414 int64_t token = ((int64_t)uid<<32) | pid;
415
416 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800417 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100418 }
419 mNotificationClients.valueFor(token)->setAudioVolumeGroupCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800420 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100421}
422
Eric Laurentb52c1522014-05-20 11:27:36 -0700423// removeNotificationClient() is called when the client process dies.
luochaojiang908c7d72018-06-21 14:58:04 +0800424void AudioPolicyService::removeNotificationClient(uid_t uid, pid_t pid)
Eric Laurentb52c1522014-05-20 11:27:36 -0700425{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000426 bool hasSameUid = false;
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800427 {
428 Mutex::Autolock _l(mNotificationClientsLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800429 int64_t token = ((int64_t)uid<<32) | pid;
430 mNotificationClients.removeItem(token);
luochaojiang908c7d72018-06-21 14:58:04 +0800431 for (size_t i = 0; i < mNotificationClients.size(); i++) {
432 if (mNotificationClients.valueAt(i)->uid() == uid) {
433 hasSameUid = true;
434 break;
435 }
436 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000437 }
438 {
439 Mutex::Autolock _l(mLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800440 if (mAudioPolicyManager && !hasSameUid) {
Eric Laurent10b71232018-04-13 18:14:44 -0700441 // called from binder death notification: no need to clear caller identity
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700442 mAudioPolicyManager->releaseResourcesForUid(uid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700443 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800444 }
Eric Laurentb52c1522014-05-20 11:27:36 -0700445}
446
447void AudioPolicyService::onAudioPortListUpdate()
448{
449 mOutputCommandThread->updateAudioPortListCommand();
450}
451
452void AudioPolicyService::doOnAudioPortListUpdate()
453{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800454 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700455 for (size_t i = 0; i < mNotificationClients.size(); i++) {
456 mNotificationClients.valueAt(i)->onAudioPortListUpdate();
457 }
458}
459
460void AudioPolicyService::onAudioPatchListUpdate()
461{
462 mOutputCommandThread->updateAudioPatchListCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700463}
464
Eric Laurentb52c1522014-05-20 11:27:36 -0700465void AudioPolicyService::doOnAudioPatchListUpdate()
466{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800467 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700468 for (size_t i = 0; i < mNotificationClients.size(); i++) {
469 mNotificationClients.valueAt(i)->onAudioPatchListUpdate();
470 }
471}
472
François Gaffiecfe17322018-11-07 13:41:29 +0100473void AudioPolicyService::onAudioVolumeGroupChanged(volume_group_t group, int flags)
474{
475 mOutputCommandThread->changeAudioVolumeGroupCommand(group, flags);
476}
477
478void AudioPolicyService::doOnAudioVolumeGroupChanged(volume_group_t group, int flags)
479{
480 Mutex::Autolock _l(mNotificationClientsLock);
481 for (size_t i = 0; i < mNotificationClients.size(); i++) {
482 mNotificationClients.valueAt(i)->onAudioVolumeGroupChanged(group, flags);
483 }
484}
485
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700486void AudioPolicyService::onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700487{
488 ALOGV("AudioPolicyService::onDynamicPolicyMixStateUpdate(%s, %d)",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +0000489 regId.c_str(), state);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700490 mOutputCommandThread->dynamicPolicyMixStateUpdateCommand(regId, state);
491}
492
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700493void AudioPolicyService::doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700494{
495 Mutex::Autolock _l(mNotificationClientsLock);
496 for (size_t i = 0; i < mNotificationClients.size(); i++) {
497 mNotificationClients.valueAt(i)->onDynamicPolicyMixStateUpdate(regId, state);
498 }
499}
500
Eric Laurenta9f86652018-11-28 17:23:11 -0800501void AudioPolicyService::onRecordingConfigurationUpdate(
502 int event,
503 const record_client_info_t *clientInfo,
504 const audio_config_base_t *clientConfig,
505 std::vector<effect_descriptor_t> clientEffects,
506 const audio_config_base_t *deviceConfig,
507 std::vector<effect_descriptor_t> effects,
508 audio_patch_handle_t patchHandle,
509 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800510{
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800511 mOutputCommandThread->recordingConfigurationUpdateCommand(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800512 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800513}
514
Eric Laurenta9f86652018-11-28 17:23:11 -0800515void AudioPolicyService::doOnRecordingConfigurationUpdate(
516 int event,
517 const record_client_info_t *clientInfo,
518 const audio_config_base_t *clientConfig,
519 std::vector<effect_descriptor_t> clientEffects,
520 const audio_config_base_t *deviceConfig,
521 std::vector<effect_descriptor_t> effects,
522 audio_patch_handle_t patchHandle,
523 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800524{
525 Mutex::Autolock _l(mNotificationClientsLock);
526 for (size_t i = 0; i < mNotificationClients.size(); i++) {
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800527 mNotificationClients.valueAt(i)->onRecordingConfigurationUpdate(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800528 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800529 }
530}
531
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700532void AudioPolicyService::onRoutingUpdated()
533{
534 mOutputCommandThread->routingChangedCommand();
535}
536
537void AudioPolicyService::doOnRoutingUpdated()
538{
539 Mutex::Autolock _l(mNotificationClientsLock);
540 for (size_t i = 0; i < mNotificationClients.size(); i++) {
541 mNotificationClients.valueAt(i)->onRoutingUpdated();
542 }
543}
544
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000545void AudioPolicyService::onVolumeRangeInitRequest()
546{
547 mOutputCommandThread->volRangeInitReqCommand();
548}
549
550void AudioPolicyService::doOnVolumeRangeInitRequest()
551{
552 Mutex::Autolock _l(mNotificationClientsLock);
553 for (size_t i = 0; i < mNotificationClients.size(); i++) {
554 mNotificationClients.valueAt(i)->onVolumeRangeInitRequest();
555 }
556}
557
Eric Laurent81dd0f52021-07-05 11:54:40 +0200558void AudioPolicyService::onCheckSpatializer()
559{
560 Mutex::Autolock _l(mLock);
Eric Laurent39095982021-08-24 18:29:27 +0200561 onCheckSpatializer_l();
562}
563
564void AudioPolicyService::onCheckSpatializer_l()
565{
566 if (mSpatializer != nullptr) {
567 mOutputCommandThread->checkSpatializerCommand();
568 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200569}
570
571void AudioPolicyService::doOnCheckSpatializer()
572{
Eric Laurentd6bee3a2022-08-31 16:07:50 +0200573 ALOGV("%s mSpatializer %p level %d",
574 __func__, mSpatializer.get(), (int)mSpatializer->getLevel());
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200575
Eric Laurent39095982021-08-24 18:29:27 +0200576 if (mSpatializer != nullptr) {
Eric Laurent52b0bd52021-09-27 15:25:40 +0200577 // Note: mSpatializer != nullptr => mAudioPolicyManager != nullptr
Shunkai Yao79882032023-10-10 19:31:10 +0000578 if (mSpatializer->getLevel() != Spatialization::Level::NONE) {
Eric Laurent39095982021-08-24 18:29:27 +0200579 audio_io_handle_t currentOutput = mSpatializer->getOutput();
580 audio_io_handle_t newOutput;
581 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
582 audio_config_base_t config = mSpatializer->getAudioInConfig();
Eric Laurent21270b62022-07-04 15:11:29 +0200583
584 Mutex::Autolock _l(mLock);
Eric Laurent39095982021-08-24 18:29:27 +0200585 status_t status =
586 mAudioPolicyManager->getSpatializerOutput(&config, &attr, &newOutput);
Eric Laurentb4f42a92022-01-17 17:37:31 +0100587 ALOGV("%s currentOutput %d newOutput %d channel_mask %#x",
588 __func__, currentOutput, newOutput, config.channel_mask);
Eric Laurent39095982021-08-24 18:29:27 +0200589 if (status == NO_ERROR && currentOutput == newOutput) {
590 return;
591 }
Eric Laurent15903592022-02-24 20:44:36 +0100592 size_t numActiveTracks = countActiveClientsOnOutput_l(newOutput);
Eric Laurent39095982021-08-24 18:29:27 +0200593 mLock.unlock();
594 // It is OK to call detachOutput() is none is already attached.
595 mSpatializer->detachOutput();
Eric Laurent21270b62022-07-04 15:11:29 +0200596 if (status == NO_ERROR && newOutput != AUDIO_IO_HANDLE_NONE) {
597 status = mSpatializer->attachOutput(newOutput, numActiveTracks);
Eric Laurent39095982021-08-24 18:29:27 +0200598 }
Eric Laurent39095982021-08-24 18:29:27 +0200599 mLock.lock();
600 if (status != NO_ERROR) {
601 mAudioPolicyManager->releaseSpatializerOutput(newOutput);
602 }
Shunkai Yao79882032023-10-10 19:31:10 +0000603 } else if (mSpatializer->getLevel() == Spatialization::Level::NONE &&
604 mSpatializer->getOutput() != AUDIO_IO_HANDLE_NONE) {
Eric Laurent39095982021-08-24 18:29:27 +0200605 audio_io_handle_t output = mSpatializer->detachOutput();
Eric Laurent21270b62022-07-04 15:11:29 +0200606
Eric Laurent39095982021-08-24 18:29:27 +0200607 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurent21270b62022-07-04 15:11:29 +0200608 Mutex::Autolock _l(mLock);
Eric Laurent39095982021-08-24 18:29:27 +0200609 mAudioPolicyManager->releaseSpatializerOutput(output);
Eric Laurent81dd0f52021-07-05 11:54:40 +0200610 }
611 }
612 }
613}
614
Eric Laurent11094172022-04-05 18:27:42 +0200615size_t AudioPolicyService::countActiveClientsOnOutput_l(
616 audio_io_handle_t output, bool spatializedOnly) {
Eric Laurent15903592022-02-24 20:44:36 +0100617 size_t count = 0;
618 for (size_t i = 0; i < mAudioPlaybackClients.size(); i++) {
619 auto client = mAudioPlaybackClients.valueAt(i);
Eric Laurent11094172022-04-05 18:27:42 +0200620 if (client->io == output && client->active
621 && (!spatializedOnly || client->isSpatialized)) {
Eric Laurent15903592022-02-24 20:44:36 +0100622 count++;
623 }
624 }
625 return count;
626}
627
628void AudioPolicyService::onUpdateActiveSpatializerTracks_l() {
629 if (mSpatializer == nullptr) {
630 return;
631 }
632 mOutputCommandThread->updateActiveSpatializerTracksCommand();
633}
634
635void AudioPolicyService::doOnUpdateActiveSpatializerTracks()
636{
Eric Laurent21270b62022-07-04 15:11:29 +0200637 if (mSpatializer == nullptr) {
638 return;
639 }
640 audio_io_handle_t output = mSpatializer->getOutput();
Eric Laurent7ea0d1b2022-04-01 14:23:44 +0200641 size_t activeClients;
642 {
643 Mutex::Autolock _l(mLock);
Eric Laurent21270b62022-07-04 15:11:29 +0200644 activeClients = countActiveClientsOnOutput_l(output);
Eric Laurent15903592022-02-24 20:44:36 +0100645 }
Eric Laurent21270b62022-07-04 15:11:29 +0200646 mSpatializer->updateActiveTracks(activeClients);
Eric Laurent15903592022-02-24 20:44:36 +0100647}
648
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800649status_t AudioPolicyService::clientCreateAudioPatch(const struct audio_patch *patch,
650 audio_patch_handle_t *handle,
651 int delayMs)
652{
653 return mAudioCommandThread->createAudioPatchCommand(patch, handle, delayMs);
654}
655
656status_t AudioPolicyService::clientReleaseAudioPatch(audio_patch_handle_t handle,
657 int delayMs)
658{
659 return mAudioCommandThread->releaseAudioPatchCommand(handle, delayMs);
660}
661
Eric Laurente1715a42014-05-20 11:30:42 -0700662status_t AudioPolicyService::clientSetAudioPortConfig(const struct audio_port_config *config,
663 int delayMs)
664{
665 return mAudioCommandThread->setAudioPortConfigCommand(config, delayMs);
666}
667
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800668AudioPolicyService::NotificationClient::NotificationClient(
669 const sp<AudioPolicyService>& service,
670 const sp<media::IAudioPolicyServiceClient>& client,
671 uid_t uid,
672 pid_t pid)
luochaojiang908c7d72018-06-21 14:58:04 +0800673 : mService(service), mUid(uid), mPid(pid), mAudioPolicyServiceClient(client),
François Gaffiecfe17322018-11-07 13:41:29 +0100674 mAudioPortCallbacksEnabled(false), mAudioVolumeGroupCallbacksEnabled(false)
Eric Laurentb52c1522014-05-20 11:27:36 -0700675{
676}
677
678AudioPolicyService::NotificationClient::~NotificationClient()
679{
680}
681
682void AudioPolicyService::NotificationClient::binderDied(const wp<IBinder>& who __unused)
683{
684 sp<NotificationClient> keep(this);
685 sp<AudioPolicyService> service = mService.promote();
686 if (service != 0) {
luochaojiang908c7d72018-06-21 14:58:04 +0800687 service->removeNotificationClient(mUid, mPid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700688 }
689}
690
691void AudioPolicyService::NotificationClient::onAudioPortListUpdate()
692{
Eric Laurente8726fe2015-06-26 09:39:24 -0700693 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700694 mAudioPolicyServiceClient->onAudioPortListUpdate();
695 }
696}
697
698void AudioPolicyService::NotificationClient::onAudioPatchListUpdate()
699{
Eric Laurente8726fe2015-06-26 09:39:24 -0700700 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700701 mAudioPolicyServiceClient->onAudioPatchListUpdate();
702 }
703}
Eric Laurent57dae992011-07-24 13:36:09 -0700704
Pattydd807582021-11-04 21:01:03 +0800705void AudioPolicyService::NotificationClient::onAudioVolumeGroupChanged(volume_group_t group,
François Gaffiecfe17322018-11-07 13:41:29 +0100706 int flags)
707{
708 if (mAudioPolicyServiceClient != 0 && mAudioVolumeGroupCallbacksEnabled) {
709 mAudioPolicyServiceClient->onAudioVolumeGroupChanged(group, flags);
710 }
711}
712
713
Jean-Michel Trivide801052015-04-14 19:10:14 -0700714void AudioPolicyService::NotificationClient::onDynamicPolicyMixStateUpdate(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700715 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700716{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700717 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800718 mAudioPolicyServiceClient->onDynamicPolicyMixStateUpdate(
719 legacy2aidl_String8_string(regId).value(), state);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800720 }
721}
722
723void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate(
Eric Laurenta9f86652018-11-28 17:23:11 -0800724 int event,
725 const record_client_info_t *clientInfo,
726 const audio_config_base_t *clientConfig,
727 std::vector<effect_descriptor_t> clientEffects,
728 const audio_config_base_t *deviceConfig,
729 std::vector<effect_descriptor_t> effects,
730 audio_patch_handle_t patchHandle,
731 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800732{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700733 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800734 status_t status = [&]() -> status_t {
735 int32_t eventAidl = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(event));
736 media::RecordClientInfo clientInfoAidl = VALUE_OR_RETURN_STATUS(
737 legacy2aidl_record_client_info_t_RecordClientInfo(*clientInfo));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700738 AudioConfigBase clientConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700739 legacy2aidl_audio_config_base_t_AudioConfigBase(
740 *clientConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800741 std::vector<media::EffectDescriptor> clientEffectsAidl = VALUE_OR_RETURN_STATUS(
742 convertContainer<std::vector<media::EffectDescriptor>>(
743 clientEffects,
744 legacy2aidl_effect_descriptor_t_EffectDescriptor));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700745 AudioConfigBase deviceConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700746 legacy2aidl_audio_config_base_t_AudioConfigBase(
747 *deviceConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800748 std::vector<media::EffectDescriptor> effectsAidl = VALUE_OR_RETURN_STATUS(
749 convertContainer<std::vector<media::EffectDescriptor>>(
750 effects,
751 legacy2aidl_effect_descriptor_t_EffectDescriptor));
752 int32_t patchHandleAidl = VALUE_OR_RETURN_STATUS(
753 legacy2aidl_audio_patch_handle_t_int32_t(patchHandle));
Mikhail Naganovddceecc2021-09-03 13:58:56 -0700754 media::audio::common::AudioSource sourceAidl = VALUE_OR_RETURN_STATUS(
755 legacy2aidl_audio_source_t_AudioSource(source));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800756 return aidl_utils::statusTFromBinderStatus(
757 mAudioPolicyServiceClient->onRecordingConfigurationUpdate(eventAidl,
758 clientInfoAidl,
759 clientConfigAidl,
760 clientEffectsAidl,
761 deviceConfigAidl,
762 effectsAidl,
763 patchHandleAidl,
764 sourceAidl));
765 }();
766 ALOGW_IF(status != OK, "onRecordingConfigurationUpdate() failed: %d", status);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700767 }
768}
769
Eric Laurente8726fe2015-06-26 09:39:24 -0700770void AudioPolicyService::NotificationClient::setAudioPortCallbacksEnabled(bool enabled)
771{
772 mAudioPortCallbacksEnabled = enabled;
773}
774
François Gaffiecfe17322018-11-07 13:41:29 +0100775void AudioPolicyService::NotificationClient::setAudioVolumeGroupCallbacksEnabled(bool enabled)
776{
777 mAudioVolumeGroupCallbacksEnabled = enabled;
778}
Eric Laurente8726fe2015-06-26 09:39:24 -0700779
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700780void AudioPolicyService::NotificationClient::onRoutingUpdated()
781{
782 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
783 mAudioPolicyServiceClient->onRoutingUpdated();
784 }
785}
786
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000787void AudioPolicyService::NotificationClient::onVolumeRangeInitRequest()
788{
789 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
790 mAudioPolicyServiceClient->onVolumeRangeInitRequest();
791 }
792}
793
Mathias Agopian65ab4712010-07-14 17:59:35 -0700794void AudioPolicyService::binderDied(const wp<IBinder>& who) {
Glenn Kasten411e4472012-11-02 10:00:06 -0700795 ALOGW("binderDied() %p, calling pid %d", who.unsafe_get(),
Eric Laurentde070132010-07-13 04:45:46 -0700796 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700797}
798
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000799static bool dumpTryLock(Mutex& mutex) ACQUIRE(mutex) NO_THREAD_SAFETY_ANALYSIS
Mathias Agopian65ab4712010-07-14 17:59:35 -0700800{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000801 return mutex.timedLock(kDumpLockTimeoutNs) == NO_ERROR;
802}
803
804static void dumpReleaseLock(Mutex& mutex, bool locked) RELEASE(mutex) NO_THREAD_SAFETY_ANALYSIS
805{
806 if (locked) mutex.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700807}
808
809status_t AudioPolicyService::dumpInternals(int fd)
810{
811 const size_t SIZE = 256;
812 char buffer[SIZE];
813 String8 result;
814
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000815 snprintf(buffer, SIZE, "Supported System Usages:\n ");
Hayden Gomes524159d2019-12-23 14:41:47 -0800816 result.append(buffer);
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000817 std::stringstream msg;
818 size_t i = 0;
819 for (auto usage : mSupportedSystemUsages) {
820 if (i++ != 0) msg << ", ";
821 if (const char* strUsage = audio_usage_to_string(usage); strUsage) {
822 msg << strUsage;
823 } else {
824 msg << usage << " (unknown)";
825 }
Hayden Gomes524159d2019-12-23 14:41:47 -0800826 }
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000827 if (i == 0) {
828 msg << "None";
829 }
830 msg << std::endl;
831 result.append(msg.str().c_str());
Hayden Gomes524159d2019-12-23 14:41:47 -0800832
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +0000833 write(fd, result.c_str(), result.size());
Oscar Azucena829d90d2022-01-28 17:17:56 -0800834
835 mUidPolicy->dumpInternals(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700836 return NO_ERROR;
837}
838
Eric Laurente8c8b432018-10-17 10:08:02 -0700839void AudioPolicyService::updateUidStates()
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800840{
Eric Laurente8c8b432018-10-17 10:08:02 -0700841 Mutex::Autolock _l(mLock);
842 updateUidStates_l();
843}
844
845void AudioPolicyService::updateUidStates_l()
846{
Eric Laurent4eb58f12018-12-07 16:41:02 -0800847// Go over all active clients and allow capture (does not force silence) in the
848// following cases:
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800849// The client is in the active assistant list
850// AND is TOP
851// AND an accessibility service is TOP
852// AND source is either VOICE_RECOGNITION OR HOTWORD
853// OR there is no active privacy sensitive capture or call
854// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
855// AND source is VOICE_RECOGNITION OR HOTWORD
856// The client is an assistant AND active assistant is not being used
Evan Severson1f700cd2021-02-10 13:10:37 -0800857// AND an accessibility service is on TOP or a RTT call is active
Eric Laurent589171c2019-07-25 18:04:29 -0700858// AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800859// OR there is no active privacy sensitive capture or call
Evan Severson1f700cd2021-02-10 13:10:37 -0800860// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800861// AND is TOP most recent assistant and uses VOICE_RECOGNITION or HOTWORD
862// OR there is no top recent assistant and source is HOTWORD
Evan Severson1f700cd2021-02-10 13:10:37 -0800863// OR The client is an accessibility service
864// AND Is on TOP
865// AND the source is VOICE_RECOGNITION or HOTWORD
866// OR The assistant is not on TOP
Eric Laurent589171c2019-07-25 18:04:29 -0700867// AND there is no active privacy sensitive capture or call
868// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Evan Severson1f700cd2021-02-10 13:10:37 -0800869// AND is on TOP
870// AND the source is VOICE_RECOGNITION or HOTWORD
871// OR the client source is virtual (remote submix, call audio TX or RX...)
872// OR the client source is HOTWORD
873// AND is on TOP
874// OR all active clients are using HOTWORD source
875// AND no call is active
876// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
877// OR the client is the current InputMethodService
878// AND a RTT call is active AND the source is VOICE_RECOGNITION
879// OR Any client
880// AND The assistant is not on TOP
881// AND is on TOP or latest started
882// AND there is no active privacy sensitive capture or call
883// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4eb58f12018-12-07 16:41:02 -0800884
Eric Laurent4e947da2019-10-17 15:24:06 -0700885
Eric Laurent4eb58f12018-12-07 16:41:02 -0800886 sp<AudioRecordClient> topActive;
887 sp<AudioRecordClient> latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800888 sp<AudioRecordClient> topSensitiveActive;
Eric Laurentb809a752020-06-29 09:53:13 -0700889 sp<AudioRecordClient> latestSensitiveActiveOrComm;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800890 sp<AudioRecordClient> latestActiveAssistant;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700891
Eric Laurenta46bedb2018-12-07 18:01:26 -0800892 nsecs_t topStartNs = 0;
893 nsecs_t latestStartNs = 0;
Eric Laurentc21d5692020-02-25 10:24:36 -0800894 nsecs_t topSensitiveStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800895 nsecs_t latestSensitiveStartNs = 0;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800896 nsecs_t latestAssistantStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800897 bool isA11yOnTop = mUidPolicy->isA11yOnTop();
898 bool isAssistantOnTop = false;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800899 bool useActiveAssistantList = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800900 bool isSensitiveActive = false;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700901 bool isInCall = mPhoneState == AUDIO_MODE_IN_CALL;
Eric Laurentc21d5692020-02-25 10:24:36 -0800902 bool isInCommunication = mPhoneState == AUDIO_MODE_IN_COMMUNICATION;
903 bool rttCallActive = (isInCall || isInCommunication)
Eric Laurent6ede98f2019-06-11 14:50:30 -0700904 && mUidPolicy->isRttEnabled();
Eric Laurent4e947da2019-10-17 15:24:06 -0700905 bool onlyHotwordActive = true;
Eric Laurentb809a752020-06-29 09:53:13 -0700906 bool isPhoneStateOwnerActive = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800907
Michael Groovercfd28302018-12-11 19:16:46 -0800908 // if Sensor Privacy is enabled then all recordings should be silenced.
909 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
910 silenceAllRecordings_l();
911 return;
912 }
913
Eric Laurente8c8b432018-10-17 10:08:02 -0700914 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
915 sp<AudioRecordClient> current = mAudioRecordClients[i];
Svet Ganov33761132021-05-13 22:51:08 +0000916 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
917 current->attributionSource.uid));
Evan Severson1f700cd2021-02-10 13:10:37 -0800918 if (!current->active) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700919 continue;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800920 }
Eric Laurent1ff16a72019-03-14 18:35:04 -0700921
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700922 app_state_t appState = apmStatFromAmState(mUidPolicy->getUidState(currentUid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700923 // clients which app is in IDLE state are not eligible for top active or
924 // latest active
925 if (appState == APP_STATE_IDLE) {
926 continue;
927 }
928
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700929 bool isAccessibility = mUidPolicy->isA11yUid(currentUid);
Eric Laurent14a88632020-07-16 12:28:30 -0700930 // Clients capturing for Accessibility services or virtual sources are not considered
Eric Laurentc21d5692020-02-25 10:24:36 -0800931 // for top or latest active to avoid masking regular clients started before
Eric Laurent14a88632020-07-16 12:28:30 -0700932 if (!isAccessibility && !isVirtualSource(current->attributes.source)) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700933 bool isAssistant = mUidPolicy->isAssistantUid(currentUid);
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800934 bool isActiveAssistant = mUidPolicy->isActiveAssistantUid(currentUid);
Eric Laurentc21d5692020-02-25 10:24:36 -0800935 bool isPrivacySensitive =
936 (current->attributes.flags & AUDIO_FLAG_CAPTURE_PRIVATE) != 0;
Eric Laurentb809a752020-06-29 09:53:13 -0700937
Eric Laurentc21d5692020-02-25 10:24:36 -0800938 if (appState == APP_STATE_TOP) {
939 if (isPrivacySensitive) {
940 if (current->startTimeNs > topSensitiveStartNs) {
941 topSensitiveActive = current;
942 topSensitiveStartNs = current->startTimeNs;
943 }
944 } else {
945 if (current->startTimeNs > topStartNs) {
946 topActive = current;
947 topStartNs = current->startTimeNs;
948 }
949 }
950 if (isAssistant) {
951 isAssistantOnTop = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800952 if (isActiveAssistant) {
953 useActiveAssistantList = true;
954 } else if (!useActiveAssistantList) {
955 if (current->startTimeNs > latestAssistantStartNs) {
956 latestActiveAssistant = current;
957 latestAssistantStartNs = current->startTimeNs;
958 }
959 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800960 }
Eric Laurenta46bedb2018-12-07 18:01:26 -0800961 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800962 // Clients capturing for HOTWORD are not considered
963 // for latest active to avoid masking regular clients started before
964 if (!(current->attributes.source == AUDIO_SOURCE_HOTWORD
965 || ((isA11yOnTop || rttCallActive) && isAssistant))) {
966 if (isPrivacySensitive) {
Eric Laurentb809a752020-06-29 09:53:13 -0700967 // if audio mode is IN_COMMUNICATION, make sure the audio mode owner
968 // is marked latest sensitive active even if another app qualifies.
969 if (current->startTimeNs > latestSensitiveStartNs
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700970 || (isInCommunication && currentUid == mPhoneStateOwnerUid)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700971 if (!isInCommunication || latestSensitiveActiveOrComm == nullptr
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700972 || VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000973 latestSensitiveActiveOrComm->attributionSource.uid))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700974 != mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700975 latestSensitiveActiveOrComm = current;
976 latestSensitiveStartNs = current->startTimeNs;
977 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800978 }
979 isSensitiveActive = true;
980 } else {
981 if (current->startTimeNs > latestStartNs) {
982 latestActive = current;
983 latestStartNs = current->startTimeNs;
984 }
985 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800986 }
987 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700988 if (current->attributes.source != AUDIO_SOURCE_HOTWORD) {
989 onlyHotwordActive = false;
990 }
Eric Laurentb0eff0f2021-11-09 16:05:49 +0100991 if (currentUid == mPhoneStateOwnerUid &&
992 !isVirtualSource(current->attributes.source)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700993 isPhoneStateOwnerActive = true;
994 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800995 }
996
Eric Laurent1ff16a72019-03-14 18:35:04 -0700997 // if no active client with UI on Top, consider latest active as top
998 if (topActive == nullptr) {
999 topActive = latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -08001000 topStartNs = latestStartNs;
1001 }
1002 if (topSensitiveActive == nullptr) {
Eric Laurentb809a752020-06-29 09:53:13 -07001003 topSensitiveActive = latestSensitiveActiveOrComm;
Eric Laurentc21d5692020-02-25 10:24:36 -08001004 topSensitiveStartNs = latestSensitiveStartNs;
Eric Laurentb809a752020-06-29 09:53:13 -07001005 } 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.
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001008 uid_t latestActiveUid = VALUE_OR_FATAL(
Svet Ganov33761132021-05-13 22:51:08 +00001009 aidl2legacy_int32_t_uid_t(latestSensitiveActiveOrComm->attributionSource.uid));
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001010 if (isInCommunication && latestActiveUid == mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -07001011 topSensitiveActive = latestSensitiveActiveOrComm;
1012 topSensitiveStartNs = latestSensitiveStartNs;
1013 }
Eric Laurentc21d5692020-02-25 10:24:36 -08001014 }
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
Ricardo Correa57a37692020-03-23 17:27:25 -07001022 && !topActive->canCaptureOutput) {
Eric Laurentc21d5692020-02-25 10:24:36 -08001023 topActive = nullptr;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001024 }
1025
1026 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
1027 sp<AudioRecordClient> current = mAudioRecordClients[i];
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001028 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +00001029 current->attributionSource.uid));
Eric Laurent1ff16a72019-03-14 18:35:04 -07001030 if (!current->active) {
1031 continue;
1032 }
1033
Eric Laurent4eb58f12018-12-07 16:41:02 -08001034 audio_source_t source = current->attributes.source;
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001035 bool isTopOrLatestActive = topActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +00001036 current->attributionSource.uid == topActive->attributionSource.uid;
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001037 bool isTopOrLatestSensitive = topSensitiveActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +00001038 current->attributionSource.uid == topSensitiveActive->attributionSource.uid;
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001039 bool isTopOrLatestAssistant = latestActiveAssistant == nullptr ? false :
1040 current->attributionSource.uid == latestActiveAssistant->attributionSource.uid;
Eric Laurentc21d5692020-02-25 10:24:36 -08001041
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001042 auto canCaptureIfInCallOrCommunication = [&](const auto &recordClient) REQUIRES(mLock) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001043 uid_t recordUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +00001044 recordClient->attributionSource.uid));
Ricardo Correa57a37692020-03-23 17:27:25 -07001045 bool canCaptureCall = recordClient->canCaptureOutput;
Eric Laurentb809a752020-06-29 09:53:13 -07001046 bool canCaptureCommunication = recordClient->canCaptureOutput
1047 || !isPhoneStateOwnerActive
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001048 || recordUid == mPhoneStateOwnerUid;
Eric Laurentb809a752020-06-29 09:53:13 -07001049 return !(isInCall && !canCaptureCall)
1050 && !(isInCommunication && !canCaptureCommunication);
Eric Laurentc21d5692020-02-25 10:24:36 -08001051 };
Eric Laurent1ff16a72019-03-14 18:35:04 -07001052
1053 // By default allow capture if:
1054 // The assistant is not on TOP
Eric Laurenta171e352019-05-07 13:04:45 -07001055 // AND is on TOP or latest started
Eric Laurent1ff16a72019-03-14 18:35:04 -07001056 // AND there is no active privacy sensitive capture or call
1057 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4ab18412022-11-07 16:25:32 +01001058 bool allowSensitiveCapture =
1059 !isSensitiveActive || isTopOrLatestSensitive || current->canCaptureOutput;
Eric Laurent1ff16a72019-03-14 18:35:04 -07001060 bool allowCapture = !isAssistantOnTop
Eric Laurentc21d5692020-02-25 10:24:36 -08001061 && (isTopOrLatestActive || isTopOrLatestSensitive)
Eric Laurent4ab18412022-11-07 16:25:32 +01001062 && allowSensitiveCapture
Eric Laurentc21d5692020-02-25 10:24:36 -08001063 && canCaptureIfInCallOrCommunication(current);
Eric Laurent2dc962b2019-03-01 08:25:25 -08001064
Eric Laurented726cc2021-07-01 14:26:41 +02001065 if (!current->hasOp()) {
1066 // Never allow capture if app op is denied
1067 allowCapture = false;
1068 } else if (isVirtualSource(source)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001069 // Allow capture for virtual (remote submix, call audio TX or RX...) sources
1070 allowCapture = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001071 } else if (!useActiveAssistantList && mUidPolicy->isAssistantUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001072 // For assistant allow capture if:
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001073 // Active assistant list is not being used
1074 // AND accessibility service is on TOP or a RTT call is active
Eric Laurent1ff16a72019-03-14 18:35:04 -07001075 // AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001076 // OR there is no active privacy sensitive capture or call
1077 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
1078 // AND is latest TOP assistant AND
1079 // uses VOICE_RECOGNITION OR uses HOTWORD
1080 // OR there is no TOP assistant and uses HOTWORD
Eric Laurent6ede98f2019-06-11 14:50:30 -07001081 if (isA11yOnTop || rttCallActive) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001082 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001083 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001084 }
Eric Laurent4ab18412022-11-07 16:25:32 +01001085 } else if (allowSensitiveCapture
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001086 && canCaptureIfInCallOrCommunication(current)) {
1087 if (isTopOrLatestAssistant
1088 && (source == AUDIO_SOURCE_VOICE_RECOGNITION
1089 || source == AUDIO_SOURCE_HOTWORD)) {
1090 allowCapture = true;
1091 } else if (!isAssistantOnTop && (source == AUDIO_SOURCE_HOTWORD)) {
1092 allowCapture = true;
1093 }
1094 }
1095 } else if (useActiveAssistantList && mUidPolicy->isActiveAssistantUid(currentUid)) {
1096 // For assistant on active list and on top allow capture if:
1097 // An accessibility service is on TOP
1098 // AND the source is VOICE_RECOGNITION or HOTWORD
1099 // OR there is no active privacy sensitive capture or call
1100 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
1101 // AND uses VOICE_RECOGNITION OR uses HOTWORD
1102 if (isA11yOnTop) {
1103 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
1104 allowCapture = true;
1105 }
Eric Laurent4ab18412022-11-07 16:25:32 +01001106 } else if (allowSensitiveCapture
Eric Laurentc21d5692020-02-25 10:24:36 -08001107 && canCaptureIfInCallOrCommunication(current)) {
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001108 if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) || (source == AUDIO_SOURCE_HOTWORD))
1109 {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001110 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001111 }
1112 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001113 } else if (mUidPolicy->isA11yUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001114 // For accessibility service allow capture if:
Eric Laurent47670c92019-08-28 16:59:05 -07001115 // The assistant is not on TOP
1116 // AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -07001117 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent47670c92019-08-28 16:59:05 -07001118 // OR
1119 // Is on TOP AND the source is VOICE_RECOGNITION or HOTWORD
1120 if (!isAssistantOnTop
Eric Laurent4ab18412022-11-07 16:25:32 +01001121 && allowSensitiveCapture
Eric Laurentc21d5692020-02-25 10:24:36 -08001122 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent47670c92019-08-28 16:59:05 -07001123 allowCapture = true;
1124 }
Eric Laurent589171c2019-07-25 18:04:29 -07001125 if (isA11yOnTop) {
1126 if (source == AUDIO_SOURCE_VOICE_RECOGNITION || source == AUDIO_SOURCE_HOTWORD) {
1127 allowCapture = true;
1128 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001129 }
Eric Laurent4e947da2019-10-17 15:24:06 -07001130 } else if (source == AUDIO_SOURCE_HOTWORD) {
1131 // For HOTWORD source allow capture when not on TOP if:
1132 // All active clients are using HOTWORD source
1133 // AND no call is active
1134 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurentc21d5692020-02-25 10:24:36 -08001135 if (onlyHotwordActive
1136 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent4e947da2019-10-17 15:24:06 -07001137 allowCapture = true;
1138 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001139 } else if (mUidPolicy->isCurrentImeUid(currentUid)) {
Kohsuke Yatoha623a132020-03-24 20:10:26 -07001140 // For current InputMethodService allow capture if:
1141 // A RTT call is active AND the source is VOICE_RECOGNITION
1142 if (rttCallActive && source == AUDIO_SOURCE_VOICE_RECOGNITION) {
1143 allowCapture = true;
1144 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001145 }
Eric Laurent8c7ef892021-06-10 13:32:16 +02001146 setAppState_l(current,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001147 allowCapture ? apmStatFromAmState(mUidPolicy->getUidState(currentUid)) :
Eric Laurent1ff16a72019-03-14 18:35:04 -07001148 APP_STATE_IDLE);
Eric Laurente8c8b432018-10-17 10:08:02 -07001149 }
1150}
1151
Michael Groovercfd28302018-12-11 19:16:46 -08001152void AudioPolicyService::silenceAllRecordings_l() {
1153 for (size_t i = 0; i < mAudioRecordClients.size(); i++) {
1154 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -07001155 if (!isVirtualSource(current->attributes.source)) {
Eric Laurent8c7ef892021-06-10 13:32:16 +02001156 setAppState_l(current, APP_STATE_IDLE);
Eric Laurent1ff16a72019-03-14 18:35:04 -07001157 }
Michael Groovercfd28302018-12-11 19:16:46 -08001158 }
1159}
1160
Eric Laurente8c8b432018-10-17 10:08:02 -07001161/* static */
1162app_state_t AudioPolicyService::apmStatFromAmState(int amState) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001163
1164 if (amState == ActivityManager::PROCESS_STATE_UNKNOWN) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001165 return APP_STATE_IDLE;
Eric Laurent1ff16a72019-03-14 18:35:04 -07001166 } else if (amState <= ActivityManager::PROCESS_STATE_TOP) {
1167 // include persistent services
1168 return APP_STATE_TOP;
Eric Laurente8c8b432018-10-17 10:08:02 -07001169 }
1170 return APP_STATE_FOREGROUND;
1171}
1172
Eric Laurent4eb58f12018-12-07 16:41:02 -08001173/* static */
Eric Laurent2dc962b2019-03-01 08:25:25 -08001174bool AudioPolicyService::isVirtualSource(audio_source_t source)
Eric Laurent4eb58f12018-12-07 16:41:02 -08001175{
1176 switch (source) {
1177 case AUDIO_SOURCE_VOICE_UPLINK:
1178 case AUDIO_SOURCE_VOICE_DOWNLINK:
1179 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent2dc962b2019-03-01 08:25:25 -08001180 case AUDIO_SOURCE_REMOTE_SUBMIX:
1181 case AUDIO_SOURCE_FM_TUNER:
Eric Laurent68eb2122020-04-30 17:40:57 -07001182 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent4eb58f12018-12-07 16:41:02 -08001183 return true;
1184 default:
1185 break;
1186 }
1187 return false;
1188}
1189
Eric Laurented726cc2021-07-01 14:26:41 +02001190/* static */
1191bool AudioPolicyService::isAppOpSource(audio_source_t source)
1192{
1193 switch (source) {
1194 case AUDIO_SOURCE_FM_TUNER:
1195 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent637bd202021-09-22 11:17:11 +02001196 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurented726cc2021-07-01 14:26:41 +02001197 return false;
1198 default:
1199 break;
1200 }
1201 return true;
1202}
1203
Eric Laurent8c7ef892021-06-10 13:32:16 +02001204void AudioPolicyService::setAppState_l(sp<AudioRecordClient> client, app_state_t state)
Eric Laurente8c8b432018-10-17 10:08:02 -07001205{
1206 AutoCallerClear acc;
1207
1208 if (mAudioPolicyManager) {
Eric Laurent8c7ef892021-06-10 13:32:16 +02001209 mAudioPolicyManager->setAppState(client->portId, state);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001210 }
1211 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1212 if (af) {
Eric Laurentf32108e2018-10-04 17:22:04 -07001213 bool silenced = state == APP_STATE_IDLE;
Eric Laurent8c7ef892021-06-10 13:32:16 +02001214 if (client->silenced != silenced) {
1215 if (client->active) {
1216 if (silenced) {
1217 finishRecording(client->attributionSource, client->attributes.source);
1218 } else {
1219 std::stringstream msg;
1220 msg << "Audio recording un-silenced on session " << client->session;
1221 if (!startRecording(client->attributionSource, String16(msg.str().c_str()),
1222 client->attributes.source)) {
1223 silenced = true;
1224 }
1225 }
1226 }
1227 af->setRecordSilenced(client->portId, silenced);
1228 client->silenced = silenced;
1229 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001230 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001231}
1232
Glenn Kasten0f11b512014-01-31 16:18:54 -08001233status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001234{
Glenn Kasten44deb052012-02-05 18:09:08 -08001235 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001236 dumpPermissionDenial(fd);
1237 } else {
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001238 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001239 if (!locked) {
1240 String8 result(kDeadlockedString);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00001241 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001242 }
1243
1244 dumpInternals(fd);
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001245
1246 String8 actPtr = String8::format("AudioCommandThread: %p\n", mAudioCommandThread.get());
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00001247 write(fd, actPtr.c_str(), actPtr.size());
Glenn Kasten9d1f02d2012-02-08 17:47:58 -08001248 if (mAudioCommandThread != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001249 mAudioCommandThread->dump(fd);
1250 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001251
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001252 String8 octPtr = String8::format("OutputCommandThread: %p\n", mOutputCommandThread.get());
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00001253 write(fd, octPtr.c_str(), octPtr.size());
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001254 if (mOutputCommandThread != 0) {
1255 mOutputCommandThread->dump(fd);
1256 }
1257
Eric Laurentdce54a12014-03-10 12:19:46 -07001258 if (mAudioPolicyManager) {
1259 mAudioPolicyManager->dump(fd);
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001260 } else {
1261 String8 apmPtr = String8::format("AudioPolicyManager: %p\n", mAudioPolicyManager);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00001262 write(fd, apmPtr.c_str(), apmPtr.size());
Eric Laurentdce54a12014-03-10 12:19:46 -07001263 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001264
Kevin Rocard8be94972019-02-22 13:26:25 -08001265 mPackageManager.dump(fd);
1266
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001267 dumpReleaseLock(mLock, locked);
Andy Hungc747c532022-03-07 21:41:14 -08001268
Shunkai Yao59b27bc2022-07-22 18:42:27 +00001269 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
Andy Hungc747c532022-03-07 21:41:14 -08001277 {
1278 std::string timeCheckStats = getIAudioPolicyServiceStatistics().dump();
1279 dprintf(fd, "\nIAudioPolicyService binder call profile\n");
1280 write(fd, timeCheckStats.c_str(), timeCheckStats.size());
1281 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001282 }
1283 return NO_ERROR;
1284}
1285
1286status_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);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00001296 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001297 return NO_ERROR;
1298}
1299
1300status_t AudioPolicyService::onTransact(
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001301 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001302 // 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_initStreamVolume:
1333 case TRANSACTION_setStreamVolumeIndex:
1334 case TRANSACTION_setVolumeIndexForAttributes:
1335 case TRANSACTION_getStreamVolumeIndex:
1336 case TRANSACTION_getVolumeIndexForAttributes:
1337 case TRANSACTION_getMinVolumeIndexForAttributes:
1338 case TRANSACTION_getMaxVolumeIndexForAttributes:
1339 case TRANSACTION_isStreamActive:
1340 case TRANSACTION_isStreamActiveRemotely:
1341 case TRANSACTION_isSourceActive:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001342 case TRANSACTION_registerPolicyMixes:
1343 case TRANSACTION_setMasterMono:
1344 case TRANSACTION_getSurroundFormats:
Kriti Dang6537def2021-03-02 13:46:59 +01001345 case TRANSACTION_getReportedSurroundFormats:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001346 case TRANSACTION_setSurroundFormatEnabled:
Oscar Azucena829d90d2022-01-28 17:17:56 -08001347 case TRANSACTION_setAssistantServicesUids:
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001348 case TRANSACTION_setActiveAssistantServicesUids:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001349 case TRANSACTION_setA11yServicesUids:
1350 case TRANSACTION_setUidDeviceAffinities:
1351 case TRANSACTION_removeUidDeviceAffinities:
1352 case TRANSACTION_setUserIdDeviceAffinities:
1353 case TRANSACTION_removeUserIdDeviceAffinities:
Pattydd807582021-11-04 21:01:03 +08001354 case TRANSACTION_getHwOffloadFormatsSupportedForBluetoothMedia:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001355 case TRANSACTION_listAudioVolumeGroups:
1356 case TRANSACTION_getVolumeGroupFromAudioAttributes:
1357 case TRANSACTION_acquireSoundTriggerSession:
1358 case TRANSACTION_releaseSoundTriggerSession:
Atneya Nair698f5ef2022-12-15 16:15:09 -08001359 case TRANSACTION_isHotwordStreamSupported:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001360 case TRANSACTION_setRttEnabled:
1361 case TRANSACTION_isCallScreenModeSupported:
1362 case TRANSACTION_setDevicesRoleForStrategy:
1363 case TRANSACTION_setSupportedSystemUsages:
1364 case TRANSACTION_removeDevicesRoleForStrategy:
Paul Wang5d7cdb52022-11-22 09:45:06 +00001365 case TRANSACTION_clearDevicesRoleForStrategy:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001366 case TRANSACTION_getDevicesForRoleAndStrategy:
1367 case TRANSACTION_getDevicesForAttributes:
1368 case TRANSACTION_setAllowedCapturePolicy:
1369 case TRANSACTION_onNewAudioModulesAvailable:
1370 case TRANSACTION_setCurrentImeUid:
1371 case TRANSACTION_registerSoundTriggerCaptureStateListener:
1372 case TRANSACTION_setDevicesRoleForCapturePreset:
1373 case TRANSACTION_addDevicesRoleForCapturePreset:
1374 case TRANSACTION_removeDevicesRoleForCapturePreset:
1375 case TRANSACTION_clearDevicesRoleForCapturePreset:
Eric Laurent81dd0f52021-07-05 11:54:40 +02001376 case TRANSACTION_getDevicesForRoleAndCapturePreset:
jiabina84c3d32022-12-02 18:59:55 +00001377 case TRANSACTION_getSpatializer:
1378 case TRANSACTION_setPreferredMixerAttributes:
1379 case TRANSACTION_clearPreferredMixerAttributes: {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001380 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
1381 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
1382 __func__, code, IPCThreadState::self()->getCallingPid(),
1383 IPCThreadState::self()->getCallingUid());
1384 return INVALID_OPERATION;
1385 }
1386 } break;
1387 default:
1388 break;
1389 }
1390
Andy Hungc747c532022-03-07 21:41:14 -08001391 const std::string methodName = getIAudioPolicyServiceStatistics().getMethodForCode(code);
1392 mediautils::TimeCheck check(
1393 std::string("IAudioPolicyService::").append(methodName),
1394 [code, methodName](bool timeout, float elapsedMs) { // don't move methodName.
1395 if (timeout) {
1396 mediametrics::LogItem(AMEDIAMETRICS_KEY_AUDIO_POLICY)
1397 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_TIMEOUT)
1398 .set(AMEDIAMETRICS_PROP_METHODCODE, int64_t(code))
1399 .set(AMEDIAMETRICS_PROP_METHODNAME, methodName.c_str())
1400 .record();
1401 } else {
1402 getIAudioPolicyServiceStatistics().event(code, elapsedMs);
1403 }
Andy Hung741b3dd2022-06-13 19:49:43 -07001404 }, mediautils::TimeCheck::kDefaultTimeoutDuration,
1405 mediautils::TimeCheck::kDefaultSecondChanceDuration,
1406 true /* crashOnTimeout */);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001407
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001408 switch (code) {
1409 case SHELL_COMMAND_TRANSACTION: {
1410 int in = data.readFileDescriptor();
1411 int out = data.readFileDescriptor();
1412 int err = data.readFileDescriptor();
1413 int argc = data.readInt32();
1414 Vector<String16> args;
1415 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
1416 args.add(data.readString16());
1417 }
1418 sp<IBinder> unusedCallback;
1419 sp<IResultReceiver> resultReceiver;
1420 status_t status;
1421 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
1422 return status;
1423 }
1424 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
1425 return status;
1426 }
1427 status = shellCommand(in, out, err, args);
1428 if (resultReceiver != nullptr) {
1429 resultReceiver->send(status);
1430 }
1431 return NO_ERROR;
1432 }
1433 }
1434
Mathias Agopian65ab4712010-07-14 17:59:35 -07001435 return BnAudioPolicyService::onTransact(code, data, reply, flags);
1436}
1437
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001438// ------------------- Shell command implementation -------------------
1439
1440// NOTE: This is a remote API - make sure all args are validated
1441status_t AudioPolicyService::shellCommand(int in, int out, int err, Vector<String16>& args) {
1442 if (!checkCallingPermission(sManageAudioPolicyPermission, nullptr, nullptr)) {
1443 return PERMISSION_DENIED;
1444 }
1445 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
1446 return BAD_VALUE;
1447 }
jovanakbe066e12019-09-02 11:54:39 -07001448 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001449 return handleSetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001450 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001451 return handleResetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001452 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001453 return handleGetUidState(args, out, err);
Eric Laurent269acb42021-04-23 16:53:22 +02001454 } else if (args.size() >= 1 && args[0] == String16("purge_permission-cache")) {
1455 purgePermissionCache();
1456 return NO_ERROR;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001457 } else if (args.size() == 1 && args[0] == String16("help")) {
1458 printHelp(out);
1459 return NO_ERROR;
1460 }
1461 printHelp(err);
1462 return BAD_VALUE;
1463}
1464
jovanakbe066e12019-09-02 11:54:39 -07001465static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1466 if (userId < 0) {
1467 ALOGE("Invalid user: %d", userId);
1468 dprintf(err, "Invalid user: %d\n", userId);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001469 return BAD_VALUE;
1470 }
jovanakbe066e12019-09-02 11:54:39 -07001471
1472 PermissionController pc;
1473 uid = pc.getPackageUid(packageName, 0);
1474 if (uid <= 0) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00001475 ALOGE("Unknown package: '%s'", String8(packageName).c_str());
1476 dprintf(err, "Unknown package: '%s'\n", String8(packageName).c_str());
jovanakbe066e12019-09-02 11:54:39 -07001477 return BAD_VALUE;
1478 }
1479
1480 uid = multiuser_get_uid(userId, uid);
1481 return NO_ERROR;
1482}
1483
1484status_t AudioPolicyService::handleSetUidState(Vector<String16>& args, int err) {
1485 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
1486 if (!(args.size() == 3 || args.size() == 5)) {
1487 printHelp(err);
1488 return BAD_VALUE;
1489 }
1490
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001491 bool active = false;
1492 if (args[2] == String16("active")) {
1493 active = true;
1494 } else if ((args[2] != String16("idle"))) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00001495 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).c_str());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001496 return BAD_VALUE;
1497 }
jovanakbe066e12019-09-02 11:54:39 -07001498
1499 int userId = 0;
1500 if (args.size() >= 5 && args[3] == String16("--user")) {
1501 userId = atoi(String8(args[4]));
1502 }
1503
1504 uid_t uid;
1505 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1506 return BAD_VALUE;
1507 }
1508
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001509 sp<UidPolicy> uidPolicy;
1510 {
1511 Mutex::Autolock _l(mLock);
1512 uidPolicy = mUidPolicy;
1513 }
1514 if (uidPolicy) {
1515 uidPolicy->addOverrideUid(uid, active);
1516 return NO_ERROR;
1517 }
1518 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001519}
1520
1521status_t AudioPolicyService::handleResetUidState(Vector<String16>& args, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001522 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1523 if (!(args.size() == 2 || args.size() == 4)) {
1524 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001525 return BAD_VALUE;
1526 }
jovanakbe066e12019-09-02 11:54:39 -07001527
1528 int userId = 0;
1529 if (args.size() >= 4 && args[2] == String16("--user")) {
1530 userId = atoi(String8(args[3]));
1531 }
1532
1533 uid_t uid;
1534 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1535 return BAD_VALUE;
1536 }
1537
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001538 sp<UidPolicy> uidPolicy;
1539 {
1540 Mutex::Autolock _l(mLock);
1541 uidPolicy = mUidPolicy;
1542 }
1543 if (uidPolicy) {
1544 uidPolicy->removeOverrideUid(uid);
1545 return NO_ERROR;
1546 }
1547 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001548}
1549
1550status_t AudioPolicyService::handleGetUidState(Vector<String16>& args, int out, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001551 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1552 if (!(args.size() == 2 || args.size() == 4)) {
1553 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001554 return BAD_VALUE;
1555 }
jovanakbe066e12019-09-02 11:54:39 -07001556
1557 int userId = 0;
1558 if (args.size() >= 4 && args[2] == String16("--user")) {
1559 userId = atoi(String8(args[3]));
1560 }
1561
1562 uid_t uid;
1563 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1564 return BAD_VALUE;
1565 }
1566
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001567 sp<UidPolicy> uidPolicy;
1568 {
1569 Mutex::Autolock _l(mLock);
1570 uidPolicy = mUidPolicy;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001571 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001572 if (uidPolicy) {
1573 return dprintf(out, uidPolicy->isUidActive(uid) ? "active\n" : "idle\n");
1574 }
1575 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001576}
1577
1578status_t AudioPolicyService::printHelp(int out) {
1579 return dprintf(out, "Audio policy service commands:\n"
jovanakbe066e12019-09-02 11:54:39 -07001580 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
1581 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
1582 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001583 " help print this message\n");
1584}
1585
Eric Laurent0d13fea2022-11-04 17:12:08 +01001586status_t AudioPolicyService::registerOutput(audio_io_handle_t output,
1587 const audio_config_base_t& config,
1588 const audio_output_flags_t flags) {
1589 return mUsecaseValidator->registerStream(output, config, flags);
1590}
1591
1592status_t AudioPolicyService::unregisterOutput(audio_io_handle_t output) {
1593 return mUsecaseValidator->unregisterStream(output);
1594}
1595
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001596// ----------- AudioPolicyService::UidPolicy implementation ----------
1597
1598void AudioPolicyService::UidPolicy::registerSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001599 status_t res = mAm.linkToDeath(this);
1600 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001601 | ActivityManager::UID_OBSERVER_IDLE
Eric Laurente8c8b432018-10-17 10:08:02 -07001602 | ActivityManager::UID_OBSERVER_ACTIVE
1603 | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001604 ActivityManager::PROCESS_STATE_UNKNOWN,
1605 String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001606 if (!res) {
1607 Mutex::Autolock _l(mLock);
1608 mObserverRegistered = true;
1609 } else {
1610 ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001611
Steven Moreland2f348142019-07-02 15:59:07 -07001612 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001613 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001614}
1615
1616void AudioPolicyService::UidPolicy::unregisterSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001617 mAm.unlinkToDeath(this);
1618 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001619 Mutex::Autolock _l(mLock);
1620 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001621}
1622
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001623void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
1624 Mutex::Autolock _l(mLock);
1625 mCachedUids.clear();
1626 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001627}
1628
Eric Laurente8c8b432018-10-17 10:08:02 -07001629void AudioPolicyService::UidPolicy::checkRegistered() {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001630 bool needToReregister = false;
1631 {
1632 Mutex::Autolock _l(mLock);
1633 needToReregister = !mObserverRegistered;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001634 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001635 if (needToReregister) {
1636 // Looks like ActivityManager has died previously, attempt to re-register.
1637 registerSelf();
1638 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001639}
1640
1641bool AudioPolicyService::UidPolicy::isUidActive(uid_t uid) {
1642 if (isServiceUid(uid)) return true;
1643 checkRegistered();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001644 {
1645 Mutex::Autolock _l(mLock);
1646 auto overrideIter = mOverrideUids.find(uid);
1647 if (overrideIter != mOverrideUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001648 return overrideIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001649 }
1650 // In an absense of the ActivityManager, assume everything to be active.
1651 if (!mObserverRegistered) return true;
1652 auto cacheIter = mCachedUids.find(uid);
Mikhail Naganoveba668a2018-04-05 08:13:15 -07001653 if (cacheIter != mCachedUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001654 return cacheIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001655 }
1656 }
1657 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001658 bool active = am.isUidActive(uid, String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001659 {
1660 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001661 mCachedUids.insert(std::pair<uid_t,
1662 std::pair<bool, int>>(uid, std::pair<bool, int>(active,
1663 ActivityManager::PROCESS_STATE_UNKNOWN)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001664 }
1665 return active;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001666}
1667
Eric Laurente8c8b432018-10-17 10:08:02 -07001668int AudioPolicyService::UidPolicy::getUidState(uid_t uid) {
1669 if (isServiceUid(uid)) {
1670 return ActivityManager::PROCESS_STATE_TOP;
1671 }
1672 checkRegistered();
1673 {
1674 Mutex::Autolock _l(mLock);
1675 auto overrideIter = mOverrideUids.find(uid);
1676 if (overrideIter != mOverrideUids.end()) {
1677 if (overrideIter->second.first) {
1678 if (overrideIter->second.second != ActivityManager::PROCESS_STATE_UNKNOWN) {
1679 return overrideIter->second.second;
1680 } else {
1681 auto cacheIter = mCachedUids.find(uid);
1682 if (cacheIter != mCachedUids.end()) {
1683 return cacheIter->second.second;
1684 }
1685 }
1686 }
1687 return ActivityManager::PROCESS_STATE_UNKNOWN;
1688 }
1689 // In an absense of the ActivityManager, assume everything to be active.
1690 if (!mObserverRegistered) {
1691 return ActivityManager::PROCESS_STATE_TOP;
1692 }
1693 auto cacheIter = mCachedUids.find(uid);
1694 if (cacheIter != mCachedUids.end()) {
1695 if (cacheIter->second.first) {
1696 return cacheIter->second.second;
1697 } else {
1698 return ActivityManager::PROCESS_STATE_UNKNOWN;
1699 }
1700 }
1701 }
1702 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001703 bool active = am.isUidActive(uid, String16("audioserver"));
Eric Laurente8c8b432018-10-17 10:08:02 -07001704 int state = ActivityManager::PROCESS_STATE_UNKNOWN;
1705 if (active) {
1706 state = am.getUidProcessState(uid, String16("audioserver"));
1707 }
1708 {
1709 Mutex::Autolock _l(mLock);
1710 mCachedUids.insert(std::pair<uid_t,
1711 std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
1712 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001713
Eric Laurente8c8b432018-10-17 10:08:02 -07001714 return state;
1715}
1716
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001717void AudioPolicyService::UidPolicy::onUidActive(uid_t uid) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001718 updateUid(&mCachedUids, uid, true, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001719}
1720
1721void AudioPolicyService::UidPolicy::onUidGone(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001722 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, false);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001723}
1724
1725void AudioPolicyService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001726 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001727}
1728
Eric Laurente8c8b432018-10-17 10:08:02 -07001729void AudioPolicyService::UidPolicy::onUidStateChanged(uid_t uid,
1730 int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07001731 int64_t procStateSeq __unused,
1732 int32_t capability __unused) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001733 if (procState != ActivityManager::PROCESS_STATE_UNKNOWN) {
1734 updateUid(&mCachedUids, uid, true, procState, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001735 }
1736}
1737
Austin Borgerdddb7552023-03-30 17:53:01 -07001738void AudioPolicyService::UidPolicy::onUidProcAdjChanged(uid_t uid __unused, int32_t adj __unused) {
Austin Borger65577682022-02-17 00:25:43 +00001739}
1740
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001741void AudioPolicyService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001742 updateUid(&mOverrideUids, uid, active, ActivityManager::PROCESS_STATE_UNKNOWN, insert);
1743}
1744
1745void AudioPolicyService::UidPolicy::notifyService() {
1746 sp<AudioPolicyService> service = mService.promote();
1747 if (service != nullptr) {
1748 service->updateUidStates();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001749 }
1750}
1751
Eric Laurente8c8b432018-10-17 10:08:02 -07001752void AudioPolicyService::UidPolicy::updateUid(std::unordered_map<uid_t,
1753 std::pair<bool, int>> *uids,
1754 uid_t uid,
1755 bool active,
1756 int state,
1757 bool insert) {
1758 if (isServiceUid(uid)) {
1759 return;
1760 }
1761 bool wasActive = isUidActive(uid);
1762 int previousState = getUidState(uid);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001763 {
1764 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001765 updateUidLocked(uids, uid, active, state, insert);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001766 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001767 if (wasActive != isUidActive(uid) || state != previousState) {
1768 notifyService();
1769 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001770}
1771
Eric Laurente8c8b432018-10-17 10:08:02 -07001772void AudioPolicyService::UidPolicy::updateUidLocked(std::unordered_map<uid_t,
1773 std::pair<bool, int>> *uids,
1774 uid_t uid,
1775 bool active,
1776 int state,
1777 bool insert) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001778 auto it = uids->find(uid);
1779 if (it != uids->end()) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001780 if (insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001781 if (state == ActivityManager::PROCESS_STATE_UNKNOWN) {
1782 it->second.first = active;
1783 }
1784 if (it->second.first) {
1785 it->second.second = state;
1786 } else {
1787 it->second.second = ActivityManager::PROCESS_STATE_UNKNOWN;
1788 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001789 } else {
1790 uids->erase(it);
1791 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001792 } else if (insert && (state == ActivityManager::PROCESS_STATE_UNKNOWN)) {
1793 uids->insert(std::pair<uid_t, std::pair<bool, int>>(uid,
1794 std::pair<bool, int>(active, state)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001795 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001796}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001797
Eric Laurent4eb58f12018-12-07 16:41:02 -08001798bool AudioPolicyService::UidPolicy::isA11yOnTop() {
lihong80e1f56e2022-08-25 11:15:33 +08001799 Mutex::Autolock _l(mLock);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001800 for (const auto &uid : mCachedUids) {
Eric Laurent47670c92019-08-28 16:59:05 -07001801 if (!isA11yUid(uid.first)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001802 continue;
1803 }
Amith Yamasanibcbb3002019-01-23 13:53:33 -08001804 if (uid.second.second >= ActivityManager::PROCESS_STATE_TOP
1805 && uid.second.second <= ActivityManager::PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001806 return true;
1807 }
1808 }
1809 return false;
1810}
1811
Eric Laurentb78763e2018-10-17 10:08:02 -07001812bool AudioPolicyService::UidPolicy::isA11yUid(uid_t uid)
1813{
1814 std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid);
1815 return it != mA11yUids.end();
1816}
1817
Oscar Azucena829d90d2022-01-28 17:17:56 -08001818void AudioPolicyService::UidPolicy::setAssistantUids(const std::vector<uid_t>& uids) {
1819 mAssistantUids.clear();
1820 mAssistantUids = uids;
1821}
1822
1823bool AudioPolicyService::UidPolicy::isAssistantUid(uid_t uid)
1824{
1825 std::vector<uid_t>::iterator it = find(mAssistantUids.begin(), mAssistantUids.end(), uid);
1826 return it != mAssistantUids.end();
1827}
1828
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001829void AudioPolicyService::UidPolicy::setActiveAssistantUids(const std::vector<uid_t>& activeUids) {
1830 mActiveAssistantUids = activeUids;
1831}
1832
1833bool AudioPolicyService::UidPolicy::isActiveAssistantUid(uid_t uid)
1834{
1835 std::vector<uid_t>::iterator it = find(mActiveAssistantUids.begin(),
1836 mActiveAssistantUids.end(), uid);
1837 return it != mActiveAssistantUids.end();
1838}
1839
Oscar Azucena829d90d2022-01-28 17:17:56 -08001840void AudioPolicyService::UidPolicy::dumpInternals(int fd) {
1841 const size_t SIZE = 256;
1842 char buffer[SIZE];
1843 String8 result;
1844 auto appendUidsToResult = [&](const char* title, const std::vector<uid_t> &uids) {
1845 snprintf(buffer, SIZE, "\t%s: \n", title);
1846 result.append(buffer);
1847 int counter = 0;
1848 if (uids.empty()) {
1849 snprintf(buffer, SIZE, "\t\tNo UIDs present.\n");
1850 result.append(buffer);
1851 return;
1852 }
1853 for (const auto &uid : uids) {
1854 snprintf(buffer, SIZE, "\t\tUID[%d]=%d\n", counter++, uid);
1855 result.append(buffer);
1856 }
1857 };
1858
1859 snprintf(buffer, SIZE, "UID Policy:\n");
1860 result.append(buffer);
1861 snprintf(buffer, SIZE, "\tmObserverRegistered=%s\n",(mObserverRegistered ? "True":"False"));
1862 result.append(buffer);
1863
1864 appendUidsToResult("Assistants UIDs", mAssistantUids);
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001865 appendUidsToResult("Active Assistants UIDs", mActiveAssistantUids);
Oscar Azucena829d90d2022-01-28 17:17:56 -08001866
1867 appendUidsToResult("Accessibility UIDs", mA11yUids);
1868
1869 snprintf(buffer, SIZE, "\tInput Method Service UID=%d\n", mCurrentImeUid);
1870 result.append(buffer);
1871
1872 snprintf(buffer, SIZE, "\tIs RTT Enabled: %s\n", (mRttEnabled ? "True":"False"));
1873 result.append(buffer);
1874
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00001875 write(fd, result.c_str(), result.size());
Oscar Azucena829d90d2022-01-28 17:17:56 -08001876}
1877
Michael Groovercfd28302018-12-11 19:16:46 -08001878// ----------- AudioPolicyService::SensorPrivacyService implementation ----------
1879void AudioPolicyService::SensorPrivacyPolicy::registerSelf() {
1880 SensorPrivacyManager spm;
1881 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1882 spm.addSensorPrivacyListener(this);
1883}
1884
1885void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
1886 SensorPrivacyManager spm;
1887 spm.removeSensorPrivacyListener(this);
1888}
1889
1890bool AudioPolicyService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1891 return mSensorPrivacyEnabled;
1892}
1893
Evan Seversond8dc6832022-01-27 10:47:03 -08001894binder::Status AudioPolicyService::SensorPrivacyPolicy::onSensorPrivacyChanged(
1895 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Groovercfd28302018-12-11 19:16:46 -08001896 mSensorPrivacyEnabled = enabled;
1897 sp<AudioPolicyService> service = mService.promote();
1898 if (service != nullptr) {
1899 service->updateUidStates();
1900 }
1901 return binder::Status::ok();
1902}
1903
Eric Laurented726cc2021-07-01 14:26:41 +02001904// ----------- AudioPolicyService::OpRecordAudioMonitor implementation ----------
1905
1906// static
1907sp<AudioPolicyService::OpRecordAudioMonitor>
1908AudioPolicyService::OpRecordAudioMonitor::createIfNeeded(
1909 const AttributionSourceState& attributionSource, const audio_attributes_t& attr,
1910 wp<AudioCommandThread> commandThread)
1911{
Eric Laurent987ce102021-07-05 12:11:51 +02001912 if (isAudioServerOrRootUid(attributionSource.uid)) {
1913 ALOGV("not silencing record for audio or root source %s",
Eric Laurented726cc2021-07-01 14:26:41 +02001914 attributionSource.toString().c_str());
1915 return nullptr;
1916 }
1917
1918 if (!AudioPolicyService::isAppOpSource(attr.source)) {
1919 ALOGD("not monitoring app op for uid %d and source %d",
1920 attributionSource.uid, attr.source);
1921 return nullptr;
1922 }
1923
1924 if (!attributionSource.packageName.has_value()
1925 || attributionSource.packageName.value().size() == 0) {
1926 return nullptr;
1927 }
1928 return new OpRecordAudioMonitor(attributionSource, getOpForSource(attr.source), commandThread);
1929}
1930
1931AudioPolicyService::OpRecordAudioMonitor::OpRecordAudioMonitor(
1932 const AttributionSourceState& attributionSource, int32_t appOp,
1933 wp<AudioCommandThread> commandThread) :
1934 mHasOp(true), mAttributionSource(attributionSource), mAppOp(appOp),
1935 mCommandThread(commandThread)
1936{
1937}
1938
1939AudioPolicyService::OpRecordAudioMonitor::~OpRecordAudioMonitor()
1940{
1941 if (mOpCallback != 0) {
1942 mAppOpsManager.stopWatchingMode(mOpCallback);
1943 }
1944 mOpCallback.clear();
1945}
1946
1947void AudioPolicyService::OpRecordAudioMonitor::onFirstRef()
1948{
1949 checkOp();
1950 mOpCallback = new RecordAudioOpCallback(this);
1951 ALOGV("start watching op %d for %s", mAppOp, mAttributionSource.toString().c_str());
Atneya Nairdc4f3752023-08-09 16:21:48 -07001952 int flags = doesPackageTargetAtLeastU(
1953 mAttributionSource.packageName.value_or("")) ?
1954 AppOpsManager::WATCH_FOREGROUND_CHANGES : 0;
Eric Laurented726cc2021-07-01 14:26:41 +02001955 // TODO: We need to always watch AppOpsManager::OP_RECORD_AUDIO too
1956 // since it controls the mic permission for legacy apps.
1957 mAppOpsManager.startWatchingMode(mAppOp, VALUE_OR_FATAL(aidl2legacy_string_view_String16(
1958 mAttributionSource.packageName.value_or(""))),
Atneya Nairdc4f3752023-08-09 16:21:48 -07001959 flags,
Eric Laurented726cc2021-07-01 14:26:41 +02001960 mOpCallback);
1961}
1962
1963bool AudioPolicyService::OpRecordAudioMonitor::hasOp() const {
1964 return mHasOp.load();
1965}
1966
1967// Called by RecordAudioOpCallback when the app op corresponding to this OpRecordAudioMonitor
1968// is updated in AppOp callback and in onFirstRef()
1969// Note this method is never called (and never to be) for audio server / root track
1970// due to the UID in createIfNeeded(). As a result for those record track, it's:
1971// - not called from constructor,
1972// - not called from RecordAudioOpCallback because the callback is not installed in this case
1973void AudioPolicyService::OpRecordAudioMonitor::checkOp(bool updateUidStates)
1974{
1975 // TODO: We need to always check AppOpsManager::OP_RECORD_AUDIO too
1976 // since it controls the mic permission for legacy apps.
1977 const int32_t mode = mAppOpsManager.checkOp(mAppOp,
1978 mAttributionSource.uid, VALUE_OR_FATAL(aidl2legacy_string_view_String16(
1979 mAttributionSource.packageName.value_or(""))));
1980 const bool hasIt = (mode == AppOpsManager::MODE_ALLOWED);
1981 // verbose logging only log when appOp changed
1982 ALOGI_IF(hasIt != mHasOp.load(),
1983 "App op %d missing, %ssilencing record %s",
1984 mAppOp, hasIt ? "un" : "", mAttributionSource.toString().c_str());
1985 mHasOp.store(hasIt);
1986
1987 if (updateUidStates) {
1988 sp<AudioCommandThread> commandThread = mCommandThread.promote();
1989 if (commandThread != nullptr) {
1990 commandThread->updateUidStatesCommand();
1991 }
1992 }
1993}
1994
1995AudioPolicyService::OpRecordAudioMonitor::RecordAudioOpCallback::RecordAudioOpCallback(
1996 const wp<OpRecordAudioMonitor>& monitor) : mMonitor(monitor)
1997{ }
1998
1999void AudioPolicyService::OpRecordAudioMonitor::RecordAudioOpCallback::opChanged(int32_t op,
2000 const String16& packageName __unused) {
2001 sp<OpRecordAudioMonitor> monitor = mMonitor.promote();
2002 if (monitor != NULL) {
2003 if (op != monitor->getOp()) {
2004 return;
2005 }
2006 monitor->checkOp(true);
2007 }
2008}
2009
2010
Mathias Agopian65ab4712010-07-14 17:59:35 -07002011// ----------- AudioPolicyService::AudioCommandThread implementation ----------
2012
Eric Laurentbfb1b832013-01-07 09:53:42 -08002013AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
2014 const wp<AudioPolicyService>& service)
2015 : Thread(false), mName(name), mService(service)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002016{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002017}
2018
2019
2020AudioPolicyService::AudioCommandThread::~AudioCommandThread()
2021{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002022 if (!mAudioCommands.isEmpty()) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002023 release_wake_lock(mName.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002024 }
2025 mAudioCommands.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002026}
2027
2028void AudioPolicyService::AudioCommandThread::onFirstRef()
2029{
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002030 run(mName.c_str(), ANDROID_PRIORITY_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002031}
2032
2033bool AudioPolicyService::AudioCommandThread::threadLoop()
2034{
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002035 nsecs_t waitTime = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002036
2037 mLock.lock();
2038 while (!exitPending())
2039 {
Eric Laurent59a89232014-06-08 14:14:17 -07002040 sp<AudioPolicyService> svc;
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07002041 int numTimesBecameEmpty = 0;
Eric Laurent59a89232014-06-08 14:14:17 -07002042 while (!mAudioCommands.isEmpty() && !exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002043 nsecs_t curTime = systemTime();
2044 // commands are sorted by increasing time stamp: execute them from index 0 and up
2045 if (mAudioCommands[0]->mTime <= curTime) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002046 sp<AudioCommand> command = mAudioCommands[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07002047 mAudioCommands.removeAt(0);
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07002048 if (mAudioCommands.isEmpty()) {
2049 ++numTimesBecameEmpty;
2050 }
Eric Laurent0ede8922014-05-09 18:04:42 -07002051 mLastCommand = command;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002052
2053 switch (command->mCommand) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002054 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002055 VolumeData *data = (VolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01002056 ALOGV("AudioCommandThread() processing set volume stream %d, \
Eric Laurentde070132010-07-13 04:45:46 -07002057 volume %f, output %d", data->mStream, data->mVolume, data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07002058 mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07002059 command->mStatus = AudioSystem::setStreamVolume(data->mStream,
2060 data->mVolume,
2061 data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07002062 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002063 }break;
2064 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002065 ParametersData *data = (ParametersData *)command->mParam.get();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002066 ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002067 data->mKeyValuePairs.c_str(), data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07002068 mLock.unlock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002069 command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
Andy Hungfe726a62018-09-27 15:17:25 -07002070 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002071 }break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002072 case SET_VOICE_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002073 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01002074 ALOGV("AudioCommandThread() processing set voice volume volume %f",
Eric Laurentde070132010-07-13 04:45:46 -07002075 data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07002076 mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002077 command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07002078 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002079 }break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002080 case STOP_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002081 StopOutputData *data = (StopOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002082 ALOGV("AudioCommandThread() processing stop output portId %d",
2083 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07002084 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002085 if (svc == 0) {
2086 break;
2087 }
2088 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002089 svc->doStopOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002090 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002091 }break;
2092 case RELEASE_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002093 ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002094 ALOGV("AudioCommandThread() processing release output portId %d",
2095 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07002096 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002097 if (svc == 0) {
2098 break;
2099 }
2100 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002101 svc->doReleaseOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002102 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002103 }break;
Eric Laurent951f4552014-05-20 10:48:17 -07002104 case CREATE_AUDIO_PATCH: {
2105 CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
2106 ALOGV("AudioCommandThread() processing create audio patch");
2107 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
2108 if (af == 0) {
2109 command->mStatus = PERMISSION_DENIED;
2110 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07002111 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07002112 command->mStatus = af->createAudioPatch(&data->mPatch, &data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07002113 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07002114 }
2115 } break;
2116 case RELEASE_AUDIO_PATCH: {
2117 ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
2118 ALOGV("AudioCommandThread() processing release audio patch");
2119 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
2120 if (af == 0) {
2121 command->mStatus = PERMISSION_DENIED;
2122 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07002123 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07002124 command->mStatus = af->releaseAudioPatch(data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07002125 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07002126 }
2127 } break;
Eric Laurentb52c1522014-05-20 11:27:36 -07002128 case UPDATE_AUDIOPORT_LIST: {
2129 ALOGV("AudioCommandThread() processing update audio port list");
Eric Laurent59a89232014-06-08 14:14:17 -07002130 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07002131 if (svc == 0) {
2132 break;
2133 }
2134 mLock.unlock();
2135 svc->doOnAudioPortListUpdate();
2136 mLock.lock();
2137 }break;
2138 case UPDATE_AUDIOPATCH_LIST: {
2139 ALOGV("AudioCommandThread() processing update audio patch list");
Eric Laurent59a89232014-06-08 14:14:17 -07002140 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07002141 if (svc == 0) {
2142 break;
2143 }
2144 mLock.unlock();
2145 svc->doOnAudioPatchListUpdate();
2146 mLock.lock();
2147 }break;
François Gaffiecfe17322018-11-07 13:41:29 +01002148 case CHANGED_AUDIOVOLUMEGROUP: {
2149 AudioVolumeGroupData *data =
2150 static_cast<AudioVolumeGroupData *>(command->mParam.get());
2151 ALOGV("AudioCommandThread() processing update audio volume group");
2152 svc = mService.promote();
2153 if (svc == 0) {
2154 break;
2155 }
2156 mLock.unlock();
2157 svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
2158 mLock.lock();
2159 }break;
Eric Laurente1715a42014-05-20 11:30:42 -07002160 case SET_AUDIOPORT_CONFIG: {
2161 SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
2162 ALOGV("AudioCommandThread() processing set port config");
2163 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
2164 if (af == 0) {
2165 command->mStatus = PERMISSION_DENIED;
2166 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07002167 mLock.unlock();
Eric Laurente1715a42014-05-20 11:30:42 -07002168 command->mStatus = af->setAudioPortConfig(&data->mConfig);
Andy Hungfe726a62018-09-27 15:17:25 -07002169 mLock.lock();
Eric Laurente1715a42014-05-20 11:30:42 -07002170 }
2171 } break;
Jean-Michel Trivide801052015-04-14 19:10:14 -07002172 case DYN_POLICY_MIX_STATE_UPDATE: {
2173 DynPolicyMixStateUpdateData *data =
2174 (DynPolicyMixStateUpdateData *)command->mParam.get();
Jean-Michel Trivide801052015-04-14 19:10:14 -07002175 ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002176 data->mRegId.c_str(), data->mState);
Jean-Michel Trivide801052015-04-14 19:10:14 -07002177 svc = mService.promote();
2178 if (svc == 0) {
2179 break;
2180 }
2181 mLock.unlock();
2182 svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
2183 mLock.lock();
2184 } break;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002185 case RECORDING_CONFIGURATION_UPDATE: {
2186 RecordingConfigurationUpdateData *data =
2187 (RecordingConfigurationUpdateData *)command->mParam.get();
2188 ALOGV("AudioCommandThread() processing recording configuration update");
2189 svc = mService.promote();
2190 if (svc == 0) {
2191 break;
2192 }
2193 mLock.unlock();
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002194 svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -08002195 &data->mClientConfig, data->mClientEffects,
2196 &data->mDeviceConfig, data->mEffects,
2197 data->mPatchHandle, data->mSource);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002198 mLock.lock();
2199 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002200 case SET_EFFECT_SUSPENDED: {
2201 SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
2202 ALOGV("AudioCommandThread() processing set effect suspended");
2203 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
2204 if (af != 0) {
2205 mLock.unlock();
2206 af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
2207 mLock.lock();
2208 }
2209 } break;
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002210 case AUDIO_MODULES_UPDATE: {
2211 ALOGV("AudioCommandThread() processing audio modules update");
2212 svc = mService.promote();
2213 if (svc == 0) {
2214 break;
2215 }
2216 mLock.unlock();
2217 svc->doOnNewAudioModulesAvailable();
2218 mLock.lock();
2219 } break;
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002220 case ROUTING_UPDATED: {
2221 ALOGV("AudioCommandThread() processing routing update");
2222 svc = mService.promote();
2223 if (svc == 0) {
2224 break;
2225 }
2226 mLock.unlock();
2227 svc->doOnRoutingUpdated();
2228 mLock.lock();
2229 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002230
Eric Laurented726cc2021-07-01 14:26:41 +02002231 case UPDATE_UID_STATES: {
2232 ALOGV("AudioCommandThread() processing updateUID states");
2233 svc = mService.promote();
2234 if (svc == 0) {
2235 break;
2236 }
2237 mLock.unlock();
2238 svc->updateUidStates();
2239 mLock.lock();
2240 } break;
2241
Eric Laurent15903592022-02-24 20:44:36 +01002242 case CHECK_SPATIALIZER_OUTPUT: {
2243 ALOGV("AudioCommandThread() processing check spatializer");
Eric Laurent81dd0f52021-07-05 11:54:40 +02002244 svc = mService.promote();
2245 if (svc == 0) {
2246 break;
2247 }
2248 mLock.unlock();
2249 svc->doOnCheckSpatializer();
2250 mLock.lock();
2251 } break;
2252
Eric Laurent15903592022-02-24 20:44:36 +01002253 case UPDATE_ACTIVE_SPATIALIZER_TRACKS: {
2254 ALOGV("AudioCommandThread() processing update spatializer tracks");
2255 svc = mService.promote();
2256 if (svc == 0) {
2257 break;
2258 }
2259 mLock.unlock();
2260 svc->doOnUpdateActiveSpatializerTracks();
2261 mLock.lock();
2262 } break;
2263
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002264 case VOL_RANGE_INIT_REQUEST: {
2265 ALOGV("AudioCommandThread() processing volume range init request");
2266 svc = mService.promote();
2267 if (svc == 0) {
2268 break;
2269 }
2270 mLock.unlock();
2271 svc->doOnVolumeRangeInitRequest();
2272 mLock.lock();
2273 } break;
2274
Mathias Agopian65ab4712010-07-14 17:59:35 -07002275 default:
Steve Block5ff1dd52012-01-05 23:22:43 +00002276 ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002277 }
Eric Laurent0ede8922014-05-09 18:04:42 -07002278 {
2279 Mutex::Autolock _l(command->mLock);
2280 if (command->mWaitStatus) {
2281 command->mWaitStatus = false;
2282 command->mCond.signal();
2283 }
2284 }
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002285 waitTime = -1;
Zach Janga754b4f2015-10-27 01:29:34 +00002286 // release mLock before releasing strong reference on the service as
2287 // AudioPolicyService destructor calls AudioCommandThread::exit() which
2288 // acquires mLock.
2289 mLock.unlock();
2290 svc.clear();
2291 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002292 } else {
2293 waitTime = mAudioCommands[0]->mTime - curTime;
2294 break;
2295 }
2296 }
Zach Janga754b4f2015-10-27 01:29:34 +00002297
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07002298 // release delayed commands wake lock as many times as we made the queue is
2299 // empty during popping.
2300 while (numTimesBecameEmpty--) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002301 release_wake_lock(mName.c_str());
Zach Janga754b4f2015-10-27 01:29:34 +00002302 }
2303
2304 // At this stage we have either an empty command queue or the first command in the queue
2305 // has a finite delay. So unless we are exiting it is safe to wait.
2306 if (!exitPending()) {
Eric Laurent59a89232014-06-08 14:14:17 -07002307 ALOGV("AudioCommandThread() going to sleep");
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002308 if (waitTime == -1) {
2309 mWaitWorkCV.wait(mLock);
2310 } else {
2311 mWaitWorkCV.waitRelative(mLock, waitTime);
2312 }
Eric Laurent59a89232014-06-08 14:14:17 -07002313 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002314 }
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002315 // release delayed commands wake lock before quitting
2316 if (!mAudioCommands.isEmpty()) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002317 release_wake_lock(mName.c_str());
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002318 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002319 mLock.unlock();
2320 return false;
2321}
2322
2323status_t AudioPolicyService::AudioCommandThread::dump(int fd)
2324{
2325 const size_t SIZE = 256;
2326 char buffer[SIZE];
2327 String8 result;
2328
Mikhail Naganov12b716c2020-04-30 22:37:43 +00002329 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002330 if (!locked) {
2331 String8 result2(kCmdDeadlockedString);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002332 write(fd, result2.c_str(), result2.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002333 }
2334
2335 snprintf(buffer, SIZE, "- Commands:\n");
2336 result = String8(buffer);
2337 result.append(" Command Time Wait pParam\n");
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002338 for (size_t i = 0; i < mAudioCommands.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002339 mAudioCommands[i]->dump(buffer, SIZE);
2340 result.append(buffer);
2341 }
2342 result.append(" Last Command\n");
Eric Laurent0ede8922014-05-09 18:04:42 -07002343 if (mLastCommand != 0) {
2344 mLastCommand->dump(buffer, SIZE);
2345 result.append(buffer);
2346 } else {
2347 result.append(" none\n");
2348 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002349
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002350 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002351
Mikhail Naganov12b716c2020-04-30 22:37:43 +00002352 dumpReleaseLock(mLock, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002353
2354 return NO_ERROR;
2355}
2356
Glenn Kastenfff6d712012-01-12 16:38:12 -08002357status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
Eric Laurentde070132010-07-13 04:45:46 -07002358 float volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002359 audio_io_handle_t output,
Eric Laurentde070132010-07-13 04:45:46 -07002360 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002361{
Eric Laurent0ede8922014-05-09 18:04:42 -07002362 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002363 command->mCommand = SET_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002364 sp<VolumeData> data = new VolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002365 data->mStream = stream;
2366 data->mVolume = volume;
2367 data->mIO = output;
2368 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002369 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002370 ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
Eric Laurentde070132010-07-13 04:45:46 -07002371 stream, volume, output);
Eric Laurent0ede8922014-05-09 18:04:42 -07002372 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002373}
2374
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002375status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
Dima Zavinfce7a472011-04-19 22:30:36 -07002376 const char *keyValuePairs,
Eric Laurentde070132010-07-13 04:45:46 -07002377 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002378{
Eric Laurent0ede8922014-05-09 18:04:42 -07002379 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002380 command->mCommand = SET_PARAMETERS;
Eric Laurent0ede8922014-05-09 18:04:42 -07002381 sp<ParametersData> data = new ParametersData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002382 data->mIO = ioHandle;
Dima Zavinfce7a472011-04-19 22:30:36 -07002383 data->mKeyValuePairs = String8(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002384 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002385 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002386 ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
Dima Zavinfce7a472011-04-19 22:30:36 -07002387 keyValuePairs, ioHandle, delayMs);
Eric Laurent0ede8922014-05-09 18:04:42 -07002388 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002389}
2390
2391status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
2392{
Eric Laurent0ede8922014-05-09 18:04:42 -07002393 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002394 command->mCommand = SET_VOICE_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002395 sp<VoiceVolumeData> data = new VoiceVolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002396 data->mVolume = volume;
2397 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002398 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002399 ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
Eric Laurent0ede8922014-05-09 18:04:42 -07002400 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002401}
2402
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002403void AudioPolicyService::AudioCommandThread::setEffectSuspendedCommand(int effectId,
2404 audio_session_t sessionId,
2405 bool suspended)
2406{
2407 sp<AudioCommand> command = new AudioCommand();
2408 command->mCommand = SET_EFFECT_SUSPENDED;
2409 sp<SetEffectSuspendedData> data = new SetEffectSuspendedData();
2410 data->mEffectId = effectId;
2411 data->mSessionId = sessionId;
2412 data->mSuspended = suspended;
2413 command->mParam = data;
2414 ALOGV("AudioCommandThread() adding set suspended effectId %d sessionId %d suspended %d",
2415 effectId, sessionId, suspended);
2416 sendCommand(command);
2417}
2418
2419
Eric Laurentd7fe0862018-07-14 16:48:01 -07002420void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002421{
Eric Laurent0ede8922014-05-09 18:04:42 -07002422 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002423 command->mCommand = STOP_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002424 sp<StopOutputData> data = new StopOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002425 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002426 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002427 ALOGV("AudioCommandThread() adding stop output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002428 sendCommand(command);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002429}
2430
Eric Laurentd7fe0862018-07-14 16:48:01 -07002431void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002432{
Eric Laurent0ede8922014-05-09 18:04:42 -07002433 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002434 command->mCommand = RELEASE_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002435 sp<ReleaseOutputData> data = new ReleaseOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002436 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002437 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002438 ALOGV("AudioCommandThread() adding release output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002439 sendCommand(command);
2440}
2441
Eric Laurent951f4552014-05-20 10:48:17 -07002442status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
2443 const struct audio_patch *patch,
2444 audio_patch_handle_t *handle,
2445 int delayMs)
2446{
2447 status_t status = NO_ERROR;
2448
2449 sp<AudioCommand> command = new AudioCommand();
2450 command->mCommand = CREATE_AUDIO_PATCH;
2451 CreateAudioPatchData *data = new CreateAudioPatchData();
2452 data->mPatch = *patch;
2453 data->mHandle = *handle;
2454 command->mParam = data;
2455 command->mWaitStatus = true;
2456 ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
2457 status = sendCommand(command, delayMs);
2458 if (status == NO_ERROR) {
2459 *handle = data->mHandle;
2460 }
2461 return status;
2462}
2463
2464status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
2465 int delayMs)
2466{
2467 sp<AudioCommand> command = new AudioCommand();
2468 command->mCommand = RELEASE_AUDIO_PATCH;
2469 ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
2470 data->mHandle = handle;
2471 command->mParam = data;
2472 command->mWaitStatus = true;
2473 ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
2474 return sendCommand(command, delayMs);
2475}
2476
Eric Laurentb52c1522014-05-20 11:27:36 -07002477void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
2478{
2479 sp<AudioCommand> command = new AudioCommand();
2480 command->mCommand = UPDATE_AUDIOPORT_LIST;
2481 ALOGV("AudioCommandThread() adding update audio port list");
2482 sendCommand(command);
2483}
2484
Eric Laurented726cc2021-07-01 14:26:41 +02002485void AudioPolicyService::AudioCommandThread::updateUidStatesCommand()
2486{
2487 sp<AudioCommand> command = new AudioCommand();
2488 command->mCommand = UPDATE_UID_STATES;
2489 ALOGV("AudioCommandThread() adding update UID states");
2490 sendCommand(command);
2491}
2492
Eric Laurentb52c1522014-05-20 11:27:36 -07002493void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
2494{
2495 sp<AudioCommand>command = new AudioCommand();
2496 command->mCommand = UPDATE_AUDIOPATCH_LIST;
2497 ALOGV("AudioCommandThread() adding update audio patch list");
2498 sendCommand(command);
2499}
2500
François Gaffiecfe17322018-11-07 13:41:29 +01002501void AudioPolicyService::AudioCommandThread::changeAudioVolumeGroupCommand(volume_group_t group,
2502 int flags)
2503{
2504 sp<AudioCommand>command = new AudioCommand();
2505 command->mCommand = CHANGED_AUDIOVOLUMEGROUP;
2506 AudioVolumeGroupData *data= new AudioVolumeGroupData();
2507 data->mGroup = group;
2508 data->mFlags = flags;
2509 command->mParam = data;
2510 ALOGV("AudioCommandThread() adding audio volume group changed");
2511 sendCommand(command);
2512}
2513
Eric Laurente1715a42014-05-20 11:30:42 -07002514status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
2515 const struct audio_port_config *config, int delayMs)
2516{
2517 sp<AudioCommand> command = new AudioCommand();
2518 command->mCommand = SET_AUDIOPORT_CONFIG;
2519 SetAudioPortConfigData *data = new SetAudioPortConfigData();
2520 data->mConfig = *config;
2521 command->mParam = data;
2522 command->mWaitStatus = true;
2523 ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
2524 return sendCommand(command, delayMs);
2525}
2526
Jean-Michel Trivide801052015-04-14 19:10:14 -07002527void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002528 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -07002529{
2530 sp<AudioCommand> command = new AudioCommand();
2531 command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
2532 DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
2533 data->mRegId = regId;
2534 data->mState = state;
2535 command->mParam = data;
2536 ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002537 regId.c_str(), state);
Jean-Michel Trivide801052015-04-14 19:10:14 -07002538 sendCommand(command);
2539}
2540
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002541void AudioPolicyService::AudioCommandThread::recordingConfigurationUpdateCommand(
Eric Laurenta9f86652018-11-28 17:23:11 -08002542 int event,
2543 const record_client_info_t *clientInfo,
2544 const audio_config_base_t *clientConfig,
2545 std::vector<effect_descriptor_t> clientEffects,
2546 const audio_config_base_t *deviceConfig,
2547 std::vector<effect_descriptor_t> effects,
2548 audio_patch_handle_t patchHandle,
2549 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002550{
2551 sp<AudioCommand>command = new AudioCommand();
2552 command->mCommand = RECORDING_CONFIGURATION_UPDATE;
2553 RecordingConfigurationUpdateData *data = new RecordingConfigurationUpdateData();
2554 data->mEvent = event;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002555 data->mClientInfo = *clientInfo;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002556 data->mClientConfig = *clientConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002557 data->mClientEffects = clientEffects;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002558 data->mDeviceConfig = *deviceConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002559 data->mEffects = effects;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002560 data->mPatchHandle = patchHandle;
Eric Laurenta9f86652018-11-28 17:23:11 -08002561 data->mSource = source;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002562 command->mParam = data;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002563 ALOGV("AudioCommandThread() adding recording configuration update event %d, source %d uid %u",
2564 event, clientInfo->source, clientInfo->uid);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002565 sendCommand(command);
2566}
2567
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002568void AudioPolicyService::AudioCommandThread::audioModulesUpdateCommand()
2569{
2570 sp<AudioCommand> command = new AudioCommand();
2571 command->mCommand = AUDIO_MODULES_UPDATE;
2572 sendCommand(command);
2573}
2574
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002575void AudioPolicyService::AudioCommandThread::routingChangedCommand()
2576{
2577 sp<AudioCommand>command = new AudioCommand();
2578 command->mCommand = ROUTING_UPDATED;
2579 ALOGV("AudioCommandThread() adding routing update");
2580 sendCommand(command);
2581}
2582
Eric Laurent81dd0f52021-07-05 11:54:40 +02002583void AudioPolicyService::AudioCommandThread::checkSpatializerCommand()
2584{
2585 sp<AudioCommand>command = new AudioCommand();
Eric Laurent15903592022-02-24 20:44:36 +01002586 command->mCommand = CHECK_SPATIALIZER_OUTPUT;
Eric Laurent81dd0f52021-07-05 11:54:40 +02002587 ALOGV("AudioCommandThread() adding check spatializer");
2588 sendCommand(command);
2589}
2590
Eric Laurent15903592022-02-24 20:44:36 +01002591void AudioPolicyService::AudioCommandThread::updateActiveSpatializerTracksCommand()
2592{
2593 sp<AudioCommand>command = new AudioCommand();
2594 command->mCommand = UPDATE_ACTIVE_SPATIALIZER_TRACKS;
2595 ALOGV("AudioCommandThread() adding update active spatializer tracks");
2596 sendCommand(command);
2597}
2598
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002599void AudioPolicyService::AudioCommandThread::volRangeInitReqCommand()
2600{
2601 sp<AudioCommand>command = new AudioCommand();
2602 command->mCommand = VOL_RANGE_INIT_REQUEST;
2603 ALOGV("AudioCommandThread() adding volume range init request");
2604 sendCommand(command);
2605}
2606
Eric Laurent0ede8922014-05-09 18:04:42 -07002607status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
2608{
2609 {
2610 Mutex::Autolock _l(mLock);
2611 insertCommand_l(command, delayMs);
2612 mWaitWorkCV.signal();
2613 }
2614 Mutex::Autolock _l(command->mLock);
2615 while (command->mWaitStatus) {
2616 nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
2617 if (command->mCond.waitRelative(command->mLock, timeOutNs) != NO_ERROR) {
2618 command->mStatus = TIMED_OUT;
2619 command->mWaitStatus = false;
2620 }
2621 }
2622 return command->mStatus;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002623}
2624
Mathias Agopian65ab4712010-07-14 17:59:35 -07002625// insertCommand_l() must be called with mLock held
Eric Laurent0ede8922014-05-09 18:04:42 -07002626void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002627{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002628 ssize_t i; // not size_t because i will count down to -1
Eric Laurent0ede8922014-05-09 18:04:42 -07002629 Vector < sp<AudioCommand> > removedCommands;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002630 command->mTime = systemTime() + milliseconds(delayMs);
2631
2632 // acquire wake lock to make sure delayed commands are processed
Eric Laurentbfb1b832013-01-07 09:53:42 -08002633 if (mAudioCommands.isEmpty()) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002634 acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002635 }
2636
2637 // check same pending commands with later time stamps and eliminate them
Ivan Lozano5ff158f2017-10-30 09:06:24 -07002638 for (i = (ssize_t)mAudioCommands.size()-1; i >= 0; i--) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002639 sp<AudioCommand> command2 = mAudioCommands[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07002640 // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
2641 if (command2->mTime <= command->mTime) break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002642
2643 // create audio patch or release audio patch commands are equivalent
2644 // with regard to filtering
2645 if ((command->mCommand == CREATE_AUDIO_PATCH) ||
2646 (command->mCommand == RELEASE_AUDIO_PATCH)) {
2647 if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
2648 (command2->mCommand != RELEASE_AUDIO_PATCH)) {
2649 continue;
2650 }
2651 } else if (command2->mCommand != command->mCommand) continue;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002652
2653 switch (command->mCommand) {
2654 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002655 ParametersData *data = (ParametersData *)command->mParam.get();
2656 ParametersData *data2 = (ParametersData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002657 if (data->mIO != data2->mIO) break;
Steve Block3856b092011-10-20 11:56:00 +01002658 ALOGV("Comparing parameter command %s to new command %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002659 data2->mKeyValuePairs.c_str(), data->mKeyValuePairs.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002660 AudioParameter param = AudioParameter(data->mKeyValuePairs);
2661 AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
2662 for (size_t j = 0; j < param.size(); j++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002663 String8 key;
2664 String8 value;
2665 param.getAt(j, key, value);
2666 for (size_t k = 0; k < param2.size(); k++) {
2667 String8 key2;
2668 String8 value2;
2669 param2.getAt(k, key2, value2);
2670 if (key2 == key) {
2671 param2.remove(key2);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002672 ALOGV("Filtering out parameter %s", key2.c_str());
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002673 break;
2674 }
2675 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002676 }
2677 // if all keys have been filtered out, remove the command.
2678 // otherwise, update the key value pairs
2679 if (param2.size() == 0) {
2680 removedCommands.add(command2);
2681 } else {
2682 data2->mKeyValuePairs = param2.toString();
2683 }
Eric Laurent21e54562013-09-23 12:08:05 -07002684 command->mTime = command2->mTime;
2685 // force delayMs to non 0 so that code below does not request to wait for
2686 // command status as the command is now delayed
2687 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002688 } break;
2689
2690 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002691 VolumeData *data = (VolumeData *)command->mParam.get();
2692 VolumeData *data2 = (VolumeData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002693 if (data->mIO != data2->mIO) break;
2694 if (data->mStream != data2->mStream) break;
Steve Block3856b092011-10-20 11:56:00 +01002695 ALOGV("Filtering out volume command on output %d for stream %d",
Eric Laurentde070132010-07-13 04:45:46 -07002696 data->mIO, data->mStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002697 removedCommands.add(command2);
Eric Laurent21e54562013-09-23 12:08:05 -07002698 command->mTime = command2->mTime;
2699 // force delayMs to non 0 so that code below does not request to wait for
2700 // command status as the command is now delayed
2701 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002702 } break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002703
Eric Laurentbaf35fe2016-07-27 15:36:53 -07002704 case SET_VOICE_VOLUME: {
2705 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
2706 VoiceVolumeData *data2 = (VoiceVolumeData *)command2->mParam.get();
2707 ALOGV("Filtering out voice volume command value %f replaced by %f",
2708 data2->mVolume, data->mVolume);
2709 removedCommands.add(command2);
2710 command->mTime = command2->mTime;
2711 // force delayMs to non 0 so that code below does not request to wait for
2712 // command status as the command is now delayed
2713 delayMs = 1;
2714 } break;
2715
Eric Laurente45b48a2014-09-04 16:40:57 -07002716 case CREATE_AUDIO_PATCH:
2717 case RELEASE_AUDIO_PATCH: {
2718 audio_patch_handle_t handle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002719 struct audio_patch patch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002720 if (command->mCommand == CREATE_AUDIO_PATCH) {
2721 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002722 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002723 } else {
2724 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
Mikhail Naganov7be71d22018-05-23 16:51:46 -07002725 memset(&patch, 0, sizeof(patch));
Eric Laurente45b48a2014-09-04 16:40:57 -07002726 }
2727 audio_patch_handle_t handle2;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002728 struct audio_patch patch2;
Eric Laurente45b48a2014-09-04 16:40:57 -07002729 if (command2->mCommand == CREATE_AUDIO_PATCH) {
2730 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002731 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002732 } else {
2733 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
Glenn Kastenf60b6b62015-07-06 10:53:26 -07002734 memset(&patch2, 0, sizeof(patch2));
Eric Laurente45b48a2014-09-04 16:40:57 -07002735 }
2736 if (handle != handle2) break;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002737 /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
2738 same output. */
2739 if( (command->mCommand == CREATE_AUDIO_PATCH) &&
2740 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
2741 bool isOutputDiff = false;
2742 if (patch.num_sources == patch2.num_sources) {
2743 for (unsigned count = 0; count < patch.num_sources; count++) {
2744 if (patch.sources[count].id != patch2.sources[count].id) {
2745 isOutputDiff = true;
2746 break;
2747 }
2748 }
2749 if (isOutputDiff)
2750 break;
2751 }
2752 }
Eric Laurente45b48a2014-09-04 16:40:57 -07002753 ALOGV("Filtering out %s audio patch command for handle %d",
2754 (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
2755 removedCommands.add(command2);
2756 command->mTime = command2->mTime;
2757 // force delayMs to non 0 so that code below does not request to wait for
2758 // command status as the command is now delayed
2759 delayMs = 1;
2760 } break;
2761
Jean-Michel Trivide801052015-04-14 19:10:14 -07002762 case DYN_POLICY_MIX_STATE_UPDATE: {
2763
2764 } break;
2765
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002766 case RECORDING_CONFIGURATION_UPDATE: {
2767
2768 } break;
2769
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002770 case ROUTING_UPDATED: {
2771
2772 } break;
2773
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002774 case VOL_RANGE_INIT_REQUEST: {
2775 // command may come from different requests, do not filter
2776 } break;
2777
Mathias Agopian65ab4712010-07-14 17:59:35 -07002778 default:
2779 break;
2780 }
2781 }
2782
2783 // remove filtered commands
2784 for (size_t j = 0; j < removedCommands.size(); j++) {
2785 // removed commands always have time stamps greater than current command
2786 for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002787 if (mAudioCommands[k].get() == removedCommands[j].get()) {
Steve Block3856b092011-10-20 11:56:00 +01002788 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002789 mAudioCommands.removeAt(k);
2790 break;
2791 }
2792 }
2793 }
2794 removedCommands.clear();
2795
Eric Laurentaa79bef2015-01-15 14:33:51 -08002796 // Disable wait for status if delay is not 0.
2797 // Except for create audio patch command because the returned patch handle
2798 // is needed by audio policy manager
2799 if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
Eric Laurentcec4abb2012-07-03 12:23:02 -07002800 command->mWaitStatus = false;
2801 }
Eric Laurentcec4abb2012-07-03 12:23:02 -07002802
Mathias Agopian65ab4712010-07-14 17:59:35 -07002803 // insert command at the right place according to its time stamp
Eric Laurent1e693b52014-07-09 15:03:28 -07002804 ALOGV("inserting command: %d at index %zd, num commands %zu",
2805 command->mCommand, i+1, mAudioCommands.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002806 mAudioCommands.insertAt(command, i + 1);
2807}
2808
2809void AudioPolicyService::AudioCommandThread::exit()
2810{
Steve Block3856b092011-10-20 11:56:00 +01002811 ALOGV("AudioCommandThread::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002812 {
2813 AutoMutex _l(mLock);
2814 requestExit();
2815 mWaitWorkCV.signal();
2816 }
Zach Janga754b4f2015-10-27 01:29:34 +00002817 // Note that we can call it from the thread loop if all other references have been released
2818 // but it will safely return WOULD_BLOCK in this case
Mathias Agopian65ab4712010-07-14 17:59:35 -07002819 requestExitAndWait();
2820}
2821
2822void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
2823{
2824 snprintf(buffer, size, " %02d %06d.%03d %01u %p\n",
2825 mCommand,
2826 (int)ns2s(mTime),
2827 (int)ns2ms(mTime)%1000,
2828 mWaitStatus,
Eric Laurent0ede8922014-05-09 18:04:42 -07002829 mParam.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002830}
2831
Dima Zavinfce7a472011-04-19 22:30:36 -07002832/******* helpers for the service_ops callbacks defined below *********/
2833void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
2834 const char *keyValuePairs,
2835 int delayMs)
2836{
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002837 mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
Dima Zavinfce7a472011-04-19 22:30:36 -07002838 delayMs);
2839}
2840
2841int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
2842 float volume,
2843 audio_io_handle_t output,
2844 int delayMs)
2845{
Glenn Kastenfff6d712012-01-12 16:38:12 -08002846 return (int)mAudioCommandThread->volumeCommand(stream, volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002847 output, delayMs);
Dima Zavinfce7a472011-04-19 22:30:36 -07002848}
2849
Dima Zavinfce7a472011-04-19 22:30:36 -07002850int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
2851{
2852 return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
2853}
2854
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002855void AudioPolicyService::setEffectSuspended(int effectId,
2856 audio_session_t sessionId,
2857 bool suspended)
2858{
2859 mAudioCommandThread->setEffectSuspendedCommand(effectId, sessionId, suspended);
2860}
2861
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002862Status AudioPolicyService::onNewAudioModulesAvailable()
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002863{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07002864 mOutputCommandThread->audioModulesUpdateCommand();
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002865 return Status::ok();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002866}
2867
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002868
Dima Zavinfce7a472011-04-19 22:30:36 -07002869extern "C" {
Eric Laurent2d388ec2014-03-07 13:25:54 -08002870audio_module_handle_t aps_load_hw_module(void *service __unused,
2871 const char *name);
2872audio_io_handle_t aps_open_output(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002873 audio_devices_t *pDevices,
2874 uint32_t *pSamplingRate,
2875 audio_format_t *pFormat,
2876 audio_channel_mask_t *pChannelMask,
2877 uint32_t *pLatencyMs,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002878 audio_output_flags_t flags);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002879
Eric Laurent2d388ec2014-03-07 13:25:54 -08002880audio_io_handle_t aps_open_output_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002881 audio_module_handle_t module,
2882 audio_devices_t *pDevices,
2883 uint32_t *pSamplingRate,
2884 audio_format_t *pFormat,
2885 audio_channel_mask_t *pChannelMask,
2886 uint32_t *pLatencyMs,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002887 audio_output_flags_t flags,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002888 const audio_offload_info_t *offloadInfo);
2889audio_io_handle_t aps_open_dup_output(void *service __unused,
Dima Zavinfce7a472011-04-19 22:30:36 -07002890 audio_io_handle_t output1,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002891 audio_io_handle_t output2);
2892int aps_close_output(void *service __unused, audio_io_handle_t output);
2893int aps_suspend_output(void *service __unused, audio_io_handle_t output);
2894int aps_restore_output(void *service __unused, audio_io_handle_t output);
2895audio_io_handle_t aps_open_input(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002896 audio_devices_t *pDevices,
2897 uint32_t *pSamplingRate,
2898 audio_format_t *pFormat,
2899 audio_channel_mask_t *pChannelMask,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002900 audio_in_acoustics_t acoustics __unused);
2901audio_io_handle_t aps_open_input_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002902 audio_module_handle_t module,
2903 audio_devices_t *pDevices,
2904 uint32_t *pSamplingRate,
2905 audio_format_t *pFormat,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002906 audio_channel_mask_t *pChannelMask);
2907int aps_close_input(void *service __unused, audio_io_handle_t input);
2908int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
Glenn Kastend848eb42016-03-08 13:42:11 -08002909int aps_move_effects(void *service __unused, audio_session_t session,
Dima Zavinfce7a472011-04-19 22:30:36 -07002910 audio_io_handle_t src_output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002911 audio_io_handle_t dst_output);
2912char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
2913 const char *keys);
2914void aps_set_parameters(void *service, audio_io_handle_t io_handle,
2915 const char *kv_pairs, int delay_ms);
2916int aps_set_stream_volume(void *service, audio_stream_type_t stream,
Dima Zavinfce7a472011-04-19 22:30:36 -07002917 float volume, audio_io_handle_t output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002918 int delay_ms);
Eric Laurent2d388ec2014-03-07 13:25:54 -08002919int aps_set_voice_volume(void *service, float volume, int delay_ms);
2920};
Dima Zavinfce7a472011-04-19 22:30:36 -07002921
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08002922} // namespace android