blob: 41335265767954f284af58b79ccc1142ca5cd6df [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
28#include <audio_utils/clock.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070029#include <binder/IServiceManager.h>
30#include <utils/Log.h>
31#include <cutils/properties.h>
32#include <binder/IPCThreadState.h>
Svet Ganovf4ddfef2018-01-16 07:37:58 -080033#include <binder/PermissionController.h>
34#include <binder/IResultReceiver.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035#include <utils/String16.h>
36#include <utils/threads.h>
Atneya Nair5b1ed642023-06-23 14:43:37 -070037#include "AudioRecordClient.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070038#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;
Mathias Agopian65ab4712010-07-14 17:59:35 -070055
Glenn Kasten8dad0e32012-01-09 08:41:22 -080056static const char kDeadlockedString[] = "AudioPolicyService may be deadlocked\n";
57static const char kCmdDeadlockedString[] = "AudioPolicyService command thread may be deadlocked\n";
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053058static const char kAudioPolicyManagerCustomPath[] = "libaudiopolicymanagercustom.so";
Mathias Agopian65ab4712010-07-14 17:59:35 -070059
Mikhail Naganov959e2d02019-03-28 11:08:19 -070060static const int kDumpLockTimeoutNs = 1 * NANOS_PER_SECOND;
Mathias Agopian65ab4712010-07-14 17:59:35 -070061
Eric Laurent0ede8922014-05-09 18:04:42 -070062static const nsecs_t kAudioCommandTimeoutNs = seconds(3); // 3 seconds
Christer Fletcher5fa8c4b2013-01-18 15:27:03 +010063
Svet Ganovf4ddfef2018-01-16 07:37:58 -080064static const String16 sManageAudioPolicyPermission("android.permission.MANAGE_AUDIO_POLICY");
Dima Zavinfce7a472011-04-19 22:30:36 -070065
Andy Hungc747c532022-03-07 21:41:14 -080066// Creates an association between Binder code to name for IAudioPolicyService.
67#define IAUDIOPOLICYSERVICE_BINDER_METHOD_MACRO_LIST \
68BINDER_METHOD_ENTRY(onNewAudioModulesAvailable) \
69BINDER_METHOD_ENTRY(setDeviceConnectionState) \
70BINDER_METHOD_ENTRY(getDeviceConnectionState) \
71BINDER_METHOD_ENTRY(handleDeviceConfigChange) \
72BINDER_METHOD_ENTRY(setPhoneState) \
73BINDER_METHOD_ENTRY(setForceUse) \
74BINDER_METHOD_ENTRY(getForceUse) \
75BINDER_METHOD_ENTRY(getOutput) \
76BINDER_METHOD_ENTRY(getOutputForAttr) \
77BINDER_METHOD_ENTRY(startOutput) \
78BINDER_METHOD_ENTRY(stopOutput) \
79BINDER_METHOD_ENTRY(releaseOutput) \
80BINDER_METHOD_ENTRY(getInputForAttr) \
81BINDER_METHOD_ENTRY(startInput) \
82BINDER_METHOD_ENTRY(stopInput) \
83BINDER_METHOD_ENTRY(releaseInput) \
84BINDER_METHOD_ENTRY(initStreamVolume) \
85BINDER_METHOD_ENTRY(setStreamVolumeIndex) \
86BINDER_METHOD_ENTRY(getStreamVolumeIndex) \
87BINDER_METHOD_ENTRY(setVolumeIndexForAttributes) \
88BINDER_METHOD_ENTRY(getVolumeIndexForAttributes) \
89BINDER_METHOD_ENTRY(getMaxVolumeIndexForAttributes) \
90BINDER_METHOD_ENTRY(getMinVolumeIndexForAttributes) \
91BINDER_METHOD_ENTRY(getStrategyForStream) \
92BINDER_METHOD_ENTRY(getDevicesForAttributes) \
93BINDER_METHOD_ENTRY(getOutputForEffect) \
94BINDER_METHOD_ENTRY(registerEffect) \
95BINDER_METHOD_ENTRY(unregisterEffect) \
96BINDER_METHOD_ENTRY(setEffectEnabled) \
97BINDER_METHOD_ENTRY(moveEffectsToIo) \
98BINDER_METHOD_ENTRY(isStreamActive) \
99BINDER_METHOD_ENTRY(isStreamActiveRemotely) \
100BINDER_METHOD_ENTRY(isSourceActive) \
101BINDER_METHOD_ENTRY(queryDefaultPreProcessing) \
102BINDER_METHOD_ENTRY(addSourceDefaultEffect) \
103BINDER_METHOD_ENTRY(addStreamDefaultEffect) \
104BINDER_METHOD_ENTRY(removeSourceDefaultEffect) \
105BINDER_METHOD_ENTRY(removeStreamDefaultEffect) \
106BINDER_METHOD_ENTRY(setSupportedSystemUsages) \
107BINDER_METHOD_ENTRY(setAllowedCapturePolicy) \
108BINDER_METHOD_ENTRY(getOffloadSupport) \
109BINDER_METHOD_ENTRY(isDirectOutputSupported) \
110BINDER_METHOD_ENTRY(listAudioPorts) \
111BINDER_METHOD_ENTRY(getAudioPort) \
112BINDER_METHOD_ENTRY(createAudioPatch) \
113BINDER_METHOD_ENTRY(releaseAudioPatch) \
114BINDER_METHOD_ENTRY(listAudioPatches) \
115BINDER_METHOD_ENTRY(setAudioPortConfig) \
116BINDER_METHOD_ENTRY(registerClient) \
117BINDER_METHOD_ENTRY(setAudioPortCallbacksEnabled) \
118BINDER_METHOD_ENTRY(setAudioVolumeGroupCallbacksEnabled) \
119BINDER_METHOD_ENTRY(acquireSoundTriggerSession) \
120BINDER_METHOD_ENTRY(releaseSoundTriggerSession) \
121BINDER_METHOD_ENTRY(getPhoneState) \
122BINDER_METHOD_ENTRY(registerPolicyMixes) \
123BINDER_METHOD_ENTRY(setUidDeviceAffinities) \
124BINDER_METHOD_ENTRY(removeUidDeviceAffinities) \
125BINDER_METHOD_ENTRY(setUserIdDeviceAffinities) \
126BINDER_METHOD_ENTRY(removeUserIdDeviceAffinities) \
127BINDER_METHOD_ENTRY(startAudioSource) \
128BINDER_METHOD_ENTRY(stopAudioSource) \
129BINDER_METHOD_ENTRY(setMasterMono) \
130BINDER_METHOD_ENTRY(getMasterMono) \
131BINDER_METHOD_ENTRY(getStreamVolumeDB) \
132BINDER_METHOD_ENTRY(getSurroundFormats) \
133BINDER_METHOD_ENTRY(getReportedSurroundFormats) \
134BINDER_METHOD_ENTRY(getHwOffloadFormatsSupportedForBluetoothMedia) \
135BINDER_METHOD_ENTRY(setSurroundFormatEnabled) \
136BINDER_METHOD_ENTRY(setAssistantServicesUids) \
137BINDER_METHOD_ENTRY(setActiveAssistantServicesUids) \
138BINDER_METHOD_ENTRY(setA11yServicesUids) \
139BINDER_METHOD_ENTRY(setCurrentImeUid) \
140BINDER_METHOD_ENTRY(isHapticPlaybackSupported) \
141BINDER_METHOD_ENTRY(isUltrasoundSupported) \
Atneya Nair698f5ef2022-12-15 16:15:09 -0800142BINDER_METHOD_ENTRY(isHotwordStreamSupported) \
Andy Hungc747c532022-03-07 21:41:14 -0800143BINDER_METHOD_ENTRY(listAudioProductStrategies) \
144BINDER_METHOD_ENTRY(getProductStrategyFromAudioAttributes) \
145BINDER_METHOD_ENTRY(listAudioVolumeGroups) \
146BINDER_METHOD_ENTRY(getVolumeGroupFromAudioAttributes) \
147BINDER_METHOD_ENTRY(setRttEnabled) \
148BINDER_METHOD_ENTRY(isCallScreenModeSupported) \
149BINDER_METHOD_ENTRY(setDevicesRoleForStrategy) \
150BINDER_METHOD_ENTRY(removeDevicesRoleForStrategy) \
Paul Wang5d7cdb52022-11-22 09:45:06 +0000151BINDER_METHOD_ENTRY(clearDevicesRoleForStrategy) \
Andy Hungc747c532022-03-07 21:41:14 -0800152BINDER_METHOD_ENTRY(getDevicesForRoleAndStrategy) \
153BINDER_METHOD_ENTRY(setDevicesRoleForCapturePreset) \
154BINDER_METHOD_ENTRY(addDevicesRoleForCapturePreset) \
155BINDER_METHOD_ENTRY(removeDevicesRoleForCapturePreset) \
156BINDER_METHOD_ENTRY(clearDevicesRoleForCapturePreset) \
157BINDER_METHOD_ENTRY(getDevicesForRoleAndCapturePreset) \
158BINDER_METHOD_ENTRY(registerSoundTriggerCaptureStateListener) \
159BINDER_METHOD_ENTRY(getSpatializer) \
160BINDER_METHOD_ENTRY(canBeSpatialized) \
161BINDER_METHOD_ENTRY(getDirectPlaybackSupport) \
jiabina84c3d32022-12-02 18:59:55 +0000162BINDER_METHOD_ENTRY(getDirectProfilesForAttributes) \
163BINDER_METHOD_ENTRY(getSupportedMixerAttributes) \
164BINDER_METHOD_ENTRY(setPreferredMixerAttributes) \
165BINDER_METHOD_ENTRY(getPreferredMixerAttributes) \
166BINDER_METHOD_ENTRY(clearPreferredMixerAttributes) \
Andy Hungc747c532022-03-07 21:41:14 -0800167
168// singleton for Binder Method Statistics for IAudioPolicyService
169static auto& getIAudioPolicyServiceStatistics() {
170 using Code = int;
171
172#pragma push_macro("BINDER_METHOD_ENTRY")
173#undef BINDER_METHOD_ENTRY
174#define BINDER_METHOD_ENTRY(ENTRY) \
175 {(Code)media::BnAudioPolicyService::TRANSACTION_##ENTRY, #ENTRY},
176
177 static mediautils::MethodStatistics<Code> methodStatistics{
178 IAUDIOPOLICYSERVICE_BINDER_METHOD_MACRO_LIST
179 METHOD_STATISTICS_BINDER_CODE_NAMES(Code)
180 };
181#pragma pop_macro("BINDER_METHOD_ENTRY")
182
183 return methodStatistics;
184}
185
Mathias Agopian65ab4712010-07-14 17:59:35 -0700186// ----------------------------------------------------------------------------
187
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530188static AudioPolicyInterface* createAudioPolicyManager(AudioPolicyClientInterface *clientInterface)
189{
Mikhail Naganov9e459d72023-05-05 17:36:39 -0700190 AudioPolicyManager *apm = nullptr;
191 media::AudioPolicyConfig apmConfig;
192 if (status_t status = clientInterface->getAudioPolicyConfig(&apmConfig); status == OK) {
193 auto config = AudioPolicyConfig::loadFromApmAidlConfigWithFallback(apmConfig);
194 LOG_ALWAYS_FATAL_IF(config->getEngineLibraryNameSuffix() !=
195 AudioPolicyConfig::kDefaultEngineLibraryNameSuffix,
196 "Only default engine is currently supported with the AIDL HAL");
197 apm = new AudioPolicyManager(config,
198 loadApmEngineLibraryAndCreateEngine(
199 config->getEngineLibraryNameSuffix(), apmConfig.engineConfig),
200 clientInterface);
201 } else {
202 auto config = AudioPolicyConfig::loadFromApmXmlConfigWithFallback(); // This can't fail.
203 apm = new AudioPolicyManager(config,
204 loadApmEngineLibraryAndCreateEngine(config->getEngineLibraryNameSuffix()),
205 clientInterface);
206 }
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530207 status_t status = apm->initialize();
208 if (status != NO_ERROR) {
209 delete apm;
210 apm = nullptr;
211 }
212 return apm;
213}
214
215static void destroyAudioPolicyManager(AudioPolicyInterface *interface)
216{
217 delete interface;
218}
219// ----------------------------------------------------------------------------
220
Mathias Agopian65ab4712010-07-14 17:59:35 -0700221AudioPolicyService::AudioPolicyService()
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -0700222 : BnAudioPolicyService(),
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -0700223 mAudioPolicyManager(NULL),
224 mAudioPolicyClient(NULL),
225 mPhoneState(AUDIO_MODE_INVALID),
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530226 mCaptureStateNotifier(false),
227 mCreateAudioPolicyManager(createAudioPolicyManager),
Eric Laurent0d13fea2022-11-04 17:12:08 +0100228 mDestroyAudioPolicyManager(destroyAudioPolicyManager),
229 mUsecaseValidator(media::createUsecaseValidator()) {
Andy Hung225aef62022-12-06 16:33:20 -0800230 setMinSchedulerPolicy(SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530231}
232
233void AudioPolicyService::loadAudioPolicyManager()
234{
235 mLibraryHandle = dlopen(kAudioPolicyManagerCustomPath, RTLD_NOW);
236 if (mLibraryHandle != nullptr) {
237 ALOGI("%s loading %s", __func__, kAudioPolicyManagerCustomPath);
238 mCreateAudioPolicyManager = reinterpret_cast<CreateAudioPolicyManagerInstance>
239 (dlsym(mLibraryHandle, "createAudioPolicyManager"));
240 const char *lastError = dlerror();
241 ALOGW_IF(mCreateAudioPolicyManager == nullptr, "%s createAudioPolicyManager is null %s",
242 __func__, lastError != nullptr ? lastError : "no error");
243
244 mDestroyAudioPolicyManager = reinterpret_cast<DestroyAudioPolicyManagerInstance>(
245 dlsym(mLibraryHandle, "destroyAudioPolicyManager"));
246 lastError = dlerror();
247 ALOGW_IF(mDestroyAudioPolicyManager == nullptr, "%s destroyAudioPolicyManager is null %s",
248 __func__, lastError != nullptr ? lastError : "no error");
249 if (mCreateAudioPolicyManager == nullptr || mDestroyAudioPolicyManager == nullptr){
250 unloadAudioPolicyManager();
251 LOG_ALWAYS_FATAL("could not find audiopolicymanager interface methods");
252 }
253 }
Eric Laurentf5ada6e2014-10-09 17:49:00 -0700254}
255
256void AudioPolicyService::onFirstRef()
257{
Andy Hungd47aca22022-03-15 11:50:51 -0700258 // Log an AudioPolicy "constructor" mediametrics event on first ref.
259 // This records the time it takes to load the audio modules and devices.
260 mediametrics::Defer defer([beginNs = systemTime()] {
261 mediametrics::LogItem(AMEDIAMETRICS_KEY_AUDIO_POLICY)
262 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CTOR)
263 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
264 .record(); });
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700265 {
266 Mutex::Autolock _l(mLock);
Eric Laurent93575202011-01-18 18:39:02 -0800267
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700268 // start audio commands thread
269 mAudioCommandThread = new AudioCommandThread(String8("ApmAudio"), this);
270 // start output activity command thread
271 mOutputCommandThread = new AudioCommandThread(String8("ApmOutput"), this);
Eric Laurentdce54a12014-03-10 12:19:46 -0700272
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700273 mAudioPolicyClient = new AudioPolicyClient(this);
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530274
275 loadAudioPolicyManager();
276 mAudioPolicyManager = mCreateAudioPolicyManager(mAudioPolicyClient);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700277 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200278
bryant_liuba2b4392014-06-11 16:49:30 +0800279 // load audio processing modules
Shunkai Yao8d6489a2023-04-18 23:14:25 +0000280 const sp<EffectsFactoryHalInterface> effectsFactoryHal = EffectsFactoryHalInterface::create();
281 sp<AudioPolicyEffects> audioPolicyEffects = new AudioPolicyEffects(effectsFactoryHal);
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000282 sp<UidPolicy> uidPolicy = new UidPolicy(this);
283 sp<SensorPrivacyPolicy> sensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700284 {
285 Mutex::Autolock _l(mLock);
286 mAudioPolicyEffects = audioPolicyEffects;
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000287 mUidPolicy = uidPolicy;
288 mSensorPrivacyPolicy = sensorPrivacyPolicy;
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700289 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000290 uidPolicy->registerSelf();
291 sensorPrivacyPolicy->registerSelf();
Eric Laurentd66d7a12021-07-13 13:35:32 +0200292
Eric Laurent81dd0f52021-07-05 11:54:40 +0200293 // Create spatializer if supported
Eric Laurent52b0bd52021-09-27 15:25:40 +0200294 if (mAudioPolicyManager != nullptr) {
295 Mutex::Autolock _l(mLock);
296 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
297 AudioDeviceTypeAddrVector devices;
298 bool hasSpatializer = mAudioPolicyManager->canBeSpatialized(&attr, nullptr, devices);
299 if (hasSpatializer) {
Shunkai Yao8d6489a2023-04-18 23:14:25 +0000300 mSpatializer = Spatializer::create(this, effectsFactoryHal);
Eric Laurent52b0bd52021-09-27 15:25:40 +0200301 }
Andy Hung8aa43c02022-09-13 18:53:06 -0700302 if (mSpatializer == nullptr) {
303 // No spatializer created, signal the reason: NO_INIT a failure, OK means intended.
304 const status_t createStatus = hasSpatializer ? NO_INIT : OK;
305 Spatializer::sendEmptyCreateSpatializerMetricWithStatus(createStatus);
306 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200307 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200308 AudioSystem::audioPolicyReady();
François Gaffie163ce832023-06-28 11:36:35 +0200309 // AudioFlinger will handle effect creation and register these effects on audio_policy
310 // service. Hence, audio_policy service must be ready.
311 audioPolicyEffects->setDefaultDeviceEffects();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700312}
313
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530314void AudioPolicyService::unloadAudioPolicyManager()
315{
316 ALOGV("%s ", __func__);
317 if (mLibraryHandle != nullptr) {
318 dlclose(mLibraryHandle);
319 }
320 mLibraryHandle = nullptr;
321 mCreateAudioPolicyManager = nullptr;
322 mDestroyAudioPolicyManager = nullptr;
323}
324
Mathias Agopian65ab4712010-07-14 17:59:35 -0700325AudioPolicyService::~AudioPolicyService()
326{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700327 mAudioCommandThread->exit();
Eric Laurent657ff612014-05-07 11:58:24 -0700328 mOutputCommandThread->exit();
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700329
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530330 mDestroyAudioPolicyManager(mAudioPolicyManager);
331 unloadAudioPolicyManager();
332
Eric Laurentdce54a12014-03-10 12:19:46 -0700333 delete mAudioPolicyClient;
Eric Laurentb52c1522014-05-20 11:27:36 -0700334
335 mNotificationClients.clear();
bryant_liuba2b4392014-06-11 16:49:30 +0800336 mAudioPolicyEffects.clear();
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800337
338 mUidPolicy->unregisterSelf();
Michael Groovercfd28302018-12-11 19:16:46 -0800339 mSensorPrivacyPolicy->unregisterSelf();
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000340
341 mUidPolicy.clear();
Michael Groovercfd28302018-12-11 19:16:46 -0800342 mSensorPrivacyPolicy.clear();
Eric Laurentb52c1522014-05-20 11:27:36 -0700343}
344
345// A notification client is always registered by AudioSystem when the client process
346// connects to AudioPolicyService.
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800347Status AudioPolicyService::registerClient(const sp<media::IAudioPolicyServiceClient>& client)
Eric Laurentb52c1522014-05-20 11:27:36 -0700348{
Eric Laurent12590252015-08-21 18:40:20 -0700349 if (client == 0) {
350 ALOGW("%s got NULL client", __FUNCTION__);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800351 return Status::ok();
Eric Laurent12590252015-08-21 18:40:20 -0700352 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800353 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700354
355 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800356 pid_t pid = IPCThreadState::self()->getCallingPid();
357 int64_t token = ((int64_t)uid<<32) | pid;
358
359 if (mNotificationClients.indexOfKey(token) < 0) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700360 sp<NotificationClient> notificationClient = new NotificationClient(this,
361 client,
luochaojiang908c7d72018-06-21 14:58:04 +0800362 uid,
363 pid);
364 ALOGV("registerClient() client %p, uid %d pid %d", client.get(), uid, pid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700365
luochaojiang908c7d72018-06-21 14:58:04 +0800366 mNotificationClients.add(token, notificationClient);
Eric Laurentb52c1522014-05-20 11:27:36 -0700367
Marco Nelissenf8880202014-11-14 07:58:25 -0800368 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurentb52c1522014-05-20 11:27:36 -0700369 binder->linkToDeath(notificationClient);
370 }
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800371 return Status::ok();
Eric Laurentb52c1522014-05-20 11:27:36 -0700372}
373
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800374Status AudioPolicyService::setAudioPortCallbacksEnabled(bool enabled)
Eric Laurente8726fe2015-06-26 09:39:24 -0700375{
376 Mutex::Autolock _l(mNotificationClientsLock);
377
378 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800379 pid_t pid = IPCThreadState::self()->getCallingPid();
380 int64_t token = ((int64_t)uid<<32) | pid;
381
382 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800383 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700384 }
luochaojiang908c7d72018-06-21 14:58:04 +0800385 mNotificationClients.valueFor(token)->setAudioPortCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800386 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700387}
388
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800389Status AudioPolicyService::setAudioVolumeGroupCallbacksEnabled(bool enabled)
François Gaffiecfe17322018-11-07 13:41:29 +0100390{
391 Mutex::Autolock _l(mNotificationClientsLock);
392
393 uid_t uid = IPCThreadState::self()->getCallingUid();
394 pid_t pid = IPCThreadState::self()->getCallingPid();
395 int64_t token = ((int64_t)uid<<32) | pid;
396
397 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800398 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100399 }
400 mNotificationClients.valueFor(token)->setAudioVolumeGroupCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800401 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100402}
403
Eric Laurentb52c1522014-05-20 11:27:36 -0700404// removeNotificationClient() is called when the client process dies.
luochaojiang908c7d72018-06-21 14:58:04 +0800405void AudioPolicyService::removeNotificationClient(uid_t uid, pid_t pid)
Eric Laurentb52c1522014-05-20 11:27:36 -0700406{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000407 bool hasSameUid = false;
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800408 {
409 Mutex::Autolock _l(mNotificationClientsLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800410 int64_t token = ((int64_t)uid<<32) | pid;
411 mNotificationClients.removeItem(token);
luochaojiang908c7d72018-06-21 14:58:04 +0800412 for (size_t i = 0; i < mNotificationClients.size(); i++) {
413 if (mNotificationClients.valueAt(i)->uid() == uid) {
414 hasSameUid = true;
415 break;
416 }
417 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000418 }
419 {
420 Mutex::Autolock _l(mLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800421 if (mAudioPolicyManager && !hasSameUid) {
Eric Laurent10b71232018-04-13 18:14:44 -0700422 // called from binder death notification: no need to clear caller identity
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700423 mAudioPolicyManager->releaseResourcesForUid(uid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700424 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800425 }
Eric Laurentb52c1522014-05-20 11:27:36 -0700426}
427
428void AudioPolicyService::onAudioPortListUpdate()
429{
430 mOutputCommandThread->updateAudioPortListCommand();
431}
432
433void AudioPolicyService::doOnAudioPortListUpdate()
434{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800435 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700436 for (size_t i = 0; i < mNotificationClients.size(); i++) {
437 mNotificationClients.valueAt(i)->onAudioPortListUpdate();
438 }
439}
440
441void AudioPolicyService::onAudioPatchListUpdate()
442{
443 mOutputCommandThread->updateAudioPatchListCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700444}
445
Eric Laurentb52c1522014-05-20 11:27:36 -0700446void AudioPolicyService::doOnAudioPatchListUpdate()
447{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800448 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700449 for (size_t i = 0; i < mNotificationClients.size(); i++) {
450 mNotificationClients.valueAt(i)->onAudioPatchListUpdate();
451 }
452}
453
François Gaffiecfe17322018-11-07 13:41:29 +0100454void AudioPolicyService::onAudioVolumeGroupChanged(volume_group_t group, int flags)
455{
456 mOutputCommandThread->changeAudioVolumeGroupCommand(group, flags);
457}
458
459void AudioPolicyService::doOnAudioVolumeGroupChanged(volume_group_t group, int flags)
460{
461 Mutex::Autolock _l(mNotificationClientsLock);
462 for (size_t i = 0; i < mNotificationClients.size(); i++) {
463 mNotificationClients.valueAt(i)->onAudioVolumeGroupChanged(group, flags);
464 }
465}
466
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700467void AudioPolicyService::onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700468{
469 ALOGV("AudioPolicyService::onDynamicPolicyMixStateUpdate(%s, %d)",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000470 regId.c_str(), state);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700471 mOutputCommandThread->dynamicPolicyMixStateUpdateCommand(regId, state);
472}
473
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700474void AudioPolicyService::doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700475{
476 Mutex::Autolock _l(mNotificationClientsLock);
477 for (size_t i = 0; i < mNotificationClients.size(); i++) {
478 mNotificationClients.valueAt(i)->onDynamicPolicyMixStateUpdate(regId, state);
479 }
480}
481
Eric Laurenta9f86652018-11-28 17:23:11 -0800482void AudioPolicyService::onRecordingConfigurationUpdate(
483 int event,
484 const record_client_info_t *clientInfo,
485 const audio_config_base_t *clientConfig,
486 std::vector<effect_descriptor_t> clientEffects,
487 const audio_config_base_t *deviceConfig,
488 std::vector<effect_descriptor_t> effects,
489 audio_patch_handle_t patchHandle,
490 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800491{
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800492 mOutputCommandThread->recordingConfigurationUpdateCommand(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800493 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800494}
495
Eric Laurenta9f86652018-11-28 17:23:11 -0800496void AudioPolicyService::doOnRecordingConfigurationUpdate(
497 int event,
498 const record_client_info_t *clientInfo,
499 const audio_config_base_t *clientConfig,
500 std::vector<effect_descriptor_t> clientEffects,
501 const audio_config_base_t *deviceConfig,
502 std::vector<effect_descriptor_t> effects,
503 audio_patch_handle_t patchHandle,
504 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800505{
506 Mutex::Autolock _l(mNotificationClientsLock);
507 for (size_t i = 0; i < mNotificationClients.size(); i++) {
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800508 mNotificationClients.valueAt(i)->onRecordingConfigurationUpdate(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800509 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800510 }
511}
512
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700513void AudioPolicyService::onRoutingUpdated()
514{
515 mOutputCommandThread->routingChangedCommand();
516}
517
518void AudioPolicyService::doOnRoutingUpdated()
519{
520 Mutex::Autolock _l(mNotificationClientsLock);
521 for (size_t i = 0; i < mNotificationClients.size(); i++) {
522 mNotificationClients.valueAt(i)->onRoutingUpdated();
523 }
524}
525
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000526void AudioPolicyService::onVolumeRangeInitRequest()
527{
528 mOutputCommandThread->volRangeInitReqCommand();
529}
530
531void AudioPolicyService::doOnVolumeRangeInitRequest()
532{
533 Mutex::Autolock _l(mNotificationClientsLock);
534 for (size_t i = 0; i < mNotificationClients.size(); i++) {
535 mNotificationClients.valueAt(i)->onVolumeRangeInitRequest();
536 }
537}
538
Eric Laurent81dd0f52021-07-05 11:54:40 +0200539void AudioPolicyService::onCheckSpatializer()
540{
541 Mutex::Autolock _l(mLock);
Eric Laurent39095982021-08-24 18:29:27 +0200542 onCheckSpatializer_l();
543}
544
545void AudioPolicyService::onCheckSpatializer_l()
546{
547 if (mSpatializer != nullptr) {
548 mOutputCommandThread->checkSpatializerCommand();
549 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200550}
551
552void AudioPolicyService::doOnCheckSpatializer()
553{
Eric Laurentd6bee3a2022-08-31 16:07:50 +0200554 ALOGV("%s mSpatializer %p level %d",
555 __func__, mSpatializer.get(), (int)mSpatializer->getLevel());
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200556
Eric Laurent39095982021-08-24 18:29:27 +0200557 if (mSpatializer != nullptr) {
Eric Laurent52b0bd52021-09-27 15:25:40 +0200558 // Note: mSpatializer != nullptr => mAudioPolicyManager != nullptr
Eric Laurent39095982021-08-24 18:29:27 +0200559 if (mSpatializer->getLevel() != media::SpatializationLevel::NONE) {
560 audio_io_handle_t currentOutput = mSpatializer->getOutput();
561 audio_io_handle_t newOutput;
562 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
563 audio_config_base_t config = mSpatializer->getAudioInConfig();
Eric Laurent21270b62022-07-04 15:11:29 +0200564
565 Mutex::Autolock _l(mLock);
Eric Laurent39095982021-08-24 18:29:27 +0200566 status_t status =
567 mAudioPolicyManager->getSpatializerOutput(&config, &attr, &newOutput);
Eric Laurentb4f42a92022-01-17 17:37:31 +0100568 ALOGV("%s currentOutput %d newOutput %d channel_mask %#x",
569 __func__, currentOutput, newOutput, config.channel_mask);
Eric Laurent39095982021-08-24 18:29:27 +0200570 if (status == NO_ERROR && currentOutput == newOutput) {
571 return;
572 }
Eric Laurent15903592022-02-24 20:44:36 +0100573 size_t numActiveTracks = countActiveClientsOnOutput_l(newOutput);
Eric Laurent39095982021-08-24 18:29:27 +0200574 mLock.unlock();
575 // It is OK to call detachOutput() is none is already attached.
576 mSpatializer->detachOutput();
Eric Laurent21270b62022-07-04 15:11:29 +0200577 if (status == NO_ERROR && newOutput != AUDIO_IO_HANDLE_NONE) {
578 status = mSpatializer->attachOutput(newOutput, numActiveTracks);
Eric Laurent39095982021-08-24 18:29:27 +0200579 }
Eric Laurent39095982021-08-24 18:29:27 +0200580 mLock.lock();
581 if (status != NO_ERROR) {
582 mAudioPolicyManager->releaseSpatializerOutput(newOutput);
583 }
584 } else if (mSpatializer->getLevel() == media::SpatializationLevel::NONE
585 && mSpatializer->getOutput() != AUDIO_IO_HANDLE_NONE) {
Eric Laurent39095982021-08-24 18:29:27 +0200586 audio_io_handle_t output = mSpatializer->detachOutput();
Eric Laurent21270b62022-07-04 15:11:29 +0200587
Eric Laurent39095982021-08-24 18:29:27 +0200588 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurent21270b62022-07-04 15:11:29 +0200589 Mutex::Autolock _l(mLock);
Eric Laurent39095982021-08-24 18:29:27 +0200590 mAudioPolicyManager->releaseSpatializerOutput(output);
Eric Laurent81dd0f52021-07-05 11:54:40 +0200591 }
592 }
593 }
594}
595
Eric Laurent11094172022-04-05 18:27:42 +0200596size_t AudioPolicyService::countActiveClientsOnOutput_l(
597 audio_io_handle_t output, bool spatializedOnly) {
Eric Laurent15903592022-02-24 20:44:36 +0100598 size_t count = 0;
599 for (size_t i = 0; i < mAudioPlaybackClients.size(); i++) {
600 auto client = mAudioPlaybackClients.valueAt(i);
Eric Laurent11094172022-04-05 18:27:42 +0200601 if (client->io == output && client->active
602 && (!spatializedOnly || client->isSpatialized)) {
Eric Laurent15903592022-02-24 20:44:36 +0100603 count++;
604 }
605 }
606 return count;
607}
608
609void AudioPolicyService::onUpdateActiveSpatializerTracks_l() {
610 if (mSpatializer == nullptr) {
611 return;
612 }
613 mOutputCommandThread->updateActiveSpatializerTracksCommand();
614}
615
616void AudioPolicyService::doOnUpdateActiveSpatializerTracks()
617{
Eric Laurent21270b62022-07-04 15:11:29 +0200618 if (mSpatializer == nullptr) {
619 return;
620 }
621 audio_io_handle_t output = mSpatializer->getOutput();
Eric Laurent7ea0d1b2022-04-01 14:23:44 +0200622 size_t activeClients;
623 {
624 Mutex::Autolock _l(mLock);
Eric Laurent21270b62022-07-04 15:11:29 +0200625 activeClients = countActiveClientsOnOutput_l(output);
Eric Laurent15903592022-02-24 20:44:36 +0100626 }
Eric Laurent21270b62022-07-04 15:11:29 +0200627 mSpatializer->updateActiveTracks(activeClients);
Eric Laurent15903592022-02-24 20:44:36 +0100628}
629
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800630status_t AudioPolicyService::clientCreateAudioPatch(const struct audio_patch *patch,
631 audio_patch_handle_t *handle,
632 int delayMs)
633{
634 return mAudioCommandThread->createAudioPatchCommand(patch, handle, delayMs);
635}
636
637status_t AudioPolicyService::clientReleaseAudioPatch(audio_patch_handle_t handle,
638 int delayMs)
639{
640 return mAudioCommandThread->releaseAudioPatchCommand(handle, delayMs);
641}
642
Eric Laurente1715a42014-05-20 11:30:42 -0700643status_t AudioPolicyService::clientSetAudioPortConfig(const struct audio_port_config *config,
644 int delayMs)
645{
646 return mAudioCommandThread->setAudioPortConfigCommand(config, delayMs);
647}
648
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800649AudioPolicyService::NotificationClient::NotificationClient(
650 const sp<AudioPolicyService>& service,
651 const sp<media::IAudioPolicyServiceClient>& client,
652 uid_t uid,
653 pid_t pid)
luochaojiang908c7d72018-06-21 14:58:04 +0800654 : mService(service), mUid(uid), mPid(pid), mAudioPolicyServiceClient(client),
François Gaffiecfe17322018-11-07 13:41:29 +0100655 mAudioPortCallbacksEnabled(false), mAudioVolumeGroupCallbacksEnabled(false)
Eric Laurentb52c1522014-05-20 11:27:36 -0700656{
657}
658
659AudioPolicyService::NotificationClient::~NotificationClient()
660{
661}
662
663void AudioPolicyService::NotificationClient::binderDied(const wp<IBinder>& who __unused)
664{
665 sp<NotificationClient> keep(this);
666 sp<AudioPolicyService> service = mService.promote();
667 if (service != 0) {
luochaojiang908c7d72018-06-21 14:58:04 +0800668 service->removeNotificationClient(mUid, mPid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700669 }
670}
671
672void AudioPolicyService::NotificationClient::onAudioPortListUpdate()
673{
Eric Laurente8726fe2015-06-26 09:39:24 -0700674 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700675 mAudioPolicyServiceClient->onAudioPortListUpdate();
676 }
677}
678
679void AudioPolicyService::NotificationClient::onAudioPatchListUpdate()
680{
Eric Laurente8726fe2015-06-26 09:39:24 -0700681 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700682 mAudioPolicyServiceClient->onAudioPatchListUpdate();
683 }
684}
Eric Laurent57dae992011-07-24 13:36:09 -0700685
Pattydd807582021-11-04 21:01:03 +0800686void AudioPolicyService::NotificationClient::onAudioVolumeGroupChanged(volume_group_t group,
François Gaffiecfe17322018-11-07 13:41:29 +0100687 int flags)
688{
689 if (mAudioPolicyServiceClient != 0 && mAudioVolumeGroupCallbacksEnabled) {
690 mAudioPolicyServiceClient->onAudioVolumeGroupChanged(group, flags);
691 }
692}
693
694
Jean-Michel Trivide801052015-04-14 19:10:14 -0700695void AudioPolicyService::NotificationClient::onDynamicPolicyMixStateUpdate(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700696 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700697{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700698 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800699 mAudioPolicyServiceClient->onDynamicPolicyMixStateUpdate(
700 legacy2aidl_String8_string(regId).value(), state);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800701 }
702}
703
704void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate(
Eric Laurenta9f86652018-11-28 17:23:11 -0800705 int event,
706 const record_client_info_t *clientInfo,
707 const audio_config_base_t *clientConfig,
708 std::vector<effect_descriptor_t> clientEffects,
709 const audio_config_base_t *deviceConfig,
710 std::vector<effect_descriptor_t> effects,
711 audio_patch_handle_t patchHandle,
712 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800713{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700714 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800715 status_t status = [&]() -> status_t {
716 int32_t eventAidl = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(event));
717 media::RecordClientInfo clientInfoAidl = VALUE_OR_RETURN_STATUS(
718 legacy2aidl_record_client_info_t_RecordClientInfo(*clientInfo));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700719 AudioConfigBase clientConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700720 legacy2aidl_audio_config_base_t_AudioConfigBase(
721 *clientConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800722 std::vector<media::EffectDescriptor> clientEffectsAidl = VALUE_OR_RETURN_STATUS(
723 convertContainer<std::vector<media::EffectDescriptor>>(
724 clientEffects,
725 legacy2aidl_effect_descriptor_t_EffectDescriptor));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700726 AudioConfigBase deviceConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700727 legacy2aidl_audio_config_base_t_AudioConfigBase(
728 *deviceConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800729 std::vector<media::EffectDescriptor> effectsAidl = VALUE_OR_RETURN_STATUS(
730 convertContainer<std::vector<media::EffectDescriptor>>(
731 effects,
732 legacy2aidl_effect_descriptor_t_EffectDescriptor));
733 int32_t patchHandleAidl = VALUE_OR_RETURN_STATUS(
734 legacy2aidl_audio_patch_handle_t_int32_t(patchHandle));
Mikhail Naganovddceecc2021-09-03 13:58:56 -0700735 media::audio::common::AudioSource sourceAidl = VALUE_OR_RETURN_STATUS(
736 legacy2aidl_audio_source_t_AudioSource(source));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800737 return aidl_utils::statusTFromBinderStatus(
738 mAudioPolicyServiceClient->onRecordingConfigurationUpdate(eventAidl,
739 clientInfoAidl,
740 clientConfigAidl,
741 clientEffectsAidl,
742 deviceConfigAidl,
743 effectsAidl,
744 patchHandleAidl,
745 sourceAidl));
746 }();
747 ALOGW_IF(status != OK, "onRecordingConfigurationUpdate() failed: %d", status);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700748 }
749}
750
Eric Laurente8726fe2015-06-26 09:39:24 -0700751void AudioPolicyService::NotificationClient::setAudioPortCallbacksEnabled(bool enabled)
752{
753 mAudioPortCallbacksEnabled = enabled;
754}
755
François Gaffiecfe17322018-11-07 13:41:29 +0100756void AudioPolicyService::NotificationClient::setAudioVolumeGroupCallbacksEnabled(bool enabled)
757{
758 mAudioVolumeGroupCallbacksEnabled = enabled;
759}
Eric Laurente8726fe2015-06-26 09:39:24 -0700760
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700761void AudioPolicyService::NotificationClient::onRoutingUpdated()
762{
763 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
764 mAudioPolicyServiceClient->onRoutingUpdated();
765 }
766}
767
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000768void AudioPolicyService::NotificationClient::onVolumeRangeInitRequest()
769{
770 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
771 mAudioPolicyServiceClient->onVolumeRangeInitRequest();
772 }
773}
774
Mathias Agopian65ab4712010-07-14 17:59:35 -0700775void AudioPolicyService::binderDied(const wp<IBinder>& who) {
Glenn Kasten411e4472012-11-02 10:00:06 -0700776 ALOGW("binderDied() %p, calling pid %d", who.unsafe_get(),
Eric Laurentde070132010-07-13 04:45:46 -0700777 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700778}
779
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000780static bool dumpTryLock(Mutex& mutex) ACQUIRE(mutex) NO_THREAD_SAFETY_ANALYSIS
Mathias Agopian65ab4712010-07-14 17:59:35 -0700781{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000782 return mutex.timedLock(kDumpLockTimeoutNs) == NO_ERROR;
783}
784
785static void dumpReleaseLock(Mutex& mutex, bool locked) RELEASE(mutex) NO_THREAD_SAFETY_ANALYSIS
786{
787 if (locked) mutex.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700788}
789
790status_t AudioPolicyService::dumpInternals(int fd)
791{
792 const size_t SIZE = 256;
793 char buffer[SIZE];
794 String8 result;
795
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000796 snprintf(buffer, SIZE, "Supported System Usages:\n ");
Hayden Gomes524159d2019-12-23 14:41:47 -0800797 result.append(buffer);
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000798 std::stringstream msg;
799 size_t i = 0;
800 for (auto usage : mSupportedSystemUsages) {
801 if (i++ != 0) msg << ", ";
802 if (const char* strUsage = audio_usage_to_string(usage); strUsage) {
803 msg << strUsage;
804 } else {
805 msg << usage << " (unknown)";
806 }
Hayden Gomes524159d2019-12-23 14:41:47 -0800807 }
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000808 if (i == 0) {
809 msg << "None";
810 }
811 msg << std::endl;
812 result.append(msg.str().c_str());
Hayden Gomes524159d2019-12-23 14:41:47 -0800813
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000814 write(fd, result.c_str(), result.size());
Oscar Azucena829d90d2022-01-28 17:17:56 -0800815
816 mUidPolicy->dumpInternals(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700817 return NO_ERROR;
818}
819
Eric Laurente8c8b432018-10-17 10:08:02 -0700820void AudioPolicyService::updateUidStates()
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800821{
Eric Laurente8c8b432018-10-17 10:08:02 -0700822 Mutex::Autolock _l(mLock);
823 updateUidStates_l();
824}
825
826void AudioPolicyService::updateUidStates_l()
827{
Eric Laurent4eb58f12018-12-07 16:41:02 -0800828// Go over all active clients and allow capture (does not force silence) in the
829// following cases:
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800830// The client is in the active assistant list
831// AND is TOP
832// AND an accessibility service is TOP
833// AND source is either VOICE_RECOGNITION OR HOTWORD
834// OR there is no active privacy sensitive capture or call
835// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
836// AND source is VOICE_RECOGNITION OR HOTWORD
837// The client is an assistant AND active assistant is not being used
Evan Severson1f700cd2021-02-10 13:10:37 -0800838// AND an accessibility service is on TOP or a RTT call is active
Eric Laurent589171c2019-07-25 18:04:29 -0700839// AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800840// OR there is no active privacy sensitive capture or call
Evan Severson1f700cd2021-02-10 13:10:37 -0800841// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800842// AND is TOP most recent assistant and uses VOICE_RECOGNITION or HOTWORD
843// OR there is no top recent assistant and source is HOTWORD
Evan Severson1f700cd2021-02-10 13:10:37 -0800844// OR The client is an accessibility service
845// AND Is on TOP
846// AND the source is VOICE_RECOGNITION or HOTWORD
847// OR The assistant is not on TOP
Eric Laurent589171c2019-07-25 18:04:29 -0700848// AND there is no active privacy sensitive capture or call
849// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Evan Severson1f700cd2021-02-10 13:10:37 -0800850// AND is on TOP
851// AND the source is VOICE_RECOGNITION or HOTWORD
852// OR the client source is virtual (remote submix, call audio TX or RX...)
853// OR the client source is HOTWORD
854// AND is on TOP
855// OR all active clients are using HOTWORD source
856// AND no call is active
857// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
858// OR the client is the current InputMethodService
859// AND a RTT call is active AND the source is VOICE_RECOGNITION
860// OR Any client
861// AND The assistant is not on TOP
862// AND is on TOP or latest started
863// AND there is no active privacy sensitive capture or call
864// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4eb58f12018-12-07 16:41:02 -0800865
Eric Laurent4e947da2019-10-17 15:24:06 -0700866
Eric Laurent4eb58f12018-12-07 16:41:02 -0800867 sp<AudioRecordClient> topActive;
868 sp<AudioRecordClient> latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800869 sp<AudioRecordClient> topSensitiveActive;
Eric Laurentb809a752020-06-29 09:53:13 -0700870 sp<AudioRecordClient> latestSensitiveActiveOrComm;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800871 sp<AudioRecordClient> latestActiveAssistant;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700872
Eric Laurenta46bedb2018-12-07 18:01:26 -0800873 nsecs_t topStartNs = 0;
874 nsecs_t latestStartNs = 0;
Eric Laurentc21d5692020-02-25 10:24:36 -0800875 nsecs_t topSensitiveStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800876 nsecs_t latestSensitiveStartNs = 0;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800877 nsecs_t latestAssistantStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800878 bool isA11yOnTop = mUidPolicy->isA11yOnTop();
879 bool isAssistantOnTop = false;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800880 bool useActiveAssistantList = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800881 bool isSensitiveActive = false;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700882 bool isInCall = mPhoneState == AUDIO_MODE_IN_CALL;
Eric Laurentc21d5692020-02-25 10:24:36 -0800883 bool isInCommunication = mPhoneState == AUDIO_MODE_IN_COMMUNICATION;
884 bool rttCallActive = (isInCall || isInCommunication)
Eric Laurent6ede98f2019-06-11 14:50:30 -0700885 && mUidPolicy->isRttEnabled();
Eric Laurent4e947da2019-10-17 15:24:06 -0700886 bool onlyHotwordActive = true;
Eric Laurentb809a752020-06-29 09:53:13 -0700887 bool isPhoneStateOwnerActive = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800888
Michael Groovercfd28302018-12-11 19:16:46 -0800889 // if Sensor Privacy is enabled then all recordings should be silenced.
890 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
891 silenceAllRecordings_l();
892 return;
893 }
894
Eric Laurente8c8b432018-10-17 10:08:02 -0700895 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
896 sp<AudioRecordClient> current = mAudioRecordClients[i];
Svet Ganov33761132021-05-13 22:51:08 +0000897 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
898 current->attributionSource.uid));
Evan Severson1f700cd2021-02-10 13:10:37 -0800899 if (!current->active) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700900 continue;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800901 }
Eric Laurent1ff16a72019-03-14 18:35:04 -0700902
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700903 app_state_t appState = apmStatFromAmState(mUidPolicy->getUidState(currentUid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700904 // clients which app is in IDLE state are not eligible for top active or
905 // latest active
906 if (appState == APP_STATE_IDLE) {
907 continue;
908 }
909
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700910 bool isAccessibility = mUidPolicy->isA11yUid(currentUid);
Eric Laurent14a88632020-07-16 12:28:30 -0700911 // Clients capturing for Accessibility services or virtual sources are not considered
Eric Laurentc21d5692020-02-25 10:24:36 -0800912 // for top or latest active to avoid masking regular clients started before
Eric Laurent14a88632020-07-16 12:28:30 -0700913 if (!isAccessibility && !isVirtualSource(current->attributes.source)) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700914 bool isAssistant = mUidPolicy->isAssistantUid(currentUid);
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800915 bool isActiveAssistant = mUidPolicy->isActiveAssistantUid(currentUid);
Eric Laurentc21d5692020-02-25 10:24:36 -0800916 bool isPrivacySensitive =
917 (current->attributes.flags & AUDIO_FLAG_CAPTURE_PRIVATE) != 0;
Eric Laurentb809a752020-06-29 09:53:13 -0700918
Eric Laurentc21d5692020-02-25 10:24:36 -0800919 if (appState == APP_STATE_TOP) {
920 if (isPrivacySensitive) {
921 if (current->startTimeNs > topSensitiveStartNs) {
922 topSensitiveActive = current;
923 topSensitiveStartNs = current->startTimeNs;
924 }
925 } else {
926 if (current->startTimeNs > topStartNs) {
927 topActive = current;
928 topStartNs = current->startTimeNs;
929 }
930 }
931 if (isAssistant) {
932 isAssistantOnTop = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800933 if (isActiveAssistant) {
934 useActiveAssistantList = true;
935 } else if (!useActiveAssistantList) {
936 if (current->startTimeNs > latestAssistantStartNs) {
937 latestActiveAssistant = current;
938 latestAssistantStartNs = current->startTimeNs;
939 }
940 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800941 }
Eric Laurenta46bedb2018-12-07 18:01:26 -0800942 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800943 // Clients capturing for HOTWORD are not considered
944 // for latest active to avoid masking regular clients started before
945 if (!(current->attributes.source == AUDIO_SOURCE_HOTWORD
946 || ((isA11yOnTop || rttCallActive) && isAssistant))) {
947 if (isPrivacySensitive) {
Eric Laurentb809a752020-06-29 09:53:13 -0700948 // if audio mode is IN_COMMUNICATION, make sure the audio mode owner
949 // is marked latest sensitive active even if another app qualifies.
950 if (current->startTimeNs > latestSensitiveStartNs
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700951 || (isInCommunication && currentUid == mPhoneStateOwnerUid)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700952 if (!isInCommunication || latestSensitiveActiveOrComm == nullptr
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700953 || VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000954 latestSensitiveActiveOrComm->attributionSource.uid))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700955 != mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700956 latestSensitiveActiveOrComm = current;
957 latestSensitiveStartNs = current->startTimeNs;
958 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800959 }
960 isSensitiveActive = true;
961 } else {
962 if (current->startTimeNs > latestStartNs) {
963 latestActive = current;
964 latestStartNs = current->startTimeNs;
965 }
966 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800967 }
968 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700969 if (current->attributes.source != AUDIO_SOURCE_HOTWORD) {
970 onlyHotwordActive = false;
971 }
Eric Laurentb0eff0f2021-11-09 16:05:49 +0100972 if (currentUid == mPhoneStateOwnerUid &&
973 !isVirtualSource(current->attributes.source)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700974 isPhoneStateOwnerActive = true;
975 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800976 }
977
Eric Laurent1ff16a72019-03-14 18:35:04 -0700978 // if no active client with UI on Top, consider latest active as top
979 if (topActive == nullptr) {
980 topActive = latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800981 topStartNs = latestStartNs;
982 }
983 if (topSensitiveActive == nullptr) {
Eric Laurentb809a752020-06-29 09:53:13 -0700984 topSensitiveActive = latestSensitiveActiveOrComm;
Eric Laurentc21d5692020-02-25 10:24:36 -0800985 topSensitiveStartNs = latestSensitiveStartNs;
Eric Laurentb809a752020-06-29 09:53:13 -0700986 } else if (latestSensitiveActiveOrComm != nullptr) {
987 // if audio mode is IN_COMMUNICATION, favor audio mode owner over an app with
988 // foreground UI in case both are capturing with privacy sensitive flag.
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700989 uid_t latestActiveUid = VALUE_OR_FATAL(
Svet Ganov33761132021-05-13 22:51:08 +0000990 aidl2legacy_int32_t_uid_t(latestSensitiveActiveOrComm->attributionSource.uid));
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700991 if (isInCommunication && latestActiveUid == mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700992 topSensitiveActive = latestSensitiveActiveOrComm;
993 topSensitiveStartNs = latestSensitiveStartNs;
994 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800995 }
996
997 // If both privacy sensitive and regular capture are active:
998 // if the regular capture is privileged
999 // allow concurrency
1000 // else
1001 // favor the privacy sensitive case
1002 if (topActive != nullptr && topSensitiveActive != nullptr
Ricardo Correa57a37692020-03-23 17:27:25 -07001003 && !topActive->canCaptureOutput) {
Eric Laurentc21d5692020-02-25 10:24:36 -08001004 topActive = nullptr;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001005 }
1006
1007 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
1008 sp<AudioRecordClient> current = mAudioRecordClients[i];
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001009 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +00001010 current->attributionSource.uid));
Eric Laurent1ff16a72019-03-14 18:35:04 -07001011 if (!current->active) {
1012 continue;
1013 }
1014
Eric Laurent4eb58f12018-12-07 16:41:02 -08001015 audio_source_t source = current->attributes.source;
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001016 bool isTopOrLatestActive = topActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +00001017 current->attributionSource.uid == topActive->attributionSource.uid;
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001018 bool isTopOrLatestSensitive = topSensitiveActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +00001019 current->attributionSource.uid == topSensitiveActive->attributionSource.uid;
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001020 bool isTopOrLatestAssistant = latestActiveAssistant == nullptr ? false :
1021 current->attributionSource.uid == latestActiveAssistant->attributionSource.uid;
Eric Laurentc21d5692020-02-25 10:24:36 -08001022
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001023 auto canCaptureIfInCallOrCommunication = [&](const auto &recordClient) REQUIRES(mLock) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001024 uid_t recordUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +00001025 recordClient->attributionSource.uid));
Ricardo Correa57a37692020-03-23 17:27:25 -07001026 bool canCaptureCall = recordClient->canCaptureOutput;
Eric Laurentb809a752020-06-29 09:53:13 -07001027 bool canCaptureCommunication = recordClient->canCaptureOutput
1028 || !isPhoneStateOwnerActive
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001029 || recordUid == mPhoneStateOwnerUid;
Eric Laurentb809a752020-06-29 09:53:13 -07001030 return !(isInCall && !canCaptureCall)
1031 && !(isInCommunication && !canCaptureCommunication);
Eric Laurentc21d5692020-02-25 10:24:36 -08001032 };
Eric Laurent1ff16a72019-03-14 18:35:04 -07001033
1034 // By default allow capture if:
1035 // The assistant is not on TOP
Eric Laurenta171e352019-05-07 13:04:45 -07001036 // AND is on TOP or latest started
Eric Laurent1ff16a72019-03-14 18:35:04 -07001037 // AND there is no active privacy sensitive capture or call
1038 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4ab18412022-11-07 16:25:32 +01001039 bool allowSensitiveCapture =
1040 !isSensitiveActive || isTopOrLatestSensitive || current->canCaptureOutput;
Eric Laurent1ff16a72019-03-14 18:35:04 -07001041 bool allowCapture = !isAssistantOnTop
Eric Laurentc21d5692020-02-25 10:24:36 -08001042 && (isTopOrLatestActive || isTopOrLatestSensitive)
Eric Laurent4ab18412022-11-07 16:25:32 +01001043 && allowSensitiveCapture
Eric Laurentc21d5692020-02-25 10:24:36 -08001044 && canCaptureIfInCallOrCommunication(current);
Eric Laurent2dc962b2019-03-01 08:25:25 -08001045
Eric Laurented726cc2021-07-01 14:26:41 +02001046 if (!current->hasOp()) {
1047 // Never allow capture if app op is denied
1048 allowCapture = false;
1049 } else if (isVirtualSource(source)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001050 // Allow capture for virtual (remote submix, call audio TX or RX...) sources
1051 allowCapture = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001052 } else if (!useActiveAssistantList && mUidPolicy->isAssistantUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001053 // For assistant allow capture if:
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001054 // Active assistant list is not being used
1055 // AND accessibility service is on TOP or a RTT call is active
Eric Laurent1ff16a72019-03-14 18:35:04 -07001056 // AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001057 // OR there is no active privacy sensitive capture or call
1058 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
1059 // AND is latest TOP assistant AND
1060 // uses VOICE_RECOGNITION OR uses HOTWORD
1061 // OR there is no TOP assistant and uses HOTWORD
Eric Laurent6ede98f2019-06-11 14:50:30 -07001062 if (isA11yOnTop || rttCallActive) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001063 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001064 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001065 }
Eric Laurent4ab18412022-11-07 16:25:32 +01001066 } else if (allowSensitiveCapture
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001067 && canCaptureIfInCallOrCommunication(current)) {
1068 if (isTopOrLatestAssistant
1069 && (source == AUDIO_SOURCE_VOICE_RECOGNITION
1070 || source == AUDIO_SOURCE_HOTWORD)) {
1071 allowCapture = true;
1072 } else if (!isAssistantOnTop && (source == AUDIO_SOURCE_HOTWORD)) {
1073 allowCapture = true;
1074 }
1075 }
1076 } else if (useActiveAssistantList && mUidPolicy->isActiveAssistantUid(currentUid)) {
1077 // For assistant on active list and on top allow capture if:
1078 // An accessibility service is on TOP
1079 // AND the source is VOICE_RECOGNITION or HOTWORD
1080 // OR there is no active privacy sensitive capture or call
1081 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
1082 // AND uses VOICE_RECOGNITION OR uses HOTWORD
1083 if (isA11yOnTop) {
1084 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
1085 allowCapture = true;
1086 }
Eric Laurent4ab18412022-11-07 16:25:32 +01001087 } else if (allowSensitiveCapture
Eric Laurentc21d5692020-02-25 10:24:36 -08001088 && canCaptureIfInCallOrCommunication(current)) {
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001089 if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) || (source == AUDIO_SOURCE_HOTWORD))
1090 {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001091 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001092 }
1093 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001094 } else if (mUidPolicy->isA11yUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001095 // For accessibility service allow capture if:
Eric Laurent47670c92019-08-28 16:59:05 -07001096 // The assistant is not on TOP
1097 // AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -07001098 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent47670c92019-08-28 16:59:05 -07001099 // OR
1100 // Is on TOP AND the source is VOICE_RECOGNITION or HOTWORD
1101 if (!isAssistantOnTop
Eric Laurent4ab18412022-11-07 16:25:32 +01001102 && allowSensitiveCapture
Eric Laurentc21d5692020-02-25 10:24:36 -08001103 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent47670c92019-08-28 16:59:05 -07001104 allowCapture = true;
1105 }
Eric Laurent589171c2019-07-25 18:04:29 -07001106 if (isA11yOnTop) {
1107 if (source == AUDIO_SOURCE_VOICE_RECOGNITION || source == AUDIO_SOURCE_HOTWORD) {
1108 allowCapture = true;
1109 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001110 }
Eric Laurent4e947da2019-10-17 15:24:06 -07001111 } else if (source == AUDIO_SOURCE_HOTWORD) {
1112 // For HOTWORD source allow capture when not on TOP if:
1113 // All active clients are using HOTWORD source
1114 // AND no call is active
1115 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurentc21d5692020-02-25 10:24:36 -08001116 if (onlyHotwordActive
1117 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent4e947da2019-10-17 15:24:06 -07001118 allowCapture = true;
1119 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001120 } else if (mUidPolicy->isCurrentImeUid(currentUid)) {
Kohsuke Yatoha623a132020-03-24 20:10:26 -07001121 // For current InputMethodService allow capture if:
1122 // A RTT call is active AND the source is VOICE_RECOGNITION
1123 if (rttCallActive && source == AUDIO_SOURCE_VOICE_RECOGNITION) {
1124 allowCapture = true;
1125 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001126 }
Eric Laurent8c7ef892021-06-10 13:32:16 +02001127 setAppState_l(current,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001128 allowCapture ? apmStatFromAmState(mUidPolicy->getUidState(currentUid)) :
Eric Laurent1ff16a72019-03-14 18:35:04 -07001129 APP_STATE_IDLE);
Eric Laurente8c8b432018-10-17 10:08:02 -07001130 }
1131}
1132
Michael Groovercfd28302018-12-11 19:16:46 -08001133void AudioPolicyService::silenceAllRecordings_l() {
1134 for (size_t i = 0; i < mAudioRecordClients.size(); i++) {
1135 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -07001136 if (!isVirtualSource(current->attributes.source)) {
Eric Laurent8c7ef892021-06-10 13:32:16 +02001137 setAppState_l(current, APP_STATE_IDLE);
Eric Laurent1ff16a72019-03-14 18:35:04 -07001138 }
Michael Groovercfd28302018-12-11 19:16:46 -08001139 }
1140}
1141
Eric Laurente8c8b432018-10-17 10:08:02 -07001142/* static */
1143app_state_t AudioPolicyService::apmStatFromAmState(int amState) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001144
1145 if (amState == ActivityManager::PROCESS_STATE_UNKNOWN) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001146 return APP_STATE_IDLE;
Eric Laurent1ff16a72019-03-14 18:35:04 -07001147 } else if (amState <= ActivityManager::PROCESS_STATE_TOP) {
1148 // include persistent services
1149 return APP_STATE_TOP;
Eric Laurente8c8b432018-10-17 10:08:02 -07001150 }
1151 return APP_STATE_FOREGROUND;
1152}
1153
Eric Laurent4eb58f12018-12-07 16:41:02 -08001154/* static */
Eric Laurent2dc962b2019-03-01 08:25:25 -08001155bool AudioPolicyService::isVirtualSource(audio_source_t source)
Eric Laurent4eb58f12018-12-07 16:41:02 -08001156{
1157 switch (source) {
1158 case AUDIO_SOURCE_VOICE_UPLINK:
1159 case AUDIO_SOURCE_VOICE_DOWNLINK:
1160 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent2dc962b2019-03-01 08:25:25 -08001161 case AUDIO_SOURCE_REMOTE_SUBMIX:
1162 case AUDIO_SOURCE_FM_TUNER:
Eric Laurent68eb2122020-04-30 17:40:57 -07001163 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent4eb58f12018-12-07 16:41:02 -08001164 return true;
1165 default:
1166 break;
1167 }
1168 return false;
1169}
1170
Eric Laurent8c7ef892021-06-10 13:32:16 +02001171void AudioPolicyService::setAppState_l(sp<AudioRecordClient> client, app_state_t state)
Eric Laurente8c8b432018-10-17 10:08:02 -07001172{
1173 AutoCallerClear acc;
1174
1175 if (mAudioPolicyManager) {
Eric Laurent8c7ef892021-06-10 13:32:16 +02001176 mAudioPolicyManager->setAppState(client->portId, state);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001177 }
1178 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1179 if (af) {
Eric Laurentf32108e2018-10-04 17:22:04 -07001180 bool silenced = state == APP_STATE_IDLE;
Eric Laurent8c7ef892021-06-10 13:32:16 +02001181 if (client->silenced != silenced) {
1182 if (client->active) {
1183 if (silenced) {
1184 finishRecording(client->attributionSource, client->attributes.source);
1185 } else {
1186 std::stringstream msg;
1187 msg << "Audio recording un-silenced on session " << client->session;
1188 if (!startRecording(client->attributionSource, String16(msg.str().c_str()),
1189 client->attributes.source)) {
1190 silenced = true;
1191 }
1192 }
1193 }
1194 af->setRecordSilenced(client->portId, silenced);
1195 client->silenced = silenced;
1196 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001197 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001198}
1199
Glenn Kasten0f11b512014-01-31 16:18:54 -08001200status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001201{
Glenn Kasten44deb052012-02-05 18:09:08 -08001202 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001203 dumpPermissionDenial(fd);
1204 } else {
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001205 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001206 if (!locked) {
1207 String8 result(kDeadlockedString);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001208 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001209 }
1210
1211 dumpInternals(fd);
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001212
1213 String8 actPtr = String8::format("AudioCommandThread: %p\n", mAudioCommandThread.get());
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001214 write(fd, actPtr.c_str(), actPtr.size());
Glenn Kasten9d1f02d2012-02-08 17:47:58 -08001215 if (mAudioCommandThread != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001216 mAudioCommandThread->dump(fd);
1217 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001218
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001219 String8 octPtr = String8::format("OutputCommandThread: %p\n", mOutputCommandThread.get());
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001220 write(fd, octPtr.c_str(), octPtr.size());
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001221 if (mOutputCommandThread != 0) {
1222 mOutputCommandThread->dump(fd);
1223 }
1224
Eric Laurentdce54a12014-03-10 12:19:46 -07001225 if (mAudioPolicyManager) {
1226 mAudioPolicyManager->dump(fd);
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001227 } else {
1228 String8 apmPtr = String8::format("AudioPolicyManager: %p\n", mAudioPolicyManager);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001229 write(fd, apmPtr.c_str(), apmPtr.size());
Eric Laurentdce54a12014-03-10 12:19:46 -07001230 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001231
Kevin Rocard8be94972019-02-22 13:26:25 -08001232 mPackageManager.dump(fd);
1233
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001234 dumpReleaseLock(mLock, locked);
Andy Hungc747c532022-03-07 21:41:14 -08001235
Shunkai Yao59b27bc2022-07-22 18:42:27 +00001236 if (mSpatializer != nullptr) {
1237 std::string dumpString = mSpatializer->toString(1 /* level */);
1238 write(fd, dumpString.c_str(), dumpString.size());
1239 } else {
1240 String8 spatializerPtr = String8::format("Spatializer no supportted on this device\n");
1241 write(fd, spatializerPtr.c_str(), spatializerPtr.size());
1242 }
1243
Andy Hungc747c532022-03-07 21:41:14 -08001244 {
1245 std::string timeCheckStats = getIAudioPolicyServiceStatistics().dump();
1246 dprintf(fd, "\nIAudioPolicyService binder call profile\n");
1247 write(fd, timeCheckStats.c_str(), timeCheckStats.size());
1248 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001249 }
1250 return NO_ERROR;
1251}
1252
1253status_t AudioPolicyService::dumpPermissionDenial(int fd)
1254{
1255 const size_t SIZE = 256;
1256 char buffer[SIZE];
1257 String8 result;
1258 snprintf(buffer, SIZE, "Permission Denial: "
1259 "can't dump AudioPolicyService from pid=%d, uid=%d\n",
1260 IPCThreadState::self()->getCallingPid(),
1261 IPCThreadState::self()->getCallingUid());
1262 result.append(buffer);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001263 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001264 return NO_ERROR;
1265}
1266
1267status_t AudioPolicyService::onTransact(
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001268 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001269 // make sure transactions reserved to AudioFlinger do not come from other processes
1270 switch (code) {
1271 case TRANSACTION_startOutput:
1272 case TRANSACTION_stopOutput:
1273 case TRANSACTION_releaseOutput:
1274 case TRANSACTION_getInputForAttr:
1275 case TRANSACTION_startInput:
1276 case TRANSACTION_stopInput:
1277 case TRANSACTION_releaseInput:
1278 case TRANSACTION_getOutputForEffect:
1279 case TRANSACTION_registerEffect:
1280 case TRANSACTION_unregisterEffect:
1281 case TRANSACTION_setEffectEnabled:
1282 case TRANSACTION_getStrategyForStream:
1283 case TRANSACTION_getOutputForAttr:
1284 case TRANSACTION_moveEffectsToIo:
1285 ALOGW("%s: transaction %d received from PID %d",
1286 __func__, code, IPCThreadState::self()->getCallingPid());
1287 return INVALID_OPERATION;
1288 default:
1289 break;
1290 }
1291
1292 // make sure the following transactions come from system components
1293 switch (code) {
1294 case TRANSACTION_setDeviceConnectionState:
1295 case TRANSACTION_handleDeviceConfigChange:
1296 case TRANSACTION_setPhoneState:
1297//FIXME: Allow setForceUse calls from system apps until a better use case routing API is available
1298// case TRANSACTION_setForceUse:
1299 case TRANSACTION_initStreamVolume:
1300 case TRANSACTION_setStreamVolumeIndex:
1301 case TRANSACTION_setVolumeIndexForAttributes:
1302 case TRANSACTION_getStreamVolumeIndex:
1303 case TRANSACTION_getVolumeIndexForAttributes:
1304 case TRANSACTION_getMinVolumeIndexForAttributes:
1305 case TRANSACTION_getMaxVolumeIndexForAttributes:
1306 case TRANSACTION_isStreamActive:
1307 case TRANSACTION_isStreamActiveRemotely:
1308 case TRANSACTION_isSourceActive:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001309 case TRANSACTION_registerPolicyMixes:
1310 case TRANSACTION_setMasterMono:
1311 case TRANSACTION_getSurroundFormats:
Kriti Dang6537def2021-03-02 13:46:59 +01001312 case TRANSACTION_getReportedSurroundFormats:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001313 case TRANSACTION_setSurroundFormatEnabled:
Oscar Azucena829d90d2022-01-28 17:17:56 -08001314 case TRANSACTION_setAssistantServicesUids:
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001315 case TRANSACTION_setActiveAssistantServicesUids:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001316 case TRANSACTION_setA11yServicesUids:
1317 case TRANSACTION_setUidDeviceAffinities:
1318 case TRANSACTION_removeUidDeviceAffinities:
1319 case TRANSACTION_setUserIdDeviceAffinities:
1320 case TRANSACTION_removeUserIdDeviceAffinities:
Pattydd807582021-11-04 21:01:03 +08001321 case TRANSACTION_getHwOffloadFormatsSupportedForBluetoothMedia:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001322 case TRANSACTION_listAudioVolumeGroups:
1323 case TRANSACTION_getVolumeGroupFromAudioAttributes:
1324 case TRANSACTION_acquireSoundTriggerSession:
1325 case TRANSACTION_releaseSoundTriggerSession:
Atneya Nair698f5ef2022-12-15 16:15:09 -08001326 case TRANSACTION_isHotwordStreamSupported:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001327 case TRANSACTION_setRttEnabled:
1328 case TRANSACTION_isCallScreenModeSupported:
1329 case TRANSACTION_setDevicesRoleForStrategy:
1330 case TRANSACTION_setSupportedSystemUsages:
1331 case TRANSACTION_removeDevicesRoleForStrategy:
Paul Wang5d7cdb52022-11-22 09:45:06 +00001332 case TRANSACTION_clearDevicesRoleForStrategy:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001333 case TRANSACTION_getDevicesForRoleAndStrategy:
1334 case TRANSACTION_getDevicesForAttributes:
1335 case TRANSACTION_setAllowedCapturePolicy:
1336 case TRANSACTION_onNewAudioModulesAvailable:
1337 case TRANSACTION_setCurrentImeUid:
1338 case TRANSACTION_registerSoundTriggerCaptureStateListener:
1339 case TRANSACTION_setDevicesRoleForCapturePreset:
1340 case TRANSACTION_addDevicesRoleForCapturePreset:
1341 case TRANSACTION_removeDevicesRoleForCapturePreset:
1342 case TRANSACTION_clearDevicesRoleForCapturePreset:
Eric Laurent81dd0f52021-07-05 11:54:40 +02001343 case TRANSACTION_getDevicesForRoleAndCapturePreset:
jiabina84c3d32022-12-02 18:59:55 +00001344 case TRANSACTION_getSpatializer:
1345 case TRANSACTION_setPreferredMixerAttributes:
1346 case TRANSACTION_clearPreferredMixerAttributes: {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001347 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
1348 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
1349 __func__, code, IPCThreadState::self()->getCallingPid(),
1350 IPCThreadState::self()->getCallingUid());
1351 return INVALID_OPERATION;
1352 }
1353 } break;
1354 default:
1355 break;
1356 }
1357
Andy Hungc747c532022-03-07 21:41:14 -08001358 const std::string methodName = getIAudioPolicyServiceStatistics().getMethodForCode(code);
1359 mediautils::TimeCheck check(
1360 std::string("IAudioPolicyService::").append(methodName),
1361 [code, methodName](bool timeout, float elapsedMs) { // don't move methodName.
1362 if (timeout) {
1363 mediametrics::LogItem(AMEDIAMETRICS_KEY_AUDIO_POLICY)
1364 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_TIMEOUT)
1365 .set(AMEDIAMETRICS_PROP_METHODCODE, int64_t(code))
1366 .set(AMEDIAMETRICS_PROP_METHODNAME, methodName.c_str())
1367 .record();
1368 } else {
1369 getIAudioPolicyServiceStatistics().event(code, elapsedMs);
1370 }
Andy Hung741b3dd2022-06-13 19:49:43 -07001371 }, mediautils::TimeCheck::kDefaultTimeoutDuration,
1372 mediautils::TimeCheck::kDefaultSecondChanceDuration,
1373 true /* crashOnTimeout */);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001374
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001375 switch (code) {
1376 case SHELL_COMMAND_TRANSACTION: {
1377 int in = data.readFileDescriptor();
1378 int out = data.readFileDescriptor();
1379 int err = data.readFileDescriptor();
1380 int argc = data.readInt32();
1381 Vector<String16> args;
1382 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
1383 args.add(data.readString16());
1384 }
1385 sp<IBinder> unusedCallback;
1386 sp<IResultReceiver> resultReceiver;
1387 status_t status;
1388 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
1389 return status;
1390 }
1391 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
1392 return status;
1393 }
1394 status = shellCommand(in, out, err, args);
1395 if (resultReceiver != nullptr) {
1396 resultReceiver->send(status);
1397 }
1398 return NO_ERROR;
1399 }
1400 }
1401
Mathias Agopian65ab4712010-07-14 17:59:35 -07001402 return BnAudioPolicyService::onTransact(code, data, reply, flags);
1403}
1404
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001405// ------------------- Shell command implementation -------------------
1406
1407// NOTE: This is a remote API - make sure all args are validated
1408status_t AudioPolicyService::shellCommand(int in, int out, int err, Vector<String16>& args) {
1409 if (!checkCallingPermission(sManageAudioPolicyPermission, nullptr, nullptr)) {
1410 return PERMISSION_DENIED;
1411 }
1412 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
1413 return BAD_VALUE;
1414 }
jovanakbe066e12019-09-02 11:54:39 -07001415 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001416 return handleSetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001417 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001418 return handleResetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001419 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001420 return handleGetUidState(args, out, err);
Eric Laurent269acb42021-04-23 16:53:22 +02001421 } else if (args.size() >= 1 && args[0] == String16("purge_permission-cache")) {
1422 purgePermissionCache();
1423 return NO_ERROR;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001424 } else if (args.size() == 1 && args[0] == String16("help")) {
1425 printHelp(out);
1426 return NO_ERROR;
1427 }
1428 printHelp(err);
1429 return BAD_VALUE;
1430}
1431
jovanakbe066e12019-09-02 11:54:39 -07001432static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1433 if (userId < 0) {
1434 ALOGE("Invalid user: %d", userId);
1435 dprintf(err, "Invalid user: %d\n", userId);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001436 return BAD_VALUE;
1437 }
jovanakbe066e12019-09-02 11:54:39 -07001438
1439 PermissionController pc;
1440 uid = pc.getPackageUid(packageName, 0);
1441 if (uid <= 0) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001442 ALOGE("Unknown package: '%s'", String8(packageName).c_str());
1443 dprintf(err, "Unknown package: '%s'\n", String8(packageName).c_str());
jovanakbe066e12019-09-02 11:54:39 -07001444 return BAD_VALUE;
1445 }
1446
1447 uid = multiuser_get_uid(userId, uid);
1448 return NO_ERROR;
1449}
1450
1451status_t AudioPolicyService::handleSetUidState(Vector<String16>& args, int err) {
1452 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
1453 if (!(args.size() == 3 || args.size() == 5)) {
1454 printHelp(err);
1455 return BAD_VALUE;
1456 }
1457
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001458 bool active = false;
1459 if (args[2] == String16("active")) {
1460 active = true;
1461 } else if ((args[2] != String16("idle"))) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001462 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).c_str());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001463 return BAD_VALUE;
1464 }
jovanakbe066e12019-09-02 11:54:39 -07001465
1466 int userId = 0;
1467 if (args.size() >= 5 && args[3] == String16("--user")) {
1468 userId = atoi(String8(args[4]));
1469 }
1470
1471 uid_t uid;
1472 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1473 return BAD_VALUE;
1474 }
1475
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001476 sp<UidPolicy> uidPolicy;
1477 {
1478 Mutex::Autolock _l(mLock);
1479 uidPolicy = mUidPolicy;
1480 }
1481 if (uidPolicy) {
1482 uidPolicy->addOverrideUid(uid, active);
1483 return NO_ERROR;
1484 }
1485 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001486}
1487
1488status_t AudioPolicyService::handleResetUidState(Vector<String16>& args, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001489 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1490 if (!(args.size() == 2 || args.size() == 4)) {
1491 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001492 return BAD_VALUE;
1493 }
jovanakbe066e12019-09-02 11:54:39 -07001494
1495 int userId = 0;
1496 if (args.size() >= 4 && args[2] == String16("--user")) {
1497 userId = atoi(String8(args[3]));
1498 }
1499
1500 uid_t uid;
1501 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1502 return BAD_VALUE;
1503 }
1504
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001505 sp<UidPolicy> uidPolicy;
1506 {
1507 Mutex::Autolock _l(mLock);
1508 uidPolicy = mUidPolicy;
1509 }
1510 if (uidPolicy) {
1511 uidPolicy->removeOverrideUid(uid);
1512 return NO_ERROR;
1513 }
1514 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001515}
1516
1517status_t AudioPolicyService::handleGetUidState(Vector<String16>& args, int out, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001518 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1519 if (!(args.size() == 2 || args.size() == 4)) {
1520 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001521 return BAD_VALUE;
1522 }
jovanakbe066e12019-09-02 11:54:39 -07001523
1524 int userId = 0;
1525 if (args.size() >= 4 && args[2] == String16("--user")) {
1526 userId = atoi(String8(args[3]));
1527 }
1528
1529 uid_t uid;
1530 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1531 return BAD_VALUE;
1532 }
1533
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001534 sp<UidPolicy> uidPolicy;
1535 {
1536 Mutex::Autolock _l(mLock);
1537 uidPolicy = mUidPolicy;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001538 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001539 if (uidPolicy) {
1540 return dprintf(out, uidPolicy->isUidActive(uid) ? "active\n" : "idle\n");
1541 }
1542 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001543}
1544
1545status_t AudioPolicyService::printHelp(int out) {
1546 return dprintf(out, "Audio policy service commands:\n"
jovanakbe066e12019-09-02 11:54:39 -07001547 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
1548 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
1549 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001550 " help print this message\n");
1551}
1552
Eric Laurent0d13fea2022-11-04 17:12:08 +01001553status_t AudioPolicyService::registerOutput(audio_io_handle_t output,
1554 const audio_config_base_t& config,
1555 const audio_output_flags_t flags) {
1556 return mUsecaseValidator->registerStream(output, config, flags);
1557}
1558
1559status_t AudioPolicyService::unregisterOutput(audio_io_handle_t output) {
1560 return mUsecaseValidator->unregisterStream(output);
1561}
1562
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001563// ----------- AudioPolicyService::UidPolicy implementation ----------
1564
1565void AudioPolicyService::UidPolicy::registerSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001566 status_t res = mAm.linkToDeath(this);
1567 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001568 | ActivityManager::UID_OBSERVER_IDLE
Eric Laurente8c8b432018-10-17 10:08:02 -07001569 | ActivityManager::UID_OBSERVER_ACTIVE
1570 | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001571 ActivityManager::PROCESS_STATE_UNKNOWN,
1572 String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001573 if (!res) {
1574 Mutex::Autolock _l(mLock);
1575 mObserverRegistered = true;
1576 } else {
1577 ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001578
Steven Moreland2f348142019-07-02 15:59:07 -07001579 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001580 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001581}
1582
1583void AudioPolicyService::UidPolicy::unregisterSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001584 mAm.unlinkToDeath(this);
1585 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001586 Mutex::Autolock _l(mLock);
1587 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001588}
1589
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001590void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
1591 Mutex::Autolock _l(mLock);
1592 mCachedUids.clear();
1593 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001594}
1595
Eric Laurente8c8b432018-10-17 10:08:02 -07001596void AudioPolicyService::UidPolicy::checkRegistered() {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001597 bool needToReregister = false;
1598 {
1599 Mutex::Autolock _l(mLock);
1600 needToReregister = !mObserverRegistered;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001601 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001602 if (needToReregister) {
1603 // Looks like ActivityManager has died previously, attempt to re-register.
1604 registerSelf();
1605 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001606}
1607
1608bool AudioPolicyService::UidPolicy::isUidActive(uid_t uid) {
1609 if (isServiceUid(uid)) return true;
1610 checkRegistered();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001611 {
1612 Mutex::Autolock _l(mLock);
1613 auto overrideIter = mOverrideUids.find(uid);
1614 if (overrideIter != mOverrideUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001615 return overrideIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001616 }
1617 // In an absense of the ActivityManager, assume everything to be active.
1618 if (!mObserverRegistered) return true;
1619 auto cacheIter = mCachedUids.find(uid);
Mikhail Naganoveba668a2018-04-05 08:13:15 -07001620 if (cacheIter != mCachedUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001621 return cacheIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001622 }
1623 }
1624 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001625 bool active = am.isUidActive(uid, String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001626 {
1627 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001628 mCachedUids.insert(std::pair<uid_t,
1629 std::pair<bool, int>>(uid, std::pair<bool, int>(active,
1630 ActivityManager::PROCESS_STATE_UNKNOWN)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001631 }
1632 return active;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001633}
1634
Eric Laurente8c8b432018-10-17 10:08:02 -07001635int AudioPolicyService::UidPolicy::getUidState(uid_t uid) {
1636 if (isServiceUid(uid)) {
1637 return ActivityManager::PROCESS_STATE_TOP;
1638 }
1639 checkRegistered();
1640 {
1641 Mutex::Autolock _l(mLock);
1642 auto overrideIter = mOverrideUids.find(uid);
1643 if (overrideIter != mOverrideUids.end()) {
1644 if (overrideIter->second.first) {
1645 if (overrideIter->second.second != ActivityManager::PROCESS_STATE_UNKNOWN) {
1646 return overrideIter->second.second;
1647 } else {
1648 auto cacheIter = mCachedUids.find(uid);
1649 if (cacheIter != mCachedUids.end()) {
1650 return cacheIter->second.second;
1651 }
1652 }
1653 }
1654 return ActivityManager::PROCESS_STATE_UNKNOWN;
1655 }
1656 // In an absense of the ActivityManager, assume everything to be active.
1657 if (!mObserverRegistered) {
1658 return ActivityManager::PROCESS_STATE_TOP;
1659 }
1660 auto cacheIter = mCachedUids.find(uid);
1661 if (cacheIter != mCachedUids.end()) {
1662 if (cacheIter->second.first) {
1663 return cacheIter->second.second;
1664 } else {
1665 return ActivityManager::PROCESS_STATE_UNKNOWN;
1666 }
1667 }
1668 }
1669 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001670 bool active = am.isUidActive(uid, String16("audioserver"));
Eric Laurente8c8b432018-10-17 10:08:02 -07001671 int state = ActivityManager::PROCESS_STATE_UNKNOWN;
1672 if (active) {
1673 state = am.getUidProcessState(uid, String16("audioserver"));
1674 }
1675 {
1676 Mutex::Autolock _l(mLock);
1677 mCachedUids.insert(std::pair<uid_t,
1678 std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
1679 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001680
Eric Laurente8c8b432018-10-17 10:08:02 -07001681 return state;
1682}
1683
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001684void AudioPolicyService::UidPolicy::onUidActive(uid_t uid) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001685 updateUid(&mCachedUids, uid, true, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001686}
1687
1688void AudioPolicyService::UidPolicy::onUidGone(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001689 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, false);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001690}
1691
1692void AudioPolicyService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001693 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001694}
1695
Eric Laurente8c8b432018-10-17 10:08:02 -07001696void AudioPolicyService::UidPolicy::onUidStateChanged(uid_t uid,
1697 int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07001698 int64_t procStateSeq __unused,
1699 int32_t capability __unused) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001700 if (procState != ActivityManager::PROCESS_STATE_UNKNOWN) {
1701 updateUid(&mCachedUids, uid, true, procState, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001702 }
1703}
1704
Austin Borgerdddb7552023-03-30 17:53:01 -07001705void AudioPolicyService::UidPolicy::onUidProcAdjChanged(uid_t uid __unused, int32_t adj __unused) {
Austin Borger65577682022-02-17 00:25:43 +00001706}
1707
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001708void AudioPolicyService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001709 updateUid(&mOverrideUids, uid, active, ActivityManager::PROCESS_STATE_UNKNOWN, insert);
1710}
1711
1712void AudioPolicyService::UidPolicy::notifyService() {
1713 sp<AudioPolicyService> service = mService.promote();
1714 if (service != nullptr) {
1715 service->updateUidStates();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001716 }
1717}
1718
Eric Laurente8c8b432018-10-17 10:08:02 -07001719void AudioPolicyService::UidPolicy::updateUid(std::unordered_map<uid_t,
1720 std::pair<bool, int>> *uids,
1721 uid_t uid,
1722 bool active,
1723 int state,
1724 bool insert) {
1725 if (isServiceUid(uid)) {
1726 return;
1727 }
1728 bool wasActive = isUidActive(uid);
1729 int previousState = getUidState(uid);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001730 {
1731 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001732 updateUidLocked(uids, uid, active, state, insert);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001733 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001734 if (wasActive != isUidActive(uid) || state != previousState) {
1735 notifyService();
1736 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001737}
1738
Eric Laurente8c8b432018-10-17 10:08:02 -07001739void AudioPolicyService::UidPolicy::updateUidLocked(std::unordered_map<uid_t,
1740 std::pair<bool, int>> *uids,
1741 uid_t uid,
1742 bool active,
1743 int state,
1744 bool insert) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001745 auto it = uids->find(uid);
1746 if (it != uids->end()) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001747 if (insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001748 if (state == ActivityManager::PROCESS_STATE_UNKNOWN) {
1749 it->second.first = active;
1750 }
1751 if (it->second.first) {
1752 it->second.second = state;
1753 } else {
1754 it->second.second = ActivityManager::PROCESS_STATE_UNKNOWN;
1755 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001756 } else {
1757 uids->erase(it);
1758 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001759 } else if (insert && (state == ActivityManager::PROCESS_STATE_UNKNOWN)) {
1760 uids->insert(std::pair<uid_t, std::pair<bool, int>>(uid,
1761 std::pair<bool, int>(active, state)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001762 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001763}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001764
Eric Laurent4eb58f12018-12-07 16:41:02 -08001765bool AudioPolicyService::UidPolicy::isA11yOnTop() {
lihong80e1f56e2022-08-25 11:15:33 +08001766 Mutex::Autolock _l(mLock);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001767 for (const auto &uid : mCachedUids) {
Eric Laurent47670c92019-08-28 16:59:05 -07001768 if (!isA11yUid(uid.first)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001769 continue;
1770 }
Amith Yamasanibcbb3002019-01-23 13:53:33 -08001771 if (uid.second.second >= ActivityManager::PROCESS_STATE_TOP
1772 && uid.second.second <= ActivityManager::PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001773 return true;
1774 }
1775 }
1776 return false;
1777}
1778
Eric Laurentb78763e2018-10-17 10:08:02 -07001779bool AudioPolicyService::UidPolicy::isA11yUid(uid_t uid)
1780{
1781 std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid);
1782 return it != mA11yUids.end();
1783}
1784
Oscar Azucena829d90d2022-01-28 17:17:56 -08001785void AudioPolicyService::UidPolicy::setAssistantUids(const std::vector<uid_t>& uids) {
1786 mAssistantUids.clear();
1787 mAssistantUids = uids;
1788}
1789
1790bool AudioPolicyService::UidPolicy::isAssistantUid(uid_t uid)
1791{
1792 std::vector<uid_t>::iterator it = find(mAssistantUids.begin(), mAssistantUids.end(), uid);
1793 return it != mAssistantUids.end();
1794}
1795
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001796void AudioPolicyService::UidPolicy::setActiveAssistantUids(const std::vector<uid_t>& activeUids) {
1797 mActiveAssistantUids = activeUids;
1798}
1799
1800bool AudioPolicyService::UidPolicy::isActiveAssistantUid(uid_t uid)
1801{
1802 std::vector<uid_t>::iterator it = find(mActiveAssistantUids.begin(),
1803 mActiveAssistantUids.end(), uid);
1804 return it != mActiveAssistantUids.end();
1805}
1806
Oscar Azucena829d90d2022-01-28 17:17:56 -08001807void AudioPolicyService::UidPolicy::dumpInternals(int fd) {
1808 const size_t SIZE = 256;
1809 char buffer[SIZE];
1810 String8 result;
1811 auto appendUidsToResult = [&](const char* title, const std::vector<uid_t> &uids) {
1812 snprintf(buffer, SIZE, "\t%s: \n", title);
1813 result.append(buffer);
1814 int counter = 0;
1815 if (uids.empty()) {
1816 snprintf(buffer, SIZE, "\t\tNo UIDs present.\n");
1817 result.append(buffer);
1818 return;
1819 }
1820 for (const auto &uid : uids) {
1821 snprintf(buffer, SIZE, "\t\tUID[%d]=%d\n", counter++, uid);
1822 result.append(buffer);
1823 }
1824 };
1825
1826 snprintf(buffer, SIZE, "UID Policy:\n");
1827 result.append(buffer);
1828 snprintf(buffer, SIZE, "\tmObserverRegistered=%s\n",(mObserverRegistered ? "True":"False"));
1829 result.append(buffer);
1830
1831 appendUidsToResult("Assistants UIDs", mAssistantUids);
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001832 appendUidsToResult("Active Assistants UIDs", mActiveAssistantUids);
Oscar Azucena829d90d2022-01-28 17:17:56 -08001833
1834 appendUidsToResult("Accessibility UIDs", mA11yUids);
1835
1836 snprintf(buffer, SIZE, "\tInput Method Service UID=%d\n", mCurrentImeUid);
1837 result.append(buffer);
1838
1839 snprintf(buffer, SIZE, "\tIs RTT Enabled: %s\n", (mRttEnabled ? "True":"False"));
1840 result.append(buffer);
1841
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001842 write(fd, result.c_str(), result.size());
Oscar Azucena829d90d2022-01-28 17:17:56 -08001843}
1844
Michael Groovercfd28302018-12-11 19:16:46 -08001845// ----------- AudioPolicyService::SensorPrivacyService implementation ----------
1846void AudioPolicyService::SensorPrivacyPolicy::registerSelf() {
1847 SensorPrivacyManager spm;
1848 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1849 spm.addSensorPrivacyListener(this);
1850}
1851
1852void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
1853 SensorPrivacyManager spm;
1854 spm.removeSensorPrivacyListener(this);
1855}
1856
1857bool AudioPolicyService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1858 return mSensorPrivacyEnabled;
1859}
1860
Evan Seversond8dc6832022-01-27 10:47:03 -08001861binder::Status AudioPolicyService::SensorPrivacyPolicy::onSensorPrivacyChanged(
1862 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Groovercfd28302018-12-11 19:16:46 -08001863 mSensorPrivacyEnabled = enabled;
1864 sp<AudioPolicyService> service = mService.promote();
1865 if (service != nullptr) {
1866 service->updateUidStates();
1867 }
1868 return binder::Status::ok();
1869}
1870
Mathias Agopian65ab4712010-07-14 17:59:35 -07001871// ----------- AudioPolicyService::AudioCommandThread implementation ----------
1872
Eric Laurentbfb1b832013-01-07 09:53:42 -08001873AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
1874 const wp<AudioPolicyService>& service)
1875 : Thread(false), mName(name), mService(service)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001876{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001877}
1878
1879
1880AudioPolicyService::AudioCommandThread::~AudioCommandThread()
1881{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001882 if (!mAudioCommands.isEmpty()) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001883 release_wake_lock(mName.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001884 }
1885 mAudioCommands.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001886}
1887
1888void AudioPolicyService::AudioCommandThread::onFirstRef()
1889{
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001890 run(mName.c_str(), ANDROID_PRIORITY_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001891}
1892
1893bool AudioPolicyService::AudioCommandThread::threadLoop()
1894{
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001895 nsecs_t waitTime = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001896
1897 mLock.lock();
1898 while (!exitPending())
1899 {
Eric Laurent59a89232014-06-08 14:14:17 -07001900 sp<AudioPolicyService> svc;
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07001901 int numTimesBecameEmpty = 0;
Eric Laurent59a89232014-06-08 14:14:17 -07001902 while (!mAudioCommands.isEmpty() && !exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001903 nsecs_t curTime = systemTime();
1904 // commands are sorted by increasing time stamp: execute them from index 0 and up
1905 if (mAudioCommands[0]->mTime <= curTime) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001906 sp<AudioCommand> command = mAudioCommands[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001907 mAudioCommands.removeAt(0);
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07001908 if (mAudioCommands.isEmpty()) {
1909 ++numTimesBecameEmpty;
1910 }
Eric Laurent0ede8922014-05-09 18:04:42 -07001911 mLastCommand = command;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001912
1913 switch (command->mCommand) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001914 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001915 VolumeData *data = (VolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001916 ALOGV("AudioCommandThread() processing set volume stream %d, \
Eric Laurentde070132010-07-13 04:45:46 -07001917 volume %f, output %d", data->mStream, data->mVolume, data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001918 mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07001919 command->mStatus = AudioSystem::setStreamVolume(data->mStream,
1920 data->mVolume,
1921 data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001922 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001923 }break;
1924 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001925 ParametersData *data = (ParametersData *)command->mParam.get();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001926 ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001927 data->mKeyValuePairs.c_str(), data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001928 mLock.unlock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001929 command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
Andy Hungfe726a62018-09-27 15:17:25 -07001930 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001931 }break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001932 case SET_VOICE_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001933 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001934 ALOGV("AudioCommandThread() processing set voice volume volume %f",
Eric Laurentde070132010-07-13 04:45:46 -07001935 data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001936 mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001937 command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001938 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001939 }break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001940 case STOP_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001941 StopOutputData *data = (StopOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001942 ALOGV("AudioCommandThread() processing stop output portId %d",
1943 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001944 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001945 if (svc == 0) {
1946 break;
1947 }
1948 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001949 svc->doStopOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001950 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001951 }break;
1952 case RELEASE_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001953 ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001954 ALOGV("AudioCommandThread() processing release output portId %d",
1955 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001956 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001957 if (svc == 0) {
1958 break;
1959 }
1960 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001961 svc->doReleaseOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001962 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001963 }break;
Eric Laurent951f4552014-05-20 10:48:17 -07001964 case CREATE_AUDIO_PATCH: {
1965 CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
1966 ALOGV("AudioCommandThread() processing create audio patch");
1967 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1968 if (af == 0) {
1969 command->mStatus = PERMISSION_DENIED;
1970 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001971 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001972 command->mStatus = af->createAudioPatch(&data->mPatch, &data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001973 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001974 }
1975 } break;
1976 case RELEASE_AUDIO_PATCH: {
1977 ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
1978 ALOGV("AudioCommandThread() processing release audio patch");
1979 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1980 if (af == 0) {
1981 command->mStatus = PERMISSION_DENIED;
1982 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001983 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001984 command->mStatus = af->releaseAudioPatch(data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001985 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001986 }
1987 } break;
Eric Laurentb52c1522014-05-20 11:27:36 -07001988 case UPDATE_AUDIOPORT_LIST: {
1989 ALOGV("AudioCommandThread() processing update audio port list");
Eric Laurent59a89232014-06-08 14:14:17 -07001990 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001991 if (svc == 0) {
1992 break;
1993 }
1994 mLock.unlock();
1995 svc->doOnAudioPortListUpdate();
1996 mLock.lock();
1997 }break;
1998 case UPDATE_AUDIOPATCH_LIST: {
1999 ALOGV("AudioCommandThread() processing update audio patch list");
Eric Laurent59a89232014-06-08 14:14:17 -07002000 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07002001 if (svc == 0) {
2002 break;
2003 }
2004 mLock.unlock();
2005 svc->doOnAudioPatchListUpdate();
2006 mLock.lock();
2007 }break;
François Gaffiecfe17322018-11-07 13:41:29 +01002008 case CHANGED_AUDIOVOLUMEGROUP: {
2009 AudioVolumeGroupData *data =
2010 static_cast<AudioVolumeGroupData *>(command->mParam.get());
2011 ALOGV("AudioCommandThread() processing update audio volume group");
2012 svc = mService.promote();
2013 if (svc == 0) {
2014 break;
2015 }
2016 mLock.unlock();
2017 svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
2018 mLock.lock();
2019 }break;
Eric Laurente1715a42014-05-20 11:30:42 -07002020 case SET_AUDIOPORT_CONFIG: {
2021 SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
2022 ALOGV("AudioCommandThread() processing set port config");
2023 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
2024 if (af == 0) {
2025 command->mStatus = PERMISSION_DENIED;
2026 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07002027 mLock.unlock();
Eric Laurente1715a42014-05-20 11:30:42 -07002028 command->mStatus = af->setAudioPortConfig(&data->mConfig);
Andy Hungfe726a62018-09-27 15:17:25 -07002029 mLock.lock();
Eric Laurente1715a42014-05-20 11:30:42 -07002030 }
2031 } break;
Jean-Michel Trivide801052015-04-14 19:10:14 -07002032 case DYN_POLICY_MIX_STATE_UPDATE: {
2033 DynPolicyMixStateUpdateData *data =
2034 (DynPolicyMixStateUpdateData *)command->mParam.get();
Jean-Michel Trivide801052015-04-14 19:10:14 -07002035 ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002036 data->mRegId.c_str(), data->mState);
Jean-Michel Trivide801052015-04-14 19:10:14 -07002037 svc = mService.promote();
2038 if (svc == 0) {
2039 break;
2040 }
2041 mLock.unlock();
2042 svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
2043 mLock.lock();
2044 } break;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002045 case RECORDING_CONFIGURATION_UPDATE: {
2046 RecordingConfigurationUpdateData *data =
2047 (RecordingConfigurationUpdateData *)command->mParam.get();
2048 ALOGV("AudioCommandThread() processing recording configuration update");
2049 svc = mService.promote();
2050 if (svc == 0) {
2051 break;
2052 }
2053 mLock.unlock();
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002054 svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -08002055 &data->mClientConfig, data->mClientEffects,
2056 &data->mDeviceConfig, data->mEffects,
2057 data->mPatchHandle, data->mSource);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002058 mLock.lock();
2059 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002060 case SET_EFFECT_SUSPENDED: {
2061 SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
2062 ALOGV("AudioCommandThread() processing set effect suspended");
2063 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
2064 if (af != 0) {
2065 mLock.unlock();
2066 af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
2067 mLock.lock();
2068 }
2069 } break;
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002070 case AUDIO_MODULES_UPDATE: {
2071 ALOGV("AudioCommandThread() processing audio modules update");
2072 svc = mService.promote();
2073 if (svc == 0) {
2074 break;
2075 }
2076 mLock.unlock();
2077 svc->doOnNewAudioModulesAvailable();
2078 mLock.lock();
2079 } break;
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002080 case ROUTING_UPDATED: {
2081 ALOGV("AudioCommandThread() processing routing update");
2082 svc = mService.promote();
2083 if (svc == 0) {
2084 break;
2085 }
2086 mLock.unlock();
2087 svc->doOnRoutingUpdated();
2088 mLock.lock();
2089 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002090
Eric Laurented726cc2021-07-01 14:26:41 +02002091 case UPDATE_UID_STATES: {
2092 ALOGV("AudioCommandThread() processing updateUID states");
2093 svc = mService.promote();
2094 if (svc == 0) {
2095 break;
2096 }
2097 mLock.unlock();
2098 svc->updateUidStates();
2099 mLock.lock();
2100 } break;
2101
Eric Laurent15903592022-02-24 20:44:36 +01002102 case CHECK_SPATIALIZER_OUTPUT: {
2103 ALOGV("AudioCommandThread() processing check spatializer");
Eric Laurent81dd0f52021-07-05 11:54:40 +02002104 svc = mService.promote();
2105 if (svc == 0) {
2106 break;
2107 }
2108 mLock.unlock();
2109 svc->doOnCheckSpatializer();
2110 mLock.lock();
2111 } break;
2112
Eric Laurent15903592022-02-24 20:44:36 +01002113 case UPDATE_ACTIVE_SPATIALIZER_TRACKS: {
2114 ALOGV("AudioCommandThread() processing update spatializer tracks");
2115 svc = mService.promote();
2116 if (svc == 0) {
2117 break;
2118 }
2119 mLock.unlock();
2120 svc->doOnUpdateActiveSpatializerTracks();
2121 mLock.lock();
2122 } break;
2123
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002124 case VOL_RANGE_INIT_REQUEST: {
2125 ALOGV("AudioCommandThread() processing volume range init request");
2126 svc = mService.promote();
2127 if (svc == 0) {
2128 break;
2129 }
2130 mLock.unlock();
2131 svc->doOnVolumeRangeInitRequest();
2132 mLock.lock();
2133 } break;
2134
Mathias Agopian65ab4712010-07-14 17:59:35 -07002135 default:
Steve Block5ff1dd52012-01-05 23:22:43 +00002136 ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002137 }
Eric Laurent0ede8922014-05-09 18:04:42 -07002138 {
2139 Mutex::Autolock _l(command->mLock);
2140 if (command->mWaitStatus) {
2141 command->mWaitStatus = false;
2142 command->mCond.signal();
2143 }
2144 }
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002145 waitTime = -1;
Zach Janga754b4f2015-10-27 01:29:34 +00002146 // release mLock before releasing strong reference on the service as
2147 // AudioPolicyService destructor calls AudioCommandThread::exit() which
2148 // acquires mLock.
2149 mLock.unlock();
2150 svc.clear();
2151 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002152 } else {
2153 waitTime = mAudioCommands[0]->mTime - curTime;
2154 break;
2155 }
2156 }
Zach Janga754b4f2015-10-27 01:29:34 +00002157
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07002158 // release delayed commands wake lock as many times as we made the queue is
2159 // empty during popping.
2160 while (numTimesBecameEmpty--) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002161 release_wake_lock(mName.c_str());
Zach Janga754b4f2015-10-27 01:29:34 +00002162 }
2163
2164 // At this stage we have either an empty command queue or the first command in the queue
2165 // has a finite delay. So unless we are exiting it is safe to wait.
2166 if (!exitPending()) {
Eric Laurent59a89232014-06-08 14:14:17 -07002167 ALOGV("AudioCommandThread() going to sleep");
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002168 if (waitTime == -1) {
2169 mWaitWorkCV.wait(mLock);
2170 } else {
2171 mWaitWorkCV.waitRelative(mLock, waitTime);
2172 }
Eric Laurent59a89232014-06-08 14:14:17 -07002173 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002174 }
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002175 // release delayed commands wake lock before quitting
2176 if (!mAudioCommands.isEmpty()) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002177 release_wake_lock(mName.c_str());
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002178 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002179 mLock.unlock();
2180 return false;
2181}
2182
2183status_t AudioPolicyService::AudioCommandThread::dump(int fd)
2184{
2185 const size_t SIZE = 256;
2186 char buffer[SIZE];
2187 String8 result;
2188
Mikhail Naganov12b716c2020-04-30 22:37:43 +00002189 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002190 if (!locked) {
2191 String8 result2(kCmdDeadlockedString);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002192 write(fd, result2.c_str(), result2.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002193 }
2194
2195 snprintf(buffer, SIZE, "- Commands:\n");
2196 result = String8(buffer);
2197 result.append(" Command Time Wait pParam\n");
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002198 for (size_t i = 0; i < mAudioCommands.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002199 mAudioCommands[i]->dump(buffer, SIZE);
2200 result.append(buffer);
2201 }
2202 result.append(" Last Command\n");
Eric Laurent0ede8922014-05-09 18:04:42 -07002203 if (mLastCommand != 0) {
2204 mLastCommand->dump(buffer, SIZE);
2205 result.append(buffer);
2206 } else {
2207 result.append(" none\n");
2208 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002209
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002210 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002211
Mikhail Naganov12b716c2020-04-30 22:37:43 +00002212 dumpReleaseLock(mLock, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002213
2214 return NO_ERROR;
2215}
2216
Glenn Kastenfff6d712012-01-12 16:38:12 -08002217status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
Eric Laurentde070132010-07-13 04:45:46 -07002218 float volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002219 audio_io_handle_t output,
Eric Laurentde070132010-07-13 04:45:46 -07002220 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002221{
Eric Laurent0ede8922014-05-09 18:04:42 -07002222 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002223 command->mCommand = SET_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002224 sp<VolumeData> data = new VolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002225 data->mStream = stream;
2226 data->mVolume = volume;
2227 data->mIO = output;
2228 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002229 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002230 ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
Eric Laurentde070132010-07-13 04:45:46 -07002231 stream, volume, output);
Eric Laurent0ede8922014-05-09 18:04:42 -07002232 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002233}
2234
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002235status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
Dima Zavinfce7a472011-04-19 22:30:36 -07002236 const char *keyValuePairs,
Eric Laurentde070132010-07-13 04:45:46 -07002237 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002238{
Eric Laurent0ede8922014-05-09 18:04:42 -07002239 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002240 command->mCommand = SET_PARAMETERS;
Eric Laurent0ede8922014-05-09 18:04:42 -07002241 sp<ParametersData> data = new ParametersData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002242 data->mIO = ioHandle;
Dima Zavinfce7a472011-04-19 22:30:36 -07002243 data->mKeyValuePairs = String8(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002244 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002245 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002246 ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
Dima Zavinfce7a472011-04-19 22:30:36 -07002247 keyValuePairs, ioHandle, delayMs);
Eric Laurent0ede8922014-05-09 18:04:42 -07002248 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002249}
2250
2251status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
2252{
Eric Laurent0ede8922014-05-09 18:04:42 -07002253 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002254 command->mCommand = SET_VOICE_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002255 sp<VoiceVolumeData> data = new VoiceVolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002256 data->mVolume = volume;
2257 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002258 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002259 ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
Eric Laurent0ede8922014-05-09 18:04:42 -07002260 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002261}
2262
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002263void AudioPolicyService::AudioCommandThread::setEffectSuspendedCommand(int effectId,
2264 audio_session_t sessionId,
2265 bool suspended)
2266{
2267 sp<AudioCommand> command = new AudioCommand();
2268 command->mCommand = SET_EFFECT_SUSPENDED;
2269 sp<SetEffectSuspendedData> data = new SetEffectSuspendedData();
2270 data->mEffectId = effectId;
2271 data->mSessionId = sessionId;
2272 data->mSuspended = suspended;
2273 command->mParam = data;
2274 ALOGV("AudioCommandThread() adding set suspended effectId %d sessionId %d suspended %d",
2275 effectId, sessionId, suspended);
2276 sendCommand(command);
2277}
2278
2279
Eric Laurentd7fe0862018-07-14 16:48:01 -07002280void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002281{
Eric Laurent0ede8922014-05-09 18:04:42 -07002282 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002283 command->mCommand = STOP_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002284 sp<StopOutputData> data = new StopOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002285 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002286 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002287 ALOGV("AudioCommandThread() adding stop output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002288 sendCommand(command);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002289}
2290
Eric Laurentd7fe0862018-07-14 16:48:01 -07002291void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002292{
Eric Laurent0ede8922014-05-09 18:04:42 -07002293 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002294 command->mCommand = RELEASE_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002295 sp<ReleaseOutputData> data = new ReleaseOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002296 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002297 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002298 ALOGV("AudioCommandThread() adding release output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002299 sendCommand(command);
2300}
2301
Eric Laurent951f4552014-05-20 10:48:17 -07002302status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
2303 const struct audio_patch *patch,
2304 audio_patch_handle_t *handle,
2305 int delayMs)
2306{
2307 status_t status = NO_ERROR;
2308
2309 sp<AudioCommand> command = new AudioCommand();
2310 command->mCommand = CREATE_AUDIO_PATCH;
2311 CreateAudioPatchData *data = new CreateAudioPatchData();
2312 data->mPatch = *patch;
2313 data->mHandle = *handle;
2314 command->mParam = data;
2315 command->mWaitStatus = true;
2316 ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
2317 status = sendCommand(command, delayMs);
2318 if (status == NO_ERROR) {
2319 *handle = data->mHandle;
2320 }
2321 return status;
2322}
2323
2324status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
2325 int delayMs)
2326{
2327 sp<AudioCommand> command = new AudioCommand();
2328 command->mCommand = RELEASE_AUDIO_PATCH;
2329 ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
2330 data->mHandle = handle;
2331 command->mParam = data;
2332 command->mWaitStatus = true;
2333 ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
2334 return sendCommand(command, delayMs);
2335}
2336
Eric Laurentb52c1522014-05-20 11:27:36 -07002337void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
2338{
2339 sp<AudioCommand> command = new AudioCommand();
2340 command->mCommand = UPDATE_AUDIOPORT_LIST;
2341 ALOGV("AudioCommandThread() adding update audio port list");
2342 sendCommand(command);
2343}
2344
Eric Laurented726cc2021-07-01 14:26:41 +02002345void AudioPolicyService::AudioCommandThread::updateUidStatesCommand()
2346{
2347 sp<AudioCommand> command = new AudioCommand();
2348 command->mCommand = UPDATE_UID_STATES;
2349 ALOGV("AudioCommandThread() adding update UID states");
2350 sendCommand(command);
2351}
2352
Eric Laurentb52c1522014-05-20 11:27:36 -07002353void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
2354{
2355 sp<AudioCommand>command = new AudioCommand();
2356 command->mCommand = UPDATE_AUDIOPATCH_LIST;
2357 ALOGV("AudioCommandThread() adding update audio patch list");
2358 sendCommand(command);
2359}
2360
François Gaffiecfe17322018-11-07 13:41:29 +01002361void AudioPolicyService::AudioCommandThread::changeAudioVolumeGroupCommand(volume_group_t group,
2362 int flags)
2363{
2364 sp<AudioCommand>command = new AudioCommand();
2365 command->mCommand = CHANGED_AUDIOVOLUMEGROUP;
2366 AudioVolumeGroupData *data= new AudioVolumeGroupData();
2367 data->mGroup = group;
2368 data->mFlags = flags;
2369 command->mParam = data;
2370 ALOGV("AudioCommandThread() adding audio volume group changed");
2371 sendCommand(command);
2372}
2373
Eric Laurente1715a42014-05-20 11:30:42 -07002374status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
2375 const struct audio_port_config *config, int delayMs)
2376{
2377 sp<AudioCommand> command = new AudioCommand();
2378 command->mCommand = SET_AUDIOPORT_CONFIG;
2379 SetAudioPortConfigData *data = new SetAudioPortConfigData();
2380 data->mConfig = *config;
2381 command->mParam = data;
2382 command->mWaitStatus = true;
2383 ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
2384 return sendCommand(command, delayMs);
2385}
2386
Jean-Michel Trivide801052015-04-14 19:10:14 -07002387void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002388 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -07002389{
2390 sp<AudioCommand> command = new AudioCommand();
2391 command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
2392 DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
2393 data->mRegId = regId;
2394 data->mState = state;
2395 command->mParam = data;
2396 ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002397 regId.c_str(), state);
Jean-Michel Trivide801052015-04-14 19:10:14 -07002398 sendCommand(command);
2399}
2400
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002401void AudioPolicyService::AudioCommandThread::recordingConfigurationUpdateCommand(
Eric Laurenta9f86652018-11-28 17:23:11 -08002402 int event,
2403 const record_client_info_t *clientInfo,
2404 const audio_config_base_t *clientConfig,
2405 std::vector<effect_descriptor_t> clientEffects,
2406 const audio_config_base_t *deviceConfig,
2407 std::vector<effect_descriptor_t> effects,
2408 audio_patch_handle_t patchHandle,
2409 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002410{
2411 sp<AudioCommand>command = new AudioCommand();
2412 command->mCommand = RECORDING_CONFIGURATION_UPDATE;
2413 RecordingConfigurationUpdateData *data = new RecordingConfigurationUpdateData();
2414 data->mEvent = event;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002415 data->mClientInfo = *clientInfo;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002416 data->mClientConfig = *clientConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002417 data->mClientEffects = clientEffects;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002418 data->mDeviceConfig = *deviceConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002419 data->mEffects = effects;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002420 data->mPatchHandle = patchHandle;
Eric Laurenta9f86652018-11-28 17:23:11 -08002421 data->mSource = source;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002422 command->mParam = data;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002423 ALOGV("AudioCommandThread() adding recording configuration update event %d, source %d uid %u",
2424 event, clientInfo->source, clientInfo->uid);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002425 sendCommand(command);
2426}
2427
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002428void AudioPolicyService::AudioCommandThread::audioModulesUpdateCommand()
2429{
2430 sp<AudioCommand> command = new AudioCommand();
2431 command->mCommand = AUDIO_MODULES_UPDATE;
2432 sendCommand(command);
2433}
2434
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002435void AudioPolicyService::AudioCommandThread::routingChangedCommand()
2436{
2437 sp<AudioCommand>command = new AudioCommand();
2438 command->mCommand = ROUTING_UPDATED;
2439 ALOGV("AudioCommandThread() adding routing update");
2440 sendCommand(command);
2441}
2442
Eric Laurent81dd0f52021-07-05 11:54:40 +02002443void AudioPolicyService::AudioCommandThread::checkSpatializerCommand()
2444{
2445 sp<AudioCommand>command = new AudioCommand();
Eric Laurent15903592022-02-24 20:44:36 +01002446 command->mCommand = CHECK_SPATIALIZER_OUTPUT;
Eric Laurent81dd0f52021-07-05 11:54:40 +02002447 ALOGV("AudioCommandThread() adding check spatializer");
2448 sendCommand(command);
2449}
2450
Eric Laurent15903592022-02-24 20:44:36 +01002451void AudioPolicyService::AudioCommandThread::updateActiveSpatializerTracksCommand()
2452{
2453 sp<AudioCommand>command = new AudioCommand();
2454 command->mCommand = UPDATE_ACTIVE_SPATIALIZER_TRACKS;
2455 ALOGV("AudioCommandThread() adding update active spatializer tracks");
2456 sendCommand(command);
2457}
2458
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002459void AudioPolicyService::AudioCommandThread::volRangeInitReqCommand()
2460{
2461 sp<AudioCommand>command = new AudioCommand();
2462 command->mCommand = VOL_RANGE_INIT_REQUEST;
2463 ALOGV("AudioCommandThread() adding volume range init request");
2464 sendCommand(command);
2465}
2466
Eric Laurent0ede8922014-05-09 18:04:42 -07002467status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
2468{
2469 {
2470 Mutex::Autolock _l(mLock);
2471 insertCommand_l(command, delayMs);
2472 mWaitWorkCV.signal();
2473 }
2474 Mutex::Autolock _l(command->mLock);
2475 while (command->mWaitStatus) {
2476 nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
2477 if (command->mCond.waitRelative(command->mLock, timeOutNs) != NO_ERROR) {
2478 command->mStatus = TIMED_OUT;
2479 command->mWaitStatus = false;
2480 }
2481 }
2482 return command->mStatus;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002483}
2484
Mathias Agopian65ab4712010-07-14 17:59:35 -07002485// insertCommand_l() must be called with mLock held
Eric Laurent0ede8922014-05-09 18:04:42 -07002486void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002487{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002488 ssize_t i; // not size_t because i will count down to -1
Eric Laurent0ede8922014-05-09 18:04:42 -07002489 Vector < sp<AudioCommand> > removedCommands;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002490 command->mTime = systemTime() + milliseconds(delayMs);
2491
2492 // acquire wake lock to make sure delayed commands are processed
Eric Laurentbfb1b832013-01-07 09:53:42 -08002493 if (mAudioCommands.isEmpty()) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002494 acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002495 }
2496
2497 // check same pending commands with later time stamps and eliminate them
Ivan Lozano5ff158f2017-10-30 09:06:24 -07002498 for (i = (ssize_t)mAudioCommands.size()-1; i >= 0; i--) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002499 sp<AudioCommand> command2 = mAudioCommands[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07002500 // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
2501 if (command2->mTime <= command->mTime) break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002502
2503 // create audio patch or release audio patch commands are equivalent
2504 // with regard to filtering
2505 if ((command->mCommand == CREATE_AUDIO_PATCH) ||
2506 (command->mCommand == RELEASE_AUDIO_PATCH)) {
2507 if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
2508 (command2->mCommand != RELEASE_AUDIO_PATCH)) {
2509 continue;
2510 }
2511 } else if (command2->mCommand != command->mCommand) continue;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002512
2513 switch (command->mCommand) {
2514 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002515 ParametersData *data = (ParametersData *)command->mParam.get();
2516 ParametersData *data2 = (ParametersData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002517 if (data->mIO != data2->mIO) break;
Steve Block3856b092011-10-20 11:56:00 +01002518 ALOGV("Comparing parameter command %s to new command %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002519 data2->mKeyValuePairs.c_str(), data->mKeyValuePairs.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002520 AudioParameter param = AudioParameter(data->mKeyValuePairs);
2521 AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
2522 for (size_t j = 0; j < param.size(); j++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002523 String8 key;
2524 String8 value;
2525 param.getAt(j, key, value);
2526 for (size_t k = 0; k < param2.size(); k++) {
2527 String8 key2;
2528 String8 value2;
2529 param2.getAt(k, key2, value2);
2530 if (key2 == key) {
2531 param2.remove(key2);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002532 ALOGV("Filtering out parameter %s", key2.c_str());
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002533 break;
2534 }
2535 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002536 }
2537 // if all keys have been filtered out, remove the command.
2538 // otherwise, update the key value pairs
2539 if (param2.size() == 0) {
2540 removedCommands.add(command2);
2541 } else {
2542 data2->mKeyValuePairs = param2.toString();
2543 }
Eric Laurent21e54562013-09-23 12:08:05 -07002544 command->mTime = command2->mTime;
2545 // force delayMs to non 0 so that code below does not request to wait for
2546 // command status as the command is now delayed
2547 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002548 } break;
2549
2550 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002551 VolumeData *data = (VolumeData *)command->mParam.get();
2552 VolumeData *data2 = (VolumeData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002553 if (data->mIO != data2->mIO) break;
2554 if (data->mStream != data2->mStream) break;
Steve Block3856b092011-10-20 11:56:00 +01002555 ALOGV("Filtering out volume command on output %d for stream %d",
Eric Laurentde070132010-07-13 04:45:46 -07002556 data->mIO, data->mStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002557 removedCommands.add(command2);
Eric Laurent21e54562013-09-23 12:08:05 -07002558 command->mTime = command2->mTime;
2559 // force delayMs to non 0 so that code below does not request to wait for
2560 // command status as the command is now delayed
2561 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002562 } break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002563
Eric Laurentbaf35fe2016-07-27 15:36:53 -07002564 case SET_VOICE_VOLUME: {
2565 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
2566 VoiceVolumeData *data2 = (VoiceVolumeData *)command2->mParam.get();
2567 ALOGV("Filtering out voice volume command value %f replaced by %f",
2568 data2->mVolume, data->mVolume);
2569 removedCommands.add(command2);
2570 command->mTime = command2->mTime;
2571 // force delayMs to non 0 so that code below does not request to wait for
2572 // command status as the command is now delayed
2573 delayMs = 1;
2574 } break;
2575
Eric Laurente45b48a2014-09-04 16:40:57 -07002576 case CREATE_AUDIO_PATCH:
2577 case RELEASE_AUDIO_PATCH: {
2578 audio_patch_handle_t handle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002579 struct audio_patch patch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002580 if (command->mCommand == CREATE_AUDIO_PATCH) {
2581 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002582 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002583 } else {
2584 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
Mikhail Naganov7be71d22018-05-23 16:51:46 -07002585 memset(&patch, 0, sizeof(patch));
Eric Laurente45b48a2014-09-04 16:40:57 -07002586 }
2587 audio_patch_handle_t handle2;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002588 struct audio_patch patch2;
Eric Laurente45b48a2014-09-04 16:40:57 -07002589 if (command2->mCommand == CREATE_AUDIO_PATCH) {
2590 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002591 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002592 } else {
2593 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
Glenn Kastenf60b6b62015-07-06 10:53:26 -07002594 memset(&patch2, 0, sizeof(patch2));
Eric Laurente45b48a2014-09-04 16:40:57 -07002595 }
2596 if (handle != handle2) break;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002597 /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
2598 same output. */
2599 if( (command->mCommand == CREATE_AUDIO_PATCH) &&
2600 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
2601 bool isOutputDiff = false;
2602 if (patch.num_sources == patch2.num_sources) {
2603 for (unsigned count = 0; count < patch.num_sources; count++) {
2604 if (patch.sources[count].id != patch2.sources[count].id) {
2605 isOutputDiff = true;
2606 break;
2607 }
2608 }
2609 if (isOutputDiff)
2610 break;
2611 }
2612 }
Eric Laurente45b48a2014-09-04 16:40:57 -07002613 ALOGV("Filtering out %s audio patch command for handle %d",
2614 (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
2615 removedCommands.add(command2);
2616 command->mTime = command2->mTime;
2617 // force delayMs to non 0 so that code below does not request to wait for
2618 // command status as the command is now delayed
2619 delayMs = 1;
2620 } break;
2621
Jean-Michel Trivide801052015-04-14 19:10:14 -07002622 case DYN_POLICY_MIX_STATE_UPDATE: {
2623
2624 } break;
2625
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002626 case RECORDING_CONFIGURATION_UPDATE: {
2627
2628 } break;
2629
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002630 case ROUTING_UPDATED: {
2631
2632 } break;
2633
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002634 case VOL_RANGE_INIT_REQUEST: {
2635 // command may come from different requests, do not filter
2636 } break;
2637
Mathias Agopian65ab4712010-07-14 17:59:35 -07002638 default:
2639 break;
2640 }
2641 }
2642
2643 // remove filtered commands
2644 for (size_t j = 0; j < removedCommands.size(); j++) {
2645 // removed commands always have time stamps greater than current command
2646 for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002647 if (mAudioCommands[k].get() == removedCommands[j].get()) {
Steve Block3856b092011-10-20 11:56:00 +01002648 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002649 mAudioCommands.removeAt(k);
2650 break;
2651 }
2652 }
2653 }
2654 removedCommands.clear();
2655
Eric Laurentaa79bef2015-01-15 14:33:51 -08002656 // Disable wait for status if delay is not 0.
2657 // Except for create audio patch command because the returned patch handle
2658 // is needed by audio policy manager
2659 if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
Eric Laurentcec4abb2012-07-03 12:23:02 -07002660 command->mWaitStatus = false;
2661 }
Eric Laurentcec4abb2012-07-03 12:23:02 -07002662
Mathias Agopian65ab4712010-07-14 17:59:35 -07002663 // insert command at the right place according to its time stamp
Eric Laurent1e693b52014-07-09 15:03:28 -07002664 ALOGV("inserting command: %d at index %zd, num commands %zu",
2665 command->mCommand, i+1, mAudioCommands.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002666 mAudioCommands.insertAt(command, i + 1);
2667}
2668
2669void AudioPolicyService::AudioCommandThread::exit()
2670{
Steve Block3856b092011-10-20 11:56:00 +01002671 ALOGV("AudioCommandThread::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002672 {
2673 AutoMutex _l(mLock);
2674 requestExit();
2675 mWaitWorkCV.signal();
2676 }
Zach Janga754b4f2015-10-27 01:29:34 +00002677 // Note that we can call it from the thread loop if all other references have been released
2678 // but it will safely return WOULD_BLOCK in this case
Mathias Agopian65ab4712010-07-14 17:59:35 -07002679 requestExitAndWait();
2680}
2681
2682void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
2683{
2684 snprintf(buffer, size, " %02d %06d.%03d %01u %p\n",
2685 mCommand,
2686 (int)ns2s(mTime),
2687 (int)ns2ms(mTime)%1000,
2688 mWaitStatus,
Eric Laurent0ede8922014-05-09 18:04:42 -07002689 mParam.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002690}
2691
Dima Zavinfce7a472011-04-19 22:30:36 -07002692/******* helpers for the service_ops callbacks defined below *********/
2693void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
2694 const char *keyValuePairs,
2695 int delayMs)
2696{
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002697 mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
Dima Zavinfce7a472011-04-19 22:30:36 -07002698 delayMs);
2699}
2700
2701int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
2702 float volume,
2703 audio_io_handle_t output,
2704 int delayMs)
2705{
Glenn Kastenfff6d712012-01-12 16:38:12 -08002706 return (int)mAudioCommandThread->volumeCommand(stream, volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002707 output, delayMs);
Dima Zavinfce7a472011-04-19 22:30:36 -07002708}
2709
Dima Zavinfce7a472011-04-19 22:30:36 -07002710int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
2711{
2712 return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
2713}
2714
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002715void AudioPolicyService::setEffectSuspended(int effectId,
2716 audio_session_t sessionId,
2717 bool suspended)
2718{
2719 mAudioCommandThread->setEffectSuspendedCommand(effectId, sessionId, suspended);
2720}
2721
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002722Status AudioPolicyService::onNewAudioModulesAvailable()
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002723{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07002724 mOutputCommandThread->audioModulesUpdateCommand();
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002725 return Status::ok();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002726}
2727
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002728
Dima Zavinfce7a472011-04-19 22:30:36 -07002729extern "C" {
Eric Laurent2d388ec2014-03-07 13:25:54 -08002730audio_module_handle_t aps_load_hw_module(void *service __unused,
2731 const char *name);
2732audio_io_handle_t aps_open_output(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002733 audio_devices_t *pDevices,
2734 uint32_t *pSamplingRate,
2735 audio_format_t *pFormat,
2736 audio_channel_mask_t *pChannelMask,
2737 uint32_t *pLatencyMs,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002738 audio_output_flags_t flags);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002739
Eric Laurent2d388ec2014-03-07 13:25:54 -08002740audio_io_handle_t aps_open_output_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002741 audio_module_handle_t module,
2742 audio_devices_t *pDevices,
2743 uint32_t *pSamplingRate,
2744 audio_format_t *pFormat,
2745 audio_channel_mask_t *pChannelMask,
2746 uint32_t *pLatencyMs,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002747 audio_output_flags_t flags,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002748 const audio_offload_info_t *offloadInfo);
2749audio_io_handle_t aps_open_dup_output(void *service __unused,
Dima Zavinfce7a472011-04-19 22:30:36 -07002750 audio_io_handle_t output1,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002751 audio_io_handle_t output2);
2752int aps_close_output(void *service __unused, audio_io_handle_t output);
2753int aps_suspend_output(void *service __unused, audio_io_handle_t output);
2754int aps_restore_output(void *service __unused, audio_io_handle_t output);
2755audio_io_handle_t aps_open_input(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002756 audio_devices_t *pDevices,
2757 uint32_t *pSamplingRate,
2758 audio_format_t *pFormat,
2759 audio_channel_mask_t *pChannelMask,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002760 audio_in_acoustics_t acoustics __unused);
2761audio_io_handle_t aps_open_input_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002762 audio_module_handle_t module,
2763 audio_devices_t *pDevices,
2764 uint32_t *pSamplingRate,
2765 audio_format_t *pFormat,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002766 audio_channel_mask_t *pChannelMask);
2767int aps_close_input(void *service __unused, audio_io_handle_t input);
2768int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
Glenn Kastend848eb42016-03-08 13:42:11 -08002769int aps_move_effects(void *service __unused, audio_session_t session,
Dima Zavinfce7a472011-04-19 22:30:36 -07002770 audio_io_handle_t src_output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002771 audio_io_handle_t dst_output);
2772char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
2773 const char *keys);
2774void aps_set_parameters(void *service, audio_io_handle_t io_handle,
2775 const char *kv_pairs, int delay_ms);
2776int aps_set_stream_volume(void *service, audio_stream_type_t stream,
Dima Zavinfce7a472011-04-19 22:30:36 -07002777 float volume, audio_io_handle_t output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002778 int delay_ms);
Eric Laurent2d388ec2014-03-07 13:25:54 -08002779int aps_set_voice_volume(void *service, float volume, int delay_ms);
2780};
Dima Zavinfce7a472011-04-19 22:30:36 -07002781
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08002782} // namespace android