blob: 193e68a8251d3b931fe7536a1c8093bd904dccf2 [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>
37#include "AudioPolicyService.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070038#include <hardware_legacy/power.h>
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -080039#include <media/AidlConversion.h>
Eric Laurent7c7f10b2011-06-17 21:29:58 -070040#include <media/AudioEffect.h>
Chih-Hung Hsiehc84d9d22014-11-14 13:33:34 -080041#include <media/AudioParameter.h>
Andy Hungc747c532022-03-07 21:41:14 -080042#include <mediautils/MethodStatistics.h>
Andy Hungab7ef302018-05-15 19:35:29 -070043#include <mediautils/ServiceUtilities.h>
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -080044#include <mediautils/TimeCheck.h>
Michael Groovercfd28302018-12-11 19:16:46 -080045#include <sensorprivacy/SensorPrivacyManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070046
Dima Zavin64760242011-05-11 14:15:23 -070047#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070048#include <system/audio_policy.h>
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053049#include <AudioPolicyManager.h>
Mikhail Naganov61a4fac2016-10-13 14:44:18 -070050
Mathias Agopian65ab4712010-07-14 17:59:35 -070051namespace android {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -080052using binder::Status;
Mathias Agopian65ab4712010-07-14 17:59:35 -070053
Glenn Kasten8dad0e32012-01-09 08:41:22 -080054static const char kDeadlockedString[] = "AudioPolicyService may be deadlocked\n";
55static const char kCmdDeadlockedString[] = "AudioPolicyService command thread may be deadlocked\n";
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053056static const char kAudioPolicyManagerCustomPath[] = "libaudiopolicymanagercustom.so";
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Mikhail Naganov959e2d02019-03-28 11:08:19 -070058static const int kDumpLockTimeoutNs = 1 * NANOS_PER_SECOND;
Mathias Agopian65ab4712010-07-14 17:59:35 -070059
Eric Laurent0ede8922014-05-09 18:04:42 -070060static const nsecs_t kAudioCommandTimeoutNs = seconds(3); // 3 seconds
Christer Fletcher5fa8c4b2013-01-18 15:27:03 +010061
Svet Ganovf4ddfef2018-01-16 07:37:58 -080062static const String16 sManageAudioPolicyPermission("android.permission.MANAGE_AUDIO_POLICY");
Dima Zavinfce7a472011-04-19 22:30:36 -070063
Andy Hungc747c532022-03-07 21:41:14 -080064// Creates an association between Binder code to name for IAudioPolicyService.
65#define IAUDIOPOLICYSERVICE_BINDER_METHOD_MACRO_LIST \
66BINDER_METHOD_ENTRY(onNewAudioModulesAvailable) \
67BINDER_METHOD_ENTRY(setDeviceConnectionState) \
68BINDER_METHOD_ENTRY(getDeviceConnectionState) \
69BINDER_METHOD_ENTRY(handleDeviceConfigChange) \
70BINDER_METHOD_ENTRY(setPhoneState) \
71BINDER_METHOD_ENTRY(setForceUse) \
72BINDER_METHOD_ENTRY(getForceUse) \
73BINDER_METHOD_ENTRY(getOutput) \
74BINDER_METHOD_ENTRY(getOutputForAttr) \
75BINDER_METHOD_ENTRY(startOutput) \
76BINDER_METHOD_ENTRY(stopOutput) \
77BINDER_METHOD_ENTRY(releaseOutput) \
78BINDER_METHOD_ENTRY(getInputForAttr) \
79BINDER_METHOD_ENTRY(startInput) \
80BINDER_METHOD_ENTRY(stopInput) \
81BINDER_METHOD_ENTRY(releaseInput) \
82BINDER_METHOD_ENTRY(initStreamVolume) \
83BINDER_METHOD_ENTRY(setStreamVolumeIndex) \
84BINDER_METHOD_ENTRY(getStreamVolumeIndex) \
85BINDER_METHOD_ENTRY(setVolumeIndexForAttributes) \
86BINDER_METHOD_ENTRY(getVolumeIndexForAttributes) \
87BINDER_METHOD_ENTRY(getMaxVolumeIndexForAttributes) \
88BINDER_METHOD_ENTRY(getMinVolumeIndexForAttributes) \
89BINDER_METHOD_ENTRY(getStrategyForStream) \
90BINDER_METHOD_ENTRY(getDevicesForAttributes) \
91BINDER_METHOD_ENTRY(getOutputForEffect) \
92BINDER_METHOD_ENTRY(registerEffect) \
93BINDER_METHOD_ENTRY(unregisterEffect) \
94BINDER_METHOD_ENTRY(setEffectEnabled) \
95BINDER_METHOD_ENTRY(moveEffectsToIo) \
96BINDER_METHOD_ENTRY(isStreamActive) \
97BINDER_METHOD_ENTRY(isStreamActiveRemotely) \
98BINDER_METHOD_ENTRY(isSourceActive) \
99BINDER_METHOD_ENTRY(queryDefaultPreProcessing) \
100BINDER_METHOD_ENTRY(addSourceDefaultEffect) \
101BINDER_METHOD_ENTRY(addStreamDefaultEffect) \
102BINDER_METHOD_ENTRY(removeSourceDefaultEffect) \
103BINDER_METHOD_ENTRY(removeStreamDefaultEffect) \
104BINDER_METHOD_ENTRY(setSupportedSystemUsages) \
105BINDER_METHOD_ENTRY(setAllowedCapturePolicy) \
106BINDER_METHOD_ENTRY(getOffloadSupport) \
107BINDER_METHOD_ENTRY(isDirectOutputSupported) \
108BINDER_METHOD_ENTRY(listAudioPorts) \
109BINDER_METHOD_ENTRY(getAudioPort) \
110BINDER_METHOD_ENTRY(createAudioPatch) \
111BINDER_METHOD_ENTRY(releaseAudioPatch) \
112BINDER_METHOD_ENTRY(listAudioPatches) \
113BINDER_METHOD_ENTRY(setAudioPortConfig) \
114BINDER_METHOD_ENTRY(registerClient) \
115BINDER_METHOD_ENTRY(setAudioPortCallbacksEnabled) \
116BINDER_METHOD_ENTRY(setAudioVolumeGroupCallbacksEnabled) \
117BINDER_METHOD_ENTRY(acquireSoundTriggerSession) \
118BINDER_METHOD_ENTRY(releaseSoundTriggerSession) \
119BINDER_METHOD_ENTRY(getPhoneState) \
120BINDER_METHOD_ENTRY(registerPolicyMixes) \
121BINDER_METHOD_ENTRY(setUidDeviceAffinities) \
122BINDER_METHOD_ENTRY(removeUidDeviceAffinities) \
123BINDER_METHOD_ENTRY(setUserIdDeviceAffinities) \
124BINDER_METHOD_ENTRY(removeUserIdDeviceAffinities) \
125BINDER_METHOD_ENTRY(startAudioSource) \
126BINDER_METHOD_ENTRY(stopAudioSource) \
127BINDER_METHOD_ENTRY(setMasterMono) \
128BINDER_METHOD_ENTRY(getMasterMono) \
129BINDER_METHOD_ENTRY(getStreamVolumeDB) \
130BINDER_METHOD_ENTRY(getSurroundFormats) \
131BINDER_METHOD_ENTRY(getReportedSurroundFormats) \
132BINDER_METHOD_ENTRY(getHwOffloadFormatsSupportedForBluetoothMedia) \
133BINDER_METHOD_ENTRY(setSurroundFormatEnabled) \
134BINDER_METHOD_ENTRY(setAssistantServicesUids) \
135BINDER_METHOD_ENTRY(setActiveAssistantServicesUids) \
136BINDER_METHOD_ENTRY(setA11yServicesUids) \
137BINDER_METHOD_ENTRY(setCurrentImeUid) \
138BINDER_METHOD_ENTRY(isHapticPlaybackSupported) \
139BINDER_METHOD_ENTRY(isUltrasoundSupported) \
Atneya Nair698f5ef2022-12-15 16:15:09 -0800140BINDER_METHOD_ENTRY(isHotwordStreamSupported) \
Andy Hungc747c532022-03-07 21:41:14 -0800141BINDER_METHOD_ENTRY(listAudioProductStrategies) \
142BINDER_METHOD_ENTRY(getProductStrategyFromAudioAttributes) \
143BINDER_METHOD_ENTRY(listAudioVolumeGroups) \
144BINDER_METHOD_ENTRY(getVolumeGroupFromAudioAttributes) \
145BINDER_METHOD_ENTRY(setRttEnabled) \
146BINDER_METHOD_ENTRY(isCallScreenModeSupported) \
147BINDER_METHOD_ENTRY(setDevicesRoleForStrategy) \
148BINDER_METHOD_ENTRY(removeDevicesRoleForStrategy) \
Paul Wang5d7cdb52022-11-22 09:45:06 +0000149BINDER_METHOD_ENTRY(clearDevicesRoleForStrategy) \
Andy Hungc747c532022-03-07 21:41:14 -0800150BINDER_METHOD_ENTRY(getDevicesForRoleAndStrategy) \
151BINDER_METHOD_ENTRY(setDevicesRoleForCapturePreset) \
152BINDER_METHOD_ENTRY(addDevicesRoleForCapturePreset) \
153BINDER_METHOD_ENTRY(removeDevicesRoleForCapturePreset) \
154BINDER_METHOD_ENTRY(clearDevicesRoleForCapturePreset) \
155BINDER_METHOD_ENTRY(getDevicesForRoleAndCapturePreset) \
156BINDER_METHOD_ENTRY(registerSoundTriggerCaptureStateListener) \
157BINDER_METHOD_ENTRY(getSpatializer) \
158BINDER_METHOD_ENTRY(canBeSpatialized) \
159BINDER_METHOD_ENTRY(getDirectPlaybackSupport) \
jiabina84c3d32022-12-02 18:59:55 +0000160BINDER_METHOD_ENTRY(getDirectProfilesForAttributes) \
161BINDER_METHOD_ENTRY(getSupportedMixerAttributes) \
162BINDER_METHOD_ENTRY(setPreferredMixerAttributes) \
163BINDER_METHOD_ENTRY(getPreferredMixerAttributes) \
164BINDER_METHOD_ENTRY(clearPreferredMixerAttributes) \
Andy Hungc747c532022-03-07 21:41:14 -0800165
166// singleton for Binder Method Statistics for IAudioPolicyService
167static auto& getIAudioPolicyServiceStatistics() {
168 using Code = int;
169
170#pragma push_macro("BINDER_METHOD_ENTRY")
171#undef BINDER_METHOD_ENTRY
172#define BINDER_METHOD_ENTRY(ENTRY) \
173 {(Code)media::BnAudioPolicyService::TRANSACTION_##ENTRY, #ENTRY},
174
175 static mediautils::MethodStatistics<Code> methodStatistics{
176 IAUDIOPOLICYSERVICE_BINDER_METHOD_MACRO_LIST
177 METHOD_STATISTICS_BINDER_CODE_NAMES(Code)
178 };
179#pragma pop_macro("BINDER_METHOD_ENTRY")
180
181 return methodStatistics;
182}
183
Mathias Agopian65ab4712010-07-14 17:59:35 -0700184// ----------------------------------------------------------------------------
185
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530186static AudioPolicyInterface* createAudioPolicyManager(AudioPolicyClientInterface *clientInterface)
187{
188 AudioPolicyManager *apm = new AudioPolicyManager(clientInterface);
189 status_t status = apm->initialize();
190 if (status != NO_ERROR) {
191 delete apm;
192 apm = nullptr;
193 }
194 return apm;
195}
196
197static void destroyAudioPolicyManager(AudioPolicyInterface *interface)
198{
199 delete interface;
200}
201// ----------------------------------------------------------------------------
202
Mathias Agopian65ab4712010-07-14 17:59:35 -0700203AudioPolicyService::AudioPolicyService()
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -0700204 : BnAudioPolicyService(),
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -0700205 mAudioPolicyManager(NULL),
206 mAudioPolicyClient(NULL),
207 mPhoneState(AUDIO_MODE_INVALID),
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530208 mCaptureStateNotifier(false),
209 mCreateAudioPolicyManager(createAudioPolicyManager),
Eric Laurent0d13fea2022-11-04 17:12:08 +0100210 mDestroyAudioPolicyManager(destroyAudioPolicyManager),
211 mUsecaseValidator(media::createUsecaseValidator()) {
Andy Hung225aef62022-12-06 16:33:20 -0800212 setMinSchedulerPolicy(SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530213}
214
215void AudioPolicyService::loadAudioPolicyManager()
216{
217 mLibraryHandle = dlopen(kAudioPolicyManagerCustomPath, RTLD_NOW);
218 if (mLibraryHandle != nullptr) {
219 ALOGI("%s loading %s", __func__, kAudioPolicyManagerCustomPath);
220 mCreateAudioPolicyManager = reinterpret_cast<CreateAudioPolicyManagerInstance>
221 (dlsym(mLibraryHandle, "createAudioPolicyManager"));
222 const char *lastError = dlerror();
223 ALOGW_IF(mCreateAudioPolicyManager == nullptr, "%s createAudioPolicyManager is null %s",
224 __func__, lastError != nullptr ? lastError : "no error");
225
226 mDestroyAudioPolicyManager = reinterpret_cast<DestroyAudioPolicyManagerInstance>(
227 dlsym(mLibraryHandle, "destroyAudioPolicyManager"));
228 lastError = dlerror();
229 ALOGW_IF(mDestroyAudioPolicyManager == nullptr, "%s destroyAudioPolicyManager is null %s",
230 __func__, lastError != nullptr ? lastError : "no error");
231 if (mCreateAudioPolicyManager == nullptr || mDestroyAudioPolicyManager == nullptr){
232 unloadAudioPolicyManager();
233 LOG_ALWAYS_FATAL("could not find audiopolicymanager interface methods");
234 }
235 }
Eric Laurentf5ada6e2014-10-09 17:49:00 -0700236}
237
238void AudioPolicyService::onFirstRef()
239{
Andy Hungd47aca22022-03-15 11:50:51 -0700240 // Log an AudioPolicy "constructor" mediametrics event on first ref.
241 // This records the time it takes to load the audio modules and devices.
242 mediametrics::Defer defer([beginNs = systemTime()] {
243 mediametrics::LogItem(AMEDIAMETRICS_KEY_AUDIO_POLICY)
244 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CTOR)
245 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
246 .record(); });
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700247 {
248 Mutex::Autolock _l(mLock);
Eric Laurent93575202011-01-18 18:39:02 -0800249
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700250 // start audio commands thread
251 mAudioCommandThread = new AudioCommandThread(String8("ApmAudio"), this);
252 // start output activity command thread
253 mOutputCommandThread = new AudioCommandThread(String8("ApmOutput"), this);
Eric Laurentdce54a12014-03-10 12:19:46 -0700254
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700255 mAudioPolicyClient = new AudioPolicyClient(this);
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530256
257 loadAudioPolicyManager();
258 mAudioPolicyManager = mCreateAudioPolicyManager(mAudioPolicyClient);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700259 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200260
bryant_liuba2b4392014-06-11 16:49:30 +0800261 // load audio processing modules
Shunkai Yao8d6489a2023-04-18 23:14:25 +0000262 const sp<EffectsFactoryHalInterface> effectsFactoryHal = EffectsFactoryHalInterface::create();
263 sp<AudioPolicyEffects> audioPolicyEffects = new AudioPolicyEffects(effectsFactoryHal);
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000264 sp<UidPolicy> uidPolicy = new UidPolicy(this);
265 sp<SensorPrivacyPolicy> sensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700266 {
267 Mutex::Autolock _l(mLock);
268 mAudioPolicyEffects = audioPolicyEffects;
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000269 mUidPolicy = uidPolicy;
270 mSensorPrivacyPolicy = sensorPrivacyPolicy;
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700271 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000272 uidPolicy->registerSelf();
273 sensorPrivacyPolicy->registerSelf();
Eric Laurentd66d7a12021-07-13 13:35:32 +0200274
Eric Laurent81dd0f52021-07-05 11:54:40 +0200275 // Create spatializer if supported
Eric Laurent52b0bd52021-09-27 15:25:40 +0200276 if (mAudioPolicyManager != nullptr) {
277 Mutex::Autolock _l(mLock);
278 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
279 AudioDeviceTypeAddrVector devices;
280 bool hasSpatializer = mAudioPolicyManager->canBeSpatialized(&attr, nullptr, devices);
281 if (hasSpatializer) {
Shunkai Yao8d6489a2023-04-18 23:14:25 +0000282 mSpatializer = Spatializer::create(this, effectsFactoryHal);
Eric Laurent52b0bd52021-09-27 15:25:40 +0200283 }
Andy Hung8aa43c02022-09-13 18:53:06 -0700284 if (mSpatializer == nullptr) {
285 // No spatializer created, signal the reason: NO_INIT a failure, OK means intended.
286 const status_t createStatus = hasSpatializer ? NO_INIT : OK;
287 Spatializer::sendEmptyCreateSpatializerMetricWithStatus(createStatus);
288 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200289 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200290 AudioSystem::audioPolicyReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700291}
292
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530293void AudioPolicyService::unloadAudioPolicyManager()
294{
295 ALOGV("%s ", __func__);
296 if (mLibraryHandle != nullptr) {
297 dlclose(mLibraryHandle);
298 }
299 mLibraryHandle = nullptr;
300 mCreateAudioPolicyManager = nullptr;
301 mDestroyAudioPolicyManager = nullptr;
302}
303
Mathias Agopian65ab4712010-07-14 17:59:35 -0700304AudioPolicyService::~AudioPolicyService()
305{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700306 mAudioCommandThread->exit();
Eric Laurent657ff612014-05-07 11:58:24 -0700307 mOutputCommandThread->exit();
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700308
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530309 mDestroyAudioPolicyManager(mAudioPolicyManager);
310 unloadAudioPolicyManager();
311
Eric Laurentdce54a12014-03-10 12:19:46 -0700312 delete mAudioPolicyClient;
Eric Laurentb52c1522014-05-20 11:27:36 -0700313
314 mNotificationClients.clear();
bryant_liuba2b4392014-06-11 16:49:30 +0800315 mAudioPolicyEffects.clear();
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800316
317 mUidPolicy->unregisterSelf();
Michael Groovercfd28302018-12-11 19:16:46 -0800318 mSensorPrivacyPolicy->unregisterSelf();
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000319
320 mUidPolicy.clear();
Michael Groovercfd28302018-12-11 19:16:46 -0800321 mSensorPrivacyPolicy.clear();
Eric Laurentb52c1522014-05-20 11:27:36 -0700322}
323
324// A notification client is always registered by AudioSystem when the client process
325// connects to AudioPolicyService.
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800326Status AudioPolicyService::registerClient(const sp<media::IAudioPolicyServiceClient>& client)
Eric Laurentb52c1522014-05-20 11:27:36 -0700327{
Eric Laurent12590252015-08-21 18:40:20 -0700328 if (client == 0) {
329 ALOGW("%s got NULL client", __FUNCTION__);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800330 return Status::ok();
Eric Laurent12590252015-08-21 18:40:20 -0700331 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800332 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700333
334 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800335 pid_t pid = IPCThreadState::self()->getCallingPid();
336 int64_t token = ((int64_t)uid<<32) | pid;
337
338 if (mNotificationClients.indexOfKey(token) < 0) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700339 sp<NotificationClient> notificationClient = new NotificationClient(this,
340 client,
luochaojiang908c7d72018-06-21 14:58:04 +0800341 uid,
342 pid);
343 ALOGV("registerClient() client %p, uid %d pid %d", client.get(), uid, pid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700344
luochaojiang908c7d72018-06-21 14:58:04 +0800345 mNotificationClients.add(token, notificationClient);
Eric Laurentb52c1522014-05-20 11:27:36 -0700346
Marco Nelissenf8880202014-11-14 07:58:25 -0800347 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurentb52c1522014-05-20 11:27:36 -0700348 binder->linkToDeath(notificationClient);
349 }
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800350 return Status::ok();
Eric Laurentb52c1522014-05-20 11:27:36 -0700351}
352
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800353Status AudioPolicyService::setAudioPortCallbacksEnabled(bool enabled)
Eric Laurente8726fe2015-06-26 09:39:24 -0700354{
355 Mutex::Autolock _l(mNotificationClientsLock);
356
357 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800358 pid_t pid = IPCThreadState::self()->getCallingPid();
359 int64_t token = ((int64_t)uid<<32) | pid;
360
361 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800362 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700363 }
luochaojiang908c7d72018-06-21 14:58:04 +0800364 mNotificationClients.valueFor(token)->setAudioPortCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800365 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700366}
367
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800368Status AudioPolicyService::setAudioVolumeGroupCallbacksEnabled(bool enabled)
François Gaffiecfe17322018-11-07 13:41:29 +0100369{
370 Mutex::Autolock _l(mNotificationClientsLock);
371
372 uid_t uid = IPCThreadState::self()->getCallingUid();
373 pid_t pid = IPCThreadState::self()->getCallingPid();
374 int64_t token = ((int64_t)uid<<32) | pid;
375
376 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800377 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100378 }
379 mNotificationClients.valueFor(token)->setAudioVolumeGroupCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800380 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100381}
382
Eric Laurentb52c1522014-05-20 11:27:36 -0700383// removeNotificationClient() is called when the client process dies.
luochaojiang908c7d72018-06-21 14:58:04 +0800384void AudioPolicyService::removeNotificationClient(uid_t uid, pid_t pid)
Eric Laurentb52c1522014-05-20 11:27:36 -0700385{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000386 bool hasSameUid = false;
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800387 {
388 Mutex::Autolock _l(mNotificationClientsLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800389 int64_t token = ((int64_t)uid<<32) | pid;
390 mNotificationClients.removeItem(token);
luochaojiang908c7d72018-06-21 14:58:04 +0800391 for (size_t i = 0; i < mNotificationClients.size(); i++) {
392 if (mNotificationClients.valueAt(i)->uid() == uid) {
393 hasSameUid = true;
394 break;
395 }
396 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000397 }
398 {
399 Mutex::Autolock _l(mLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800400 if (mAudioPolicyManager && !hasSameUid) {
Eric Laurent10b71232018-04-13 18:14:44 -0700401 // called from binder death notification: no need to clear caller identity
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700402 mAudioPolicyManager->releaseResourcesForUid(uid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700403 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800404 }
Eric Laurentb52c1522014-05-20 11:27:36 -0700405}
406
407void AudioPolicyService::onAudioPortListUpdate()
408{
409 mOutputCommandThread->updateAudioPortListCommand();
410}
411
412void AudioPolicyService::doOnAudioPortListUpdate()
413{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800414 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700415 for (size_t i = 0; i < mNotificationClients.size(); i++) {
416 mNotificationClients.valueAt(i)->onAudioPortListUpdate();
417 }
418}
419
420void AudioPolicyService::onAudioPatchListUpdate()
421{
422 mOutputCommandThread->updateAudioPatchListCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700423}
424
Eric Laurentb52c1522014-05-20 11:27:36 -0700425void AudioPolicyService::doOnAudioPatchListUpdate()
426{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800427 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700428 for (size_t i = 0; i < mNotificationClients.size(); i++) {
429 mNotificationClients.valueAt(i)->onAudioPatchListUpdate();
430 }
431}
432
François Gaffiecfe17322018-11-07 13:41:29 +0100433void AudioPolicyService::onAudioVolumeGroupChanged(volume_group_t group, int flags)
434{
435 mOutputCommandThread->changeAudioVolumeGroupCommand(group, flags);
436}
437
438void AudioPolicyService::doOnAudioVolumeGroupChanged(volume_group_t group, int flags)
439{
440 Mutex::Autolock _l(mNotificationClientsLock);
441 for (size_t i = 0; i < mNotificationClients.size(); i++) {
442 mNotificationClients.valueAt(i)->onAudioVolumeGroupChanged(group, flags);
443 }
444}
445
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700446void AudioPolicyService::onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700447{
448 ALOGV("AudioPolicyService::onDynamicPolicyMixStateUpdate(%s, %d)",
449 regId.string(), state);
450 mOutputCommandThread->dynamicPolicyMixStateUpdateCommand(regId, state);
451}
452
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700453void AudioPolicyService::doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700454{
455 Mutex::Autolock _l(mNotificationClientsLock);
456 for (size_t i = 0; i < mNotificationClients.size(); i++) {
457 mNotificationClients.valueAt(i)->onDynamicPolicyMixStateUpdate(regId, state);
458 }
459}
460
Eric Laurenta9f86652018-11-28 17:23:11 -0800461void AudioPolicyService::onRecordingConfigurationUpdate(
462 int event,
463 const record_client_info_t *clientInfo,
464 const audio_config_base_t *clientConfig,
465 std::vector<effect_descriptor_t> clientEffects,
466 const audio_config_base_t *deviceConfig,
467 std::vector<effect_descriptor_t> effects,
468 audio_patch_handle_t patchHandle,
469 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800470{
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800471 mOutputCommandThread->recordingConfigurationUpdateCommand(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800472 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800473}
474
Eric Laurenta9f86652018-11-28 17:23:11 -0800475void AudioPolicyService::doOnRecordingConfigurationUpdate(
476 int event,
477 const record_client_info_t *clientInfo,
478 const audio_config_base_t *clientConfig,
479 std::vector<effect_descriptor_t> clientEffects,
480 const audio_config_base_t *deviceConfig,
481 std::vector<effect_descriptor_t> effects,
482 audio_patch_handle_t patchHandle,
483 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800484{
485 Mutex::Autolock _l(mNotificationClientsLock);
486 for (size_t i = 0; i < mNotificationClients.size(); i++) {
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800487 mNotificationClients.valueAt(i)->onRecordingConfigurationUpdate(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800488 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800489 }
490}
491
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700492void AudioPolicyService::onRoutingUpdated()
493{
494 mOutputCommandThread->routingChangedCommand();
495}
496
497void AudioPolicyService::doOnRoutingUpdated()
498{
499 Mutex::Autolock _l(mNotificationClientsLock);
500 for (size_t i = 0; i < mNotificationClients.size(); i++) {
501 mNotificationClients.valueAt(i)->onRoutingUpdated();
502 }
503}
504
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000505void AudioPolicyService::onVolumeRangeInitRequest()
506{
507 mOutputCommandThread->volRangeInitReqCommand();
508}
509
510void AudioPolicyService::doOnVolumeRangeInitRequest()
511{
512 Mutex::Autolock _l(mNotificationClientsLock);
513 for (size_t i = 0; i < mNotificationClients.size(); i++) {
514 mNotificationClients.valueAt(i)->onVolumeRangeInitRequest();
515 }
516}
517
Eric Laurent81dd0f52021-07-05 11:54:40 +0200518void AudioPolicyService::onCheckSpatializer()
519{
520 Mutex::Autolock _l(mLock);
Eric Laurent39095982021-08-24 18:29:27 +0200521 onCheckSpatializer_l();
522}
523
524void AudioPolicyService::onCheckSpatializer_l()
525{
526 if (mSpatializer != nullptr) {
527 mOutputCommandThread->checkSpatializerCommand();
528 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200529}
530
531void AudioPolicyService::doOnCheckSpatializer()
532{
Eric Laurentd6bee3a2022-08-31 16:07:50 +0200533 ALOGV("%s mSpatializer %p level %d",
534 __func__, mSpatializer.get(), (int)mSpatializer->getLevel());
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200535
Eric Laurent39095982021-08-24 18:29:27 +0200536 if (mSpatializer != nullptr) {
Eric Laurent52b0bd52021-09-27 15:25:40 +0200537 // Note: mSpatializer != nullptr => mAudioPolicyManager != nullptr
Eric Laurent39095982021-08-24 18:29:27 +0200538 if (mSpatializer->getLevel() != media::SpatializationLevel::NONE) {
539 audio_io_handle_t currentOutput = mSpatializer->getOutput();
540 audio_io_handle_t newOutput;
541 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
542 audio_config_base_t config = mSpatializer->getAudioInConfig();
Eric Laurent21270b62022-07-04 15:11:29 +0200543
544 Mutex::Autolock _l(mLock);
Eric Laurent39095982021-08-24 18:29:27 +0200545 status_t status =
546 mAudioPolicyManager->getSpatializerOutput(&config, &attr, &newOutput);
Eric Laurentb4f42a92022-01-17 17:37:31 +0100547 ALOGV("%s currentOutput %d newOutput %d channel_mask %#x",
548 __func__, currentOutput, newOutput, config.channel_mask);
Eric Laurent39095982021-08-24 18:29:27 +0200549 if (status == NO_ERROR && currentOutput == newOutput) {
550 return;
551 }
Eric Laurent15903592022-02-24 20:44:36 +0100552 size_t numActiveTracks = countActiveClientsOnOutput_l(newOutput);
Eric Laurent39095982021-08-24 18:29:27 +0200553 mLock.unlock();
554 // It is OK to call detachOutput() is none is already attached.
555 mSpatializer->detachOutput();
Eric Laurent21270b62022-07-04 15:11:29 +0200556 if (status == NO_ERROR && newOutput != AUDIO_IO_HANDLE_NONE) {
557 status = mSpatializer->attachOutput(newOutput, numActiveTracks);
Eric Laurent39095982021-08-24 18:29:27 +0200558 }
Eric Laurent39095982021-08-24 18:29:27 +0200559 mLock.lock();
560 if (status != NO_ERROR) {
561 mAudioPolicyManager->releaseSpatializerOutput(newOutput);
562 }
563 } else if (mSpatializer->getLevel() == media::SpatializationLevel::NONE
564 && mSpatializer->getOutput() != AUDIO_IO_HANDLE_NONE) {
Eric Laurent39095982021-08-24 18:29:27 +0200565 audio_io_handle_t output = mSpatializer->detachOutput();
Eric Laurent21270b62022-07-04 15:11:29 +0200566
Eric Laurent39095982021-08-24 18:29:27 +0200567 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurent21270b62022-07-04 15:11:29 +0200568 Mutex::Autolock _l(mLock);
Eric Laurent39095982021-08-24 18:29:27 +0200569 mAudioPolicyManager->releaseSpatializerOutput(output);
Eric Laurent81dd0f52021-07-05 11:54:40 +0200570 }
571 }
572 }
573}
574
Eric Laurent11094172022-04-05 18:27:42 +0200575size_t AudioPolicyService::countActiveClientsOnOutput_l(
576 audio_io_handle_t output, bool spatializedOnly) {
Eric Laurent15903592022-02-24 20:44:36 +0100577 size_t count = 0;
578 for (size_t i = 0; i < mAudioPlaybackClients.size(); i++) {
579 auto client = mAudioPlaybackClients.valueAt(i);
Eric Laurent11094172022-04-05 18:27:42 +0200580 if (client->io == output && client->active
581 && (!spatializedOnly || client->isSpatialized)) {
Eric Laurent15903592022-02-24 20:44:36 +0100582 count++;
583 }
584 }
585 return count;
586}
587
588void AudioPolicyService::onUpdateActiveSpatializerTracks_l() {
589 if (mSpatializer == nullptr) {
590 return;
591 }
592 mOutputCommandThread->updateActiveSpatializerTracksCommand();
593}
594
595void AudioPolicyService::doOnUpdateActiveSpatializerTracks()
596{
Eric Laurent21270b62022-07-04 15:11:29 +0200597 if (mSpatializer == nullptr) {
598 return;
599 }
600 audio_io_handle_t output = mSpatializer->getOutput();
Eric Laurent7ea0d1b2022-04-01 14:23:44 +0200601 size_t activeClients;
602 {
603 Mutex::Autolock _l(mLock);
Eric Laurent21270b62022-07-04 15:11:29 +0200604 activeClients = countActiveClientsOnOutput_l(output);
Eric Laurent15903592022-02-24 20:44:36 +0100605 }
Eric Laurent21270b62022-07-04 15:11:29 +0200606 mSpatializer->updateActiveTracks(activeClients);
Eric Laurent15903592022-02-24 20:44:36 +0100607}
608
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800609status_t AudioPolicyService::clientCreateAudioPatch(const struct audio_patch *patch,
610 audio_patch_handle_t *handle,
611 int delayMs)
612{
613 return mAudioCommandThread->createAudioPatchCommand(patch, handle, delayMs);
614}
615
616status_t AudioPolicyService::clientReleaseAudioPatch(audio_patch_handle_t handle,
617 int delayMs)
618{
619 return mAudioCommandThread->releaseAudioPatchCommand(handle, delayMs);
620}
621
Eric Laurente1715a42014-05-20 11:30:42 -0700622status_t AudioPolicyService::clientSetAudioPortConfig(const struct audio_port_config *config,
623 int delayMs)
624{
625 return mAudioCommandThread->setAudioPortConfigCommand(config, delayMs);
626}
627
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800628AudioPolicyService::NotificationClient::NotificationClient(
629 const sp<AudioPolicyService>& service,
630 const sp<media::IAudioPolicyServiceClient>& client,
631 uid_t uid,
632 pid_t pid)
luochaojiang908c7d72018-06-21 14:58:04 +0800633 : mService(service), mUid(uid), mPid(pid), mAudioPolicyServiceClient(client),
François Gaffiecfe17322018-11-07 13:41:29 +0100634 mAudioPortCallbacksEnabled(false), mAudioVolumeGroupCallbacksEnabled(false)
Eric Laurentb52c1522014-05-20 11:27:36 -0700635{
636}
637
638AudioPolicyService::NotificationClient::~NotificationClient()
639{
640}
641
642void AudioPolicyService::NotificationClient::binderDied(const wp<IBinder>& who __unused)
643{
644 sp<NotificationClient> keep(this);
645 sp<AudioPolicyService> service = mService.promote();
646 if (service != 0) {
luochaojiang908c7d72018-06-21 14:58:04 +0800647 service->removeNotificationClient(mUid, mPid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700648 }
649}
650
651void AudioPolicyService::NotificationClient::onAudioPortListUpdate()
652{
Eric Laurente8726fe2015-06-26 09:39:24 -0700653 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700654 mAudioPolicyServiceClient->onAudioPortListUpdate();
655 }
656}
657
658void AudioPolicyService::NotificationClient::onAudioPatchListUpdate()
659{
Eric Laurente8726fe2015-06-26 09:39:24 -0700660 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700661 mAudioPolicyServiceClient->onAudioPatchListUpdate();
662 }
663}
Eric Laurent57dae992011-07-24 13:36:09 -0700664
Pattydd807582021-11-04 21:01:03 +0800665void AudioPolicyService::NotificationClient::onAudioVolumeGroupChanged(volume_group_t group,
François Gaffiecfe17322018-11-07 13:41:29 +0100666 int flags)
667{
668 if (mAudioPolicyServiceClient != 0 && mAudioVolumeGroupCallbacksEnabled) {
669 mAudioPolicyServiceClient->onAudioVolumeGroupChanged(group, flags);
670 }
671}
672
673
Jean-Michel Trivide801052015-04-14 19:10:14 -0700674void AudioPolicyService::NotificationClient::onDynamicPolicyMixStateUpdate(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700675 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700676{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700677 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800678 mAudioPolicyServiceClient->onDynamicPolicyMixStateUpdate(
679 legacy2aidl_String8_string(regId).value(), state);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800680 }
681}
682
683void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate(
Eric Laurenta9f86652018-11-28 17:23:11 -0800684 int event,
685 const record_client_info_t *clientInfo,
686 const audio_config_base_t *clientConfig,
687 std::vector<effect_descriptor_t> clientEffects,
688 const audio_config_base_t *deviceConfig,
689 std::vector<effect_descriptor_t> effects,
690 audio_patch_handle_t patchHandle,
691 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800692{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700693 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800694 status_t status = [&]() -> status_t {
695 int32_t eventAidl = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(event));
696 media::RecordClientInfo clientInfoAidl = VALUE_OR_RETURN_STATUS(
697 legacy2aidl_record_client_info_t_RecordClientInfo(*clientInfo));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700698 AudioConfigBase clientConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700699 legacy2aidl_audio_config_base_t_AudioConfigBase(
700 *clientConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800701 std::vector<media::EffectDescriptor> clientEffectsAidl = VALUE_OR_RETURN_STATUS(
702 convertContainer<std::vector<media::EffectDescriptor>>(
703 clientEffects,
704 legacy2aidl_effect_descriptor_t_EffectDescriptor));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700705 AudioConfigBase deviceConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700706 legacy2aidl_audio_config_base_t_AudioConfigBase(
707 *deviceConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800708 std::vector<media::EffectDescriptor> effectsAidl = VALUE_OR_RETURN_STATUS(
709 convertContainer<std::vector<media::EffectDescriptor>>(
710 effects,
711 legacy2aidl_effect_descriptor_t_EffectDescriptor));
712 int32_t patchHandleAidl = VALUE_OR_RETURN_STATUS(
713 legacy2aidl_audio_patch_handle_t_int32_t(patchHandle));
Mikhail Naganovddceecc2021-09-03 13:58:56 -0700714 media::audio::common::AudioSource sourceAidl = VALUE_OR_RETURN_STATUS(
715 legacy2aidl_audio_source_t_AudioSource(source));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800716 return aidl_utils::statusTFromBinderStatus(
717 mAudioPolicyServiceClient->onRecordingConfigurationUpdate(eventAidl,
718 clientInfoAidl,
719 clientConfigAidl,
720 clientEffectsAidl,
721 deviceConfigAidl,
722 effectsAidl,
723 patchHandleAidl,
724 sourceAidl));
725 }();
726 ALOGW_IF(status != OK, "onRecordingConfigurationUpdate() failed: %d", status);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700727 }
728}
729
Eric Laurente8726fe2015-06-26 09:39:24 -0700730void AudioPolicyService::NotificationClient::setAudioPortCallbacksEnabled(bool enabled)
731{
732 mAudioPortCallbacksEnabled = enabled;
733}
734
François Gaffiecfe17322018-11-07 13:41:29 +0100735void AudioPolicyService::NotificationClient::setAudioVolumeGroupCallbacksEnabled(bool enabled)
736{
737 mAudioVolumeGroupCallbacksEnabled = enabled;
738}
Eric Laurente8726fe2015-06-26 09:39:24 -0700739
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700740void AudioPolicyService::NotificationClient::onRoutingUpdated()
741{
742 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
743 mAudioPolicyServiceClient->onRoutingUpdated();
744 }
745}
746
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000747void AudioPolicyService::NotificationClient::onVolumeRangeInitRequest()
748{
749 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
750 mAudioPolicyServiceClient->onVolumeRangeInitRequest();
751 }
752}
753
Mathias Agopian65ab4712010-07-14 17:59:35 -0700754void AudioPolicyService::binderDied(const wp<IBinder>& who) {
Glenn Kasten411e4472012-11-02 10:00:06 -0700755 ALOGW("binderDied() %p, calling pid %d", who.unsafe_get(),
Eric Laurentde070132010-07-13 04:45:46 -0700756 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700757}
758
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000759static bool dumpTryLock(Mutex& mutex) ACQUIRE(mutex) NO_THREAD_SAFETY_ANALYSIS
Mathias Agopian65ab4712010-07-14 17:59:35 -0700760{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000761 return mutex.timedLock(kDumpLockTimeoutNs) == NO_ERROR;
762}
763
764static void dumpReleaseLock(Mutex& mutex, bool locked) RELEASE(mutex) NO_THREAD_SAFETY_ANALYSIS
765{
766 if (locked) mutex.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700767}
768
769status_t AudioPolicyService::dumpInternals(int fd)
770{
771 const size_t SIZE = 256;
772 char buffer[SIZE];
773 String8 result;
774
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000775 snprintf(buffer, SIZE, "Supported System Usages:\n ");
Hayden Gomes524159d2019-12-23 14:41:47 -0800776 result.append(buffer);
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000777 std::stringstream msg;
778 size_t i = 0;
779 for (auto usage : mSupportedSystemUsages) {
780 if (i++ != 0) msg << ", ";
781 if (const char* strUsage = audio_usage_to_string(usage); strUsage) {
782 msg << strUsage;
783 } else {
784 msg << usage << " (unknown)";
785 }
Hayden Gomes524159d2019-12-23 14:41:47 -0800786 }
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000787 if (i == 0) {
788 msg << "None";
789 }
790 msg << std::endl;
791 result.append(msg.str().c_str());
Hayden Gomes524159d2019-12-23 14:41:47 -0800792
Mathias Agopian65ab4712010-07-14 17:59:35 -0700793 write(fd, result.string(), result.size());
Oscar Azucena829d90d2022-01-28 17:17:56 -0800794
795 mUidPolicy->dumpInternals(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700796 return NO_ERROR;
797}
798
Eric Laurente8c8b432018-10-17 10:08:02 -0700799void AudioPolicyService::updateUidStates()
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800800{
Eric Laurente8c8b432018-10-17 10:08:02 -0700801 Mutex::Autolock _l(mLock);
802 updateUidStates_l();
803}
804
805void AudioPolicyService::updateUidStates_l()
806{
Eric Laurent4eb58f12018-12-07 16:41:02 -0800807// Go over all active clients and allow capture (does not force silence) in the
808// following cases:
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800809// The client is in the active assistant list
810// AND is TOP
811// AND an accessibility service is TOP
812// AND source is either VOICE_RECOGNITION OR HOTWORD
813// OR there is no active privacy sensitive capture or call
814// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
815// AND source is VOICE_RECOGNITION OR HOTWORD
816// The client is an assistant AND active assistant is not being used
Evan Severson1f700cd2021-02-10 13:10:37 -0800817// AND an accessibility service is on TOP or a RTT call is active
Eric Laurent589171c2019-07-25 18:04:29 -0700818// AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800819// OR there is no active privacy sensitive capture or call
Evan Severson1f700cd2021-02-10 13:10:37 -0800820// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800821// AND is TOP most recent assistant and uses VOICE_RECOGNITION or HOTWORD
822// OR there is no top recent assistant and source is HOTWORD
Evan Severson1f700cd2021-02-10 13:10:37 -0800823// OR The client is an accessibility service
824// AND Is on TOP
825// AND the source is VOICE_RECOGNITION or HOTWORD
826// OR The assistant is not on TOP
Eric Laurent589171c2019-07-25 18:04:29 -0700827// AND there is no active privacy sensitive capture or call
828// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Evan Severson1f700cd2021-02-10 13:10:37 -0800829// AND is on TOP
830// AND the source is VOICE_RECOGNITION or HOTWORD
831// OR the client source is virtual (remote submix, call audio TX or RX...)
832// OR the client source is HOTWORD
833// AND is on TOP
834// OR all active clients are using HOTWORD source
835// AND no call is active
836// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
837// OR the client is the current InputMethodService
838// AND a RTT call is active AND the source is VOICE_RECOGNITION
839// OR Any client
840// AND The assistant is not on TOP
841// AND is on TOP or latest started
842// AND there is no active privacy sensitive capture or call
843// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4eb58f12018-12-07 16:41:02 -0800844
Eric Laurent4e947da2019-10-17 15:24:06 -0700845
Eric Laurent4eb58f12018-12-07 16:41:02 -0800846 sp<AudioRecordClient> topActive;
847 sp<AudioRecordClient> latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800848 sp<AudioRecordClient> topSensitiveActive;
Eric Laurentb809a752020-06-29 09:53:13 -0700849 sp<AudioRecordClient> latestSensitiveActiveOrComm;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800850 sp<AudioRecordClient> latestActiveAssistant;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700851
Eric Laurenta46bedb2018-12-07 18:01:26 -0800852 nsecs_t topStartNs = 0;
853 nsecs_t latestStartNs = 0;
Eric Laurentc21d5692020-02-25 10:24:36 -0800854 nsecs_t topSensitiveStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800855 nsecs_t latestSensitiveStartNs = 0;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800856 nsecs_t latestAssistantStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800857 bool isA11yOnTop = mUidPolicy->isA11yOnTop();
858 bool isAssistantOnTop = false;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800859 bool useActiveAssistantList = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800860 bool isSensitiveActive = false;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700861 bool isInCall = mPhoneState == AUDIO_MODE_IN_CALL;
Eric Laurentc21d5692020-02-25 10:24:36 -0800862 bool isInCommunication = mPhoneState == AUDIO_MODE_IN_COMMUNICATION;
863 bool rttCallActive = (isInCall || isInCommunication)
Eric Laurent6ede98f2019-06-11 14:50:30 -0700864 && mUidPolicy->isRttEnabled();
Eric Laurent4e947da2019-10-17 15:24:06 -0700865 bool onlyHotwordActive = true;
Eric Laurentb809a752020-06-29 09:53:13 -0700866 bool isPhoneStateOwnerActive = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800867
Michael Groovercfd28302018-12-11 19:16:46 -0800868 // if Sensor Privacy is enabled then all recordings should be silenced.
869 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
870 silenceAllRecordings_l();
871 return;
872 }
873
Eric Laurente8c8b432018-10-17 10:08:02 -0700874 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
875 sp<AudioRecordClient> current = mAudioRecordClients[i];
Svet Ganov33761132021-05-13 22:51:08 +0000876 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
877 current->attributionSource.uid));
Evan Severson1f700cd2021-02-10 13:10:37 -0800878 if (!current->active) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700879 continue;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800880 }
Eric Laurent1ff16a72019-03-14 18:35:04 -0700881
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700882 app_state_t appState = apmStatFromAmState(mUidPolicy->getUidState(currentUid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700883 // clients which app is in IDLE state are not eligible for top active or
884 // latest active
885 if (appState == APP_STATE_IDLE) {
886 continue;
887 }
888
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700889 bool isAccessibility = mUidPolicy->isA11yUid(currentUid);
Eric Laurent14a88632020-07-16 12:28:30 -0700890 // Clients capturing for Accessibility services or virtual sources are not considered
Eric Laurentc21d5692020-02-25 10:24:36 -0800891 // for top or latest active to avoid masking regular clients started before
Eric Laurent14a88632020-07-16 12:28:30 -0700892 if (!isAccessibility && !isVirtualSource(current->attributes.source)) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700893 bool isAssistant = mUidPolicy->isAssistantUid(currentUid);
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800894 bool isActiveAssistant = mUidPolicy->isActiveAssistantUid(currentUid);
Eric Laurentc21d5692020-02-25 10:24:36 -0800895 bool isPrivacySensitive =
896 (current->attributes.flags & AUDIO_FLAG_CAPTURE_PRIVATE) != 0;
Eric Laurentb809a752020-06-29 09:53:13 -0700897
Eric Laurentc21d5692020-02-25 10:24:36 -0800898 if (appState == APP_STATE_TOP) {
899 if (isPrivacySensitive) {
900 if (current->startTimeNs > topSensitiveStartNs) {
901 topSensitiveActive = current;
902 topSensitiveStartNs = current->startTimeNs;
903 }
904 } else {
905 if (current->startTimeNs > topStartNs) {
906 topActive = current;
907 topStartNs = current->startTimeNs;
908 }
909 }
910 if (isAssistant) {
911 isAssistantOnTop = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800912 if (isActiveAssistant) {
913 useActiveAssistantList = true;
914 } else if (!useActiveAssistantList) {
915 if (current->startTimeNs > latestAssistantStartNs) {
916 latestActiveAssistant = current;
917 latestAssistantStartNs = current->startTimeNs;
918 }
919 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800920 }
Eric Laurenta46bedb2018-12-07 18:01:26 -0800921 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800922 // Clients capturing for HOTWORD are not considered
923 // for latest active to avoid masking regular clients started before
924 if (!(current->attributes.source == AUDIO_SOURCE_HOTWORD
925 || ((isA11yOnTop || rttCallActive) && isAssistant))) {
926 if (isPrivacySensitive) {
Eric Laurentb809a752020-06-29 09:53:13 -0700927 // if audio mode is IN_COMMUNICATION, make sure the audio mode owner
928 // is marked latest sensitive active even if another app qualifies.
929 if (current->startTimeNs > latestSensitiveStartNs
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700930 || (isInCommunication && currentUid == mPhoneStateOwnerUid)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700931 if (!isInCommunication || latestSensitiveActiveOrComm == nullptr
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700932 || VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000933 latestSensitiveActiveOrComm->attributionSource.uid))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700934 != mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700935 latestSensitiveActiveOrComm = current;
936 latestSensitiveStartNs = current->startTimeNs;
937 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800938 }
939 isSensitiveActive = true;
940 } else {
941 if (current->startTimeNs > latestStartNs) {
942 latestActive = current;
943 latestStartNs = current->startTimeNs;
944 }
945 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800946 }
947 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700948 if (current->attributes.source != AUDIO_SOURCE_HOTWORD) {
949 onlyHotwordActive = false;
950 }
Eric Laurentb0eff0f2021-11-09 16:05:49 +0100951 if (currentUid == mPhoneStateOwnerUid &&
952 !isVirtualSource(current->attributes.source)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700953 isPhoneStateOwnerActive = true;
954 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800955 }
956
Eric Laurent1ff16a72019-03-14 18:35:04 -0700957 // if no active client with UI on Top, consider latest active as top
958 if (topActive == nullptr) {
959 topActive = latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800960 topStartNs = latestStartNs;
961 }
962 if (topSensitiveActive == nullptr) {
Eric Laurentb809a752020-06-29 09:53:13 -0700963 topSensitiveActive = latestSensitiveActiveOrComm;
Eric Laurentc21d5692020-02-25 10:24:36 -0800964 topSensitiveStartNs = latestSensitiveStartNs;
Eric Laurentb809a752020-06-29 09:53:13 -0700965 } else if (latestSensitiveActiveOrComm != nullptr) {
966 // if audio mode is IN_COMMUNICATION, favor audio mode owner over an app with
967 // foreground UI in case both are capturing with privacy sensitive flag.
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700968 uid_t latestActiveUid = VALUE_OR_FATAL(
Svet Ganov33761132021-05-13 22:51:08 +0000969 aidl2legacy_int32_t_uid_t(latestSensitiveActiveOrComm->attributionSource.uid));
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700970 if (isInCommunication && latestActiveUid == mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700971 topSensitiveActive = latestSensitiveActiveOrComm;
972 topSensitiveStartNs = latestSensitiveStartNs;
973 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800974 }
975
976 // If both privacy sensitive and regular capture are active:
977 // if the regular capture is privileged
978 // allow concurrency
979 // else
980 // favor the privacy sensitive case
981 if (topActive != nullptr && topSensitiveActive != nullptr
Ricardo Correa57a37692020-03-23 17:27:25 -0700982 && !topActive->canCaptureOutput) {
Eric Laurentc21d5692020-02-25 10:24:36 -0800983 topActive = nullptr;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800984 }
985
986 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
987 sp<AudioRecordClient> current = mAudioRecordClients[i];
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700988 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000989 current->attributionSource.uid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700990 if (!current->active) {
991 continue;
992 }
993
Eric Laurent4eb58f12018-12-07 16:41:02 -0800994 audio_source_t source = current->attributes.source;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700995 bool isTopOrLatestActive = topActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +0000996 current->attributionSource.uid == topActive->attributionSource.uid;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700997 bool isTopOrLatestSensitive = topSensitiveActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +0000998 current->attributionSource.uid == topSensitiveActive->attributionSource.uid;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800999 bool isTopOrLatestAssistant = latestActiveAssistant == nullptr ? false :
1000 current->attributionSource.uid == latestActiveAssistant->attributionSource.uid;
Eric Laurentc21d5692020-02-25 10:24:36 -08001001
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001002 auto canCaptureIfInCallOrCommunication = [&](const auto &recordClient) REQUIRES(mLock) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001003 uid_t recordUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +00001004 recordClient->attributionSource.uid));
Ricardo Correa57a37692020-03-23 17:27:25 -07001005 bool canCaptureCall = recordClient->canCaptureOutput;
Eric Laurentb809a752020-06-29 09:53:13 -07001006 bool canCaptureCommunication = recordClient->canCaptureOutput
1007 || !isPhoneStateOwnerActive
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001008 || recordUid == mPhoneStateOwnerUid;
Eric Laurentb809a752020-06-29 09:53:13 -07001009 return !(isInCall && !canCaptureCall)
1010 && !(isInCommunication && !canCaptureCommunication);
Eric Laurentc21d5692020-02-25 10:24:36 -08001011 };
Eric Laurent1ff16a72019-03-14 18:35:04 -07001012
1013 // By default allow capture if:
1014 // The assistant is not on TOP
Eric Laurenta171e352019-05-07 13:04:45 -07001015 // AND is on TOP or latest started
Eric Laurent1ff16a72019-03-14 18:35:04 -07001016 // AND there is no active privacy sensitive capture or call
1017 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4ab18412022-11-07 16:25:32 +01001018 bool allowSensitiveCapture =
1019 !isSensitiveActive || isTopOrLatestSensitive || current->canCaptureOutput;
Eric Laurent1ff16a72019-03-14 18:35:04 -07001020 bool allowCapture = !isAssistantOnTop
Eric Laurentc21d5692020-02-25 10:24:36 -08001021 && (isTopOrLatestActive || isTopOrLatestSensitive)
Eric Laurent4ab18412022-11-07 16:25:32 +01001022 && allowSensitiveCapture
Eric Laurentc21d5692020-02-25 10:24:36 -08001023 && canCaptureIfInCallOrCommunication(current);
Eric Laurent2dc962b2019-03-01 08:25:25 -08001024
Eric Laurented726cc2021-07-01 14:26:41 +02001025 if (!current->hasOp()) {
1026 // Never allow capture if app op is denied
1027 allowCapture = false;
1028 } else if (isVirtualSource(source)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001029 // Allow capture for virtual (remote submix, call audio TX or RX...) sources
1030 allowCapture = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001031 } else if (!useActiveAssistantList && mUidPolicy->isAssistantUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001032 // For assistant allow capture if:
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001033 // Active assistant list is not being used
1034 // AND accessibility service is on TOP or a RTT call is active
Eric Laurent1ff16a72019-03-14 18:35:04 -07001035 // AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001036 // OR there is no active privacy sensitive capture or call
1037 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
1038 // AND is latest TOP assistant AND
1039 // uses VOICE_RECOGNITION OR uses HOTWORD
1040 // OR there is no TOP assistant and uses HOTWORD
Eric Laurent6ede98f2019-06-11 14:50:30 -07001041 if (isA11yOnTop || rttCallActive) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001042 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001043 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001044 }
Eric Laurent4ab18412022-11-07 16:25:32 +01001045 } else if (allowSensitiveCapture
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001046 && canCaptureIfInCallOrCommunication(current)) {
1047 if (isTopOrLatestAssistant
1048 && (source == AUDIO_SOURCE_VOICE_RECOGNITION
1049 || source == AUDIO_SOURCE_HOTWORD)) {
1050 allowCapture = true;
1051 } else if (!isAssistantOnTop && (source == AUDIO_SOURCE_HOTWORD)) {
1052 allowCapture = true;
1053 }
1054 }
1055 } else if (useActiveAssistantList && mUidPolicy->isActiveAssistantUid(currentUid)) {
1056 // For assistant on active list and on top allow capture if:
1057 // An accessibility service is on TOP
1058 // AND the source is VOICE_RECOGNITION or HOTWORD
1059 // OR there is no active privacy sensitive capture or call
1060 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
1061 // AND uses VOICE_RECOGNITION OR uses HOTWORD
1062 if (isA11yOnTop) {
1063 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
1064 allowCapture = true;
1065 }
Eric Laurent4ab18412022-11-07 16:25:32 +01001066 } else if (allowSensitiveCapture
Eric Laurentc21d5692020-02-25 10:24:36 -08001067 && canCaptureIfInCallOrCommunication(current)) {
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001068 if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) || (source == AUDIO_SOURCE_HOTWORD))
1069 {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001070 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001071 }
1072 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001073 } else if (mUidPolicy->isA11yUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001074 // For accessibility service allow capture if:
Eric Laurent47670c92019-08-28 16:59:05 -07001075 // The assistant is not on TOP
1076 // AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -07001077 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent47670c92019-08-28 16:59:05 -07001078 // OR
1079 // Is on TOP AND the source is VOICE_RECOGNITION or HOTWORD
1080 if (!isAssistantOnTop
Eric Laurent4ab18412022-11-07 16:25:32 +01001081 && allowSensitiveCapture
Eric Laurentc21d5692020-02-25 10:24:36 -08001082 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent47670c92019-08-28 16:59:05 -07001083 allowCapture = true;
1084 }
Eric Laurent589171c2019-07-25 18:04:29 -07001085 if (isA11yOnTop) {
1086 if (source == AUDIO_SOURCE_VOICE_RECOGNITION || source == AUDIO_SOURCE_HOTWORD) {
1087 allowCapture = true;
1088 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001089 }
Eric Laurent4e947da2019-10-17 15:24:06 -07001090 } else if (source == AUDIO_SOURCE_HOTWORD) {
1091 // For HOTWORD source allow capture when not on TOP if:
1092 // All active clients are using HOTWORD source
1093 // AND no call is active
1094 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurentc21d5692020-02-25 10:24:36 -08001095 if (onlyHotwordActive
1096 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent4e947da2019-10-17 15:24:06 -07001097 allowCapture = true;
1098 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001099 } else if (mUidPolicy->isCurrentImeUid(currentUid)) {
Kohsuke Yatoha623a132020-03-24 20:10:26 -07001100 // For current InputMethodService allow capture if:
1101 // A RTT call is active AND the source is VOICE_RECOGNITION
1102 if (rttCallActive && source == AUDIO_SOURCE_VOICE_RECOGNITION) {
1103 allowCapture = true;
1104 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001105 }
Eric Laurent8c7ef892021-06-10 13:32:16 +02001106 setAppState_l(current,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001107 allowCapture ? apmStatFromAmState(mUidPolicy->getUidState(currentUid)) :
Eric Laurent1ff16a72019-03-14 18:35:04 -07001108 APP_STATE_IDLE);
Eric Laurente8c8b432018-10-17 10:08:02 -07001109 }
1110}
1111
Michael Groovercfd28302018-12-11 19:16:46 -08001112void AudioPolicyService::silenceAllRecordings_l() {
1113 for (size_t i = 0; i < mAudioRecordClients.size(); i++) {
1114 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -07001115 if (!isVirtualSource(current->attributes.source)) {
Eric Laurent8c7ef892021-06-10 13:32:16 +02001116 setAppState_l(current, APP_STATE_IDLE);
Eric Laurent1ff16a72019-03-14 18:35:04 -07001117 }
Michael Groovercfd28302018-12-11 19:16:46 -08001118 }
1119}
1120
Eric Laurente8c8b432018-10-17 10:08:02 -07001121/* static */
1122app_state_t AudioPolicyService::apmStatFromAmState(int amState) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001123
1124 if (amState == ActivityManager::PROCESS_STATE_UNKNOWN) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001125 return APP_STATE_IDLE;
Eric Laurent1ff16a72019-03-14 18:35:04 -07001126 } else if (amState <= ActivityManager::PROCESS_STATE_TOP) {
1127 // include persistent services
1128 return APP_STATE_TOP;
Eric Laurente8c8b432018-10-17 10:08:02 -07001129 }
1130 return APP_STATE_FOREGROUND;
1131}
1132
Eric Laurent4eb58f12018-12-07 16:41:02 -08001133/* static */
Eric Laurent2dc962b2019-03-01 08:25:25 -08001134bool AudioPolicyService::isVirtualSource(audio_source_t source)
Eric Laurent4eb58f12018-12-07 16:41:02 -08001135{
1136 switch (source) {
1137 case AUDIO_SOURCE_VOICE_UPLINK:
1138 case AUDIO_SOURCE_VOICE_DOWNLINK:
1139 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent2dc962b2019-03-01 08:25:25 -08001140 case AUDIO_SOURCE_REMOTE_SUBMIX:
1141 case AUDIO_SOURCE_FM_TUNER:
Eric Laurent68eb2122020-04-30 17:40:57 -07001142 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent4eb58f12018-12-07 16:41:02 -08001143 return true;
1144 default:
1145 break;
1146 }
1147 return false;
1148}
1149
Eric Laurented726cc2021-07-01 14:26:41 +02001150/* static */
1151bool AudioPolicyService::isAppOpSource(audio_source_t source)
1152{
1153 switch (source) {
1154 case AUDIO_SOURCE_FM_TUNER:
1155 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent637bd202021-09-22 11:17:11 +02001156 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurented726cc2021-07-01 14:26:41 +02001157 return false;
1158 default:
1159 break;
1160 }
1161 return true;
1162}
1163
Eric Laurent8c7ef892021-06-10 13:32:16 +02001164void AudioPolicyService::setAppState_l(sp<AudioRecordClient> client, app_state_t state)
Eric Laurente8c8b432018-10-17 10:08:02 -07001165{
1166 AutoCallerClear acc;
1167
1168 if (mAudioPolicyManager) {
Eric Laurent8c7ef892021-06-10 13:32:16 +02001169 mAudioPolicyManager->setAppState(client->portId, state);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001170 }
1171 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1172 if (af) {
Eric Laurentf32108e2018-10-04 17:22:04 -07001173 bool silenced = state == APP_STATE_IDLE;
Eric Laurent8c7ef892021-06-10 13:32:16 +02001174 if (client->silenced != silenced) {
1175 if (client->active) {
1176 if (silenced) {
1177 finishRecording(client->attributionSource, client->attributes.source);
1178 } else {
1179 std::stringstream msg;
1180 msg << "Audio recording un-silenced on session " << client->session;
1181 if (!startRecording(client->attributionSource, String16(msg.str().c_str()),
1182 client->attributes.source)) {
1183 silenced = true;
1184 }
1185 }
1186 }
1187 af->setRecordSilenced(client->portId, silenced);
1188 client->silenced = silenced;
1189 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001190 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001191}
1192
Glenn Kasten0f11b512014-01-31 16:18:54 -08001193status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001194{
Glenn Kasten44deb052012-02-05 18:09:08 -08001195 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001196 dumpPermissionDenial(fd);
1197 } else {
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001198 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001199 if (!locked) {
1200 String8 result(kDeadlockedString);
1201 write(fd, result.string(), result.size());
1202 }
1203
1204 dumpInternals(fd);
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001205
1206 String8 actPtr = String8::format("AudioCommandThread: %p\n", mAudioCommandThread.get());
1207 write(fd, actPtr.string(), actPtr.size());
Glenn Kasten9d1f02d2012-02-08 17:47:58 -08001208 if (mAudioCommandThread != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001209 mAudioCommandThread->dump(fd);
1210 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001211
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001212 String8 octPtr = String8::format("OutputCommandThread: %p\n", mOutputCommandThread.get());
1213 write(fd, octPtr.string(), octPtr.size());
1214 if (mOutputCommandThread != 0) {
1215 mOutputCommandThread->dump(fd);
1216 }
1217
Eric Laurentdce54a12014-03-10 12:19:46 -07001218 if (mAudioPolicyManager) {
1219 mAudioPolicyManager->dump(fd);
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001220 } else {
1221 String8 apmPtr = String8::format("AudioPolicyManager: %p\n", mAudioPolicyManager);
1222 write(fd, apmPtr.string(), apmPtr.size());
Eric Laurentdce54a12014-03-10 12:19:46 -07001223 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001224
Kevin Rocard8be94972019-02-22 13:26:25 -08001225 mPackageManager.dump(fd);
1226
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001227 dumpReleaseLock(mLock, locked);
Andy Hungc747c532022-03-07 21:41:14 -08001228
Shunkai Yao59b27bc2022-07-22 18:42:27 +00001229 if (mSpatializer != nullptr) {
1230 std::string dumpString = mSpatializer->toString(1 /* level */);
1231 write(fd, dumpString.c_str(), dumpString.size());
1232 } else {
1233 String8 spatializerPtr = String8::format("Spatializer no supportted on this device\n");
1234 write(fd, spatializerPtr.c_str(), spatializerPtr.size());
1235 }
1236
Andy Hungc747c532022-03-07 21:41:14 -08001237 {
1238 std::string timeCheckStats = getIAudioPolicyServiceStatistics().dump();
1239 dprintf(fd, "\nIAudioPolicyService binder call profile\n");
1240 write(fd, timeCheckStats.c_str(), timeCheckStats.size());
1241 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001242 }
1243 return NO_ERROR;
1244}
1245
1246status_t AudioPolicyService::dumpPermissionDenial(int fd)
1247{
1248 const size_t SIZE = 256;
1249 char buffer[SIZE];
1250 String8 result;
1251 snprintf(buffer, SIZE, "Permission Denial: "
1252 "can't dump AudioPolicyService from pid=%d, uid=%d\n",
1253 IPCThreadState::self()->getCallingPid(),
1254 IPCThreadState::self()->getCallingUid());
1255 result.append(buffer);
1256 write(fd, result.string(), result.size());
1257 return NO_ERROR;
1258}
1259
1260status_t AudioPolicyService::onTransact(
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001261 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001262 // make sure transactions reserved to AudioFlinger do not come from other processes
1263 switch (code) {
1264 case TRANSACTION_startOutput:
1265 case TRANSACTION_stopOutput:
1266 case TRANSACTION_releaseOutput:
1267 case TRANSACTION_getInputForAttr:
1268 case TRANSACTION_startInput:
1269 case TRANSACTION_stopInput:
1270 case TRANSACTION_releaseInput:
1271 case TRANSACTION_getOutputForEffect:
1272 case TRANSACTION_registerEffect:
1273 case TRANSACTION_unregisterEffect:
1274 case TRANSACTION_setEffectEnabled:
1275 case TRANSACTION_getStrategyForStream:
1276 case TRANSACTION_getOutputForAttr:
1277 case TRANSACTION_moveEffectsToIo:
1278 ALOGW("%s: transaction %d received from PID %d",
1279 __func__, code, IPCThreadState::self()->getCallingPid());
1280 return INVALID_OPERATION;
1281 default:
1282 break;
1283 }
1284
1285 // make sure the following transactions come from system components
1286 switch (code) {
1287 case TRANSACTION_setDeviceConnectionState:
1288 case TRANSACTION_handleDeviceConfigChange:
1289 case TRANSACTION_setPhoneState:
1290//FIXME: Allow setForceUse calls from system apps until a better use case routing API is available
1291// case TRANSACTION_setForceUse:
1292 case TRANSACTION_initStreamVolume:
1293 case TRANSACTION_setStreamVolumeIndex:
1294 case TRANSACTION_setVolumeIndexForAttributes:
1295 case TRANSACTION_getStreamVolumeIndex:
1296 case TRANSACTION_getVolumeIndexForAttributes:
1297 case TRANSACTION_getMinVolumeIndexForAttributes:
1298 case TRANSACTION_getMaxVolumeIndexForAttributes:
1299 case TRANSACTION_isStreamActive:
1300 case TRANSACTION_isStreamActiveRemotely:
1301 case TRANSACTION_isSourceActive:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001302 case TRANSACTION_registerPolicyMixes:
1303 case TRANSACTION_setMasterMono:
1304 case TRANSACTION_getSurroundFormats:
Kriti Dang6537def2021-03-02 13:46:59 +01001305 case TRANSACTION_getReportedSurroundFormats:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001306 case TRANSACTION_setSurroundFormatEnabled:
Oscar Azucena829d90d2022-01-28 17:17:56 -08001307 case TRANSACTION_setAssistantServicesUids:
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001308 case TRANSACTION_setActiveAssistantServicesUids:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001309 case TRANSACTION_setA11yServicesUids:
1310 case TRANSACTION_setUidDeviceAffinities:
1311 case TRANSACTION_removeUidDeviceAffinities:
1312 case TRANSACTION_setUserIdDeviceAffinities:
1313 case TRANSACTION_removeUserIdDeviceAffinities:
Pattydd807582021-11-04 21:01:03 +08001314 case TRANSACTION_getHwOffloadFormatsSupportedForBluetoothMedia:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001315 case TRANSACTION_listAudioVolumeGroups:
1316 case TRANSACTION_getVolumeGroupFromAudioAttributes:
1317 case TRANSACTION_acquireSoundTriggerSession:
1318 case TRANSACTION_releaseSoundTriggerSession:
Atneya Nair698f5ef2022-12-15 16:15:09 -08001319 case TRANSACTION_isHotwordStreamSupported:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001320 case TRANSACTION_setRttEnabled:
1321 case TRANSACTION_isCallScreenModeSupported:
1322 case TRANSACTION_setDevicesRoleForStrategy:
1323 case TRANSACTION_setSupportedSystemUsages:
1324 case TRANSACTION_removeDevicesRoleForStrategy:
Paul Wang5d7cdb52022-11-22 09:45:06 +00001325 case TRANSACTION_clearDevicesRoleForStrategy:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001326 case TRANSACTION_getDevicesForRoleAndStrategy:
1327 case TRANSACTION_getDevicesForAttributes:
1328 case TRANSACTION_setAllowedCapturePolicy:
1329 case TRANSACTION_onNewAudioModulesAvailable:
1330 case TRANSACTION_setCurrentImeUid:
1331 case TRANSACTION_registerSoundTriggerCaptureStateListener:
1332 case TRANSACTION_setDevicesRoleForCapturePreset:
1333 case TRANSACTION_addDevicesRoleForCapturePreset:
1334 case TRANSACTION_removeDevicesRoleForCapturePreset:
1335 case TRANSACTION_clearDevicesRoleForCapturePreset:
Eric Laurent81dd0f52021-07-05 11:54:40 +02001336 case TRANSACTION_getDevicesForRoleAndCapturePreset:
jiabina84c3d32022-12-02 18:59:55 +00001337 case TRANSACTION_getSpatializer:
1338 case TRANSACTION_setPreferredMixerAttributes:
1339 case TRANSACTION_clearPreferredMixerAttributes: {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001340 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
1341 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
1342 __func__, code, IPCThreadState::self()->getCallingPid(),
1343 IPCThreadState::self()->getCallingUid());
1344 return INVALID_OPERATION;
1345 }
1346 } break;
1347 default:
1348 break;
1349 }
1350
Andy Hungc747c532022-03-07 21:41:14 -08001351 const std::string methodName = getIAudioPolicyServiceStatistics().getMethodForCode(code);
1352 mediautils::TimeCheck check(
1353 std::string("IAudioPolicyService::").append(methodName),
1354 [code, methodName](bool timeout, float elapsedMs) { // don't move methodName.
1355 if (timeout) {
1356 mediametrics::LogItem(AMEDIAMETRICS_KEY_AUDIO_POLICY)
1357 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_TIMEOUT)
1358 .set(AMEDIAMETRICS_PROP_METHODCODE, int64_t(code))
1359 .set(AMEDIAMETRICS_PROP_METHODNAME, methodName.c_str())
1360 .record();
1361 } else {
1362 getIAudioPolicyServiceStatistics().event(code, elapsedMs);
1363 }
Andy Hung741b3dd2022-06-13 19:49:43 -07001364 }, mediautils::TimeCheck::kDefaultTimeoutDuration,
1365 mediautils::TimeCheck::kDefaultSecondChanceDuration,
1366 true /* crashOnTimeout */);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001367
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001368 switch (code) {
1369 case SHELL_COMMAND_TRANSACTION: {
1370 int in = data.readFileDescriptor();
1371 int out = data.readFileDescriptor();
1372 int err = data.readFileDescriptor();
1373 int argc = data.readInt32();
1374 Vector<String16> args;
1375 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
1376 args.add(data.readString16());
1377 }
1378 sp<IBinder> unusedCallback;
1379 sp<IResultReceiver> resultReceiver;
1380 status_t status;
1381 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
1382 return status;
1383 }
1384 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
1385 return status;
1386 }
1387 status = shellCommand(in, out, err, args);
1388 if (resultReceiver != nullptr) {
1389 resultReceiver->send(status);
1390 }
1391 return NO_ERROR;
1392 }
1393 }
1394
Mathias Agopian65ab4712010-07-14 17:59:35 -07001395 return BnAudioPolicyService::onTransact(code, data, reply, flags);
1396}
1397
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001398// ------------------- Shell command implementation -------------------
1399
1400// NOTE: This is a remote API - make sure all args are validated
1401status_t AudioPolicyService::shellCommand(int in, int out, int err, Vector<String16>& args) {
1402 if (!checkCallingPermission(sManageAudioPolicyPermission, nullptr, nullptr)) {
1403 return PERMISSION_DENIED;
1404 }
1405 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
1406 return BAD_VALUE;
1407 }
jovanakbe066e12019-09-02 11:54:39 -07001408 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001409 return handleSetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001410 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001411 return handleResetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001412 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001413 return handleGetUidState(args, out, err);
Eric Laurent269acb42021-04-23 16:53:22 +02001414 } else if (args.size() >= 1 && args[0] == String16("purge_permission-cache")) {
1415 purgePermissionCache();
1416 return NO_ERROR;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001417 } else if (args.size() == 1 && args[0] == String16("help")) {
1418 printHelp(out);
1419 return NO_ERROR;
1420 }
1421 printHelp(err);
1422 return BAD_VALUE;
1423}
1424
jovanakbe066e12019-09-02 11:54:39 -07001425static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1426 if (userId < 0) {
1427 ALOGE("Invalid user: %d", userId);
1428 dprintf(err, "Invalid user: %d\n", userId);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001429 return BAD_VALUE;
1430 }
jovanakbe066e12019-09-02 11:54:39 -07001431
1432 PermissionController pc;
1433 uid = pc.getPackageUid(packageName, 0);
1434 if (uid <= 0) {
1435 ALOGE("Unknown package: '%s'", String8(packageName).string());
1436 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1437 return BAD_VALUE;
1438 }
1439
1440 uid = multiuser_get_uid(userId, uid);
1441 return NO_ERROR;
1442}
1443
1444status_t AudioPolicyService::handleSetUidState(Vector<String16>& args, int err) {
1445 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
1446 if (!(args.size() == 3 || args.size() == 5)) {
1447 printHelp(err);
1448 return BAD_VALUE;
1449 }
1450
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001451 bool active = false;
1452 if (args[2] == String16("active")) {
1453 active = true;
1454 } else if ((args[2] != String16("idle"))) {
1455 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
1456 return BAD_VALUE;
1457 }
jovanakbe066e12019-09-02 11:54:39 -07001458
1459 int userId = 0;
1460 if (args.size() >= 5 && args[3] == String16("--user")) {
1461 userId = atoi(String8(args[4]));
1462 }
1463
1464 uid_t uid;
1465 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1466 return BAD_VALUE;
1467 }
1468
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001469 sp<UidPolicy> uidPolicy;
1470 {
1471 Mutex::Autolock _l(mLock);
1472 uidPolicy = mUidPolicy;
1473 }
1474 if (uidPolicy) {
1475 uidPolicy->addOverrideUid(uid, active);
1476 return NO_ERROR;
1477 }
1478 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001479}
1480
1481status_t AudioPolicyService::handleResetUidState(Vector<String16>& args, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001482 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1483 if (!(args.size() == 2 || args.size() == 4)) {
1484 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001485 return BAD_VALUE;
1486 }
jovanakbe066e12019-09-02 11:54:39 -07001487
1488 int userId = 0;
1489 if (args.size() >= 4 && args[2] == String16("--user")) {
1490 userId = atoi(String8(args[3]));
1491 }
1492
1493 uid_t uid;
1494 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1495 return BAD_VALUE;
1496 }
1497
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001498 sp<UidPolicy> uidPolicy;
1499 {
1500 Mutex::Autolock _l(mLock);
1501 uidPolicy = mUidPolicy;
1502 }
1503 if (uidPolicy) {
1504 uidPolicy->removeOverrideUid(uid);
1505 return NO_ERROR;
1506 }
1507 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001508}
1509
1510status_t AudioPolicyService::handleGetUidState(Vector<String16>& args, int out, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001511 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1512 if (!(args.size() == 2 || args.size() == 4)) {
1513 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001514 return BAD_VALUE;
1515 }
jovanakbe066e12019-09-02 11:54:39 -07001516
1517 int userId = 0;
1518 if (args.size() >= 4 && args[2] == String16("--user")) {
1519 userId = atoi(String8(args[3]));
1520 }
1521
1522 uid_t uid;
1523 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1524 return BAD_VALUE;
1525 }
1526
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001527 sp<UidPolicy> uidPolicy;
1528 {
1529 Mutex::Autolock _l(mLock);
1530 uidPolicy = mUidPolicy;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001531 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001532 if (uidPolicy) {
1533 return dprintf(out, uidPolicy->isUidActive(uid) ? "active\n" : "idle\n");
1534 }
1535 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001536}
1537
1538status_t AudioPolicyService::printHelp(int out) {
1539 return dprintf(out, "Audio policy service commands:\n"
jovanakbe066e12019-09-02 11:54:39 -07001540 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
1541 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
1542 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001543 " help print this message\n");
1544}
1545
Eric Laurent0d13fea2022-11-04 17:12:08 +01001546status_t AudioPolicyService::registerOutput(audio_io_handle_t output,
1547 const audio_config_base_t& config,
1548 const audio_output_flags_t flags) {
1549 return mUsecaseValidator->registerStream(output, config, flags);
1550}
1551
1552status_t AudioPolicyService::unregisterOutput(audio_io_handle_t output) {
1553 return mUsecaseValidator->unregisterStream(output);
1554}
1555
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001556// ----------- AudioPolicyService::UidPolicy implementation ----------
1557
1558void AudioPolicyService::UidPolicy::registerSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001559 status_t res = mAm.linkToDeath(this);
1560 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001561 | ActivityManager::UID_OBSERVER_IDLE
Eric Laurente8c8b432018-10-17 10:08:02 -07001562 | ActivityManager::UID_OBSERVER_ACTIVE
1563 | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001564 ActivityManager::PROCESS_STATE_UNKNOWN,
1565 String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001566 if (!res) {
1567 Mutex::Autolock _l(mLock);
1568 mObserverRegistered = true;
1569 } else {
1570 ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001571
Steven Moreland2f348142019-07-02 15:59:07 -07001572 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001573 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001574}
1575
1576void AudioPolicyService::UidPolicy::unregisterSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001577 mAm.unlinkToDeath(this);
1578 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001579 Mutex::Autolock _l(mLock);
1580 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001581}
1582
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001583void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
1584 Mutex::Autolock _l(mLock);
1585 mCachedUids.clear();
1586 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001587}
1588
Eric Laurente8c8b432018-10-17 10:08:02 -07001589void AudioPolicyService::UidPolicy::checkRegistered() {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001590 bool needToReregister = false;
1591 {
1592 Mutex::Autolock _l(mLock);
1593 needToReregister = !mObserverRegistered;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001594 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001595 if (needToReregister) {
1596 // Looks like ActivityManager has died previously, attempt to re-register.
1597 registerSelf();
1598 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001599}
1600
1601bool AudioPolicyService::UidPolicy::isUidActive(uid_t uid) {
1602 if (isServiceUid(uid)) return true;
1603 checkRegistered();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001604 {
1605 Mutex::Autolock _l(mLock);
1606 auto overrideIter = mOverrideUids.find(uid);
1607 if (overrideIter != mOverrideUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001608 return overrideIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001609 }
1610 // In an absense of the ActivityManager, assume everything to be active.
1611 if (!mObserverRegistered) return true;
1612 auto cacheIter = mCachedUids.find(uid);
Mikhail Naganoveba668a2018-04-05 08:13:15 -07001613 if (cacheIter != mCachedUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001614 return cacheIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001615 }
1616 }
1617 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001618 bool active = am.isUidActive(uid, String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001619 {
1620 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001621 mCachedUids.insert(std::pair<uid_t,
1622 std::pair<bool, int>>(uid, std::pair<bool, int>(active,
1623 ActivityManager::PROCESS_STATE_UNKNOWN)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001624 }
1625 return active;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001626}
1627
Eric Laurente8c8b432018-10-17 10:08:02 -07001628int AudioPolicyService::UidPolicy::getUidState(uid_t uid) {
1629 if (isServiceUid(uid)) {
1630 return ActivityManager::PROCESS_STATE_TOP;
1631 }
1632 checkRegistered();
1633 {
1634 Mutex::Autolock _l(mLock);
1635 auto overrideIter = mOverrideUids.find(uid);
1636 if (overrideIter != mOverrideUids.end()) {
1637 if (overrideIter->second.first) {
1638 if (overrideIter->second.second != ActivityManager::PROCESS_STATE_UNKNOWN) {
1639 return overrideIter->second.second;
1640 } else {
1641 auto cacheIter = mCachedUids.find(uid);
1642 if (cacheIter != mCachedUids.end()) {
1643 return cacheIter->second.second;
1644 }
1645 }
1646 }
1647 return ActivityManager::PROCESS_STATE_UNKNOWN;
1648 }
1649 // In an absense of the ActivityManager, assume everything to be active.
1650 if (!mObserverRegistered) {
1651 return ActivityManager::PROCESS_STATE_TOP;
1652 }
1653 auto cacheIter = mCachedUids.find(uid);
1654 if (cacheIter != mCachedUids.end()) {
1655 if (cacheIter->second.first) {
1656 return cacheIter->second.second;
1657 } else {
1658 return ActivityManager::PROCESS_STATE_UNKNOWN;
1659 }
1660 }
1661 }
1662 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001663 bool active = am.isUidActive(uid, String16("audioserver"));
Eric Laurente8c8b432018-10-17 10:08:02 -07001664 int state = ActivityManager::PROCESS_STATE_UNKNOWN;
1665 if (active) {
1666 state = am.getUidProcessState(uid, String16("audioserver"));
1667 }
1668 {
1669 Mutex::Autolock _l(mLock);
1670 mCachedUids.insert(std::pair<uid_t,
1671 std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
1672 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001673
Eric Laurente8c8b432018-10-17 10:08:02 -07001674 return state;
1675}
1676
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001677void AudioPolicyService::UidPolicy::onUidActive(uid_t uid) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001678 updateUid(&mCachedUids, uid, true, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001679}
1680
1681void AudioPolicyService::UidPolicy::onUidGone(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001682 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, false);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001683}
1684
1685void AudioPolicyService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001686 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001687}
1688
Eric Laurente8c8b432018-10-17 10:08:02 -07001689void AudioPolicyService::UidPolicy::onUidStateChanged(uid_t uid,
1690 int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07001691 int64_t procStateSeq __unused,
1692 int32_t capability __unused) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001693 if (procState != ActivityManager::PROCESS_STATE_UNKNOWN) {
1694 updateUid(&mCachedUids, uid, true, procState, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001695 }
1696}
1697
Austin Borger65577682022-02-17 00:25:43 +00001698void AudioPolicyService::UidPolicy::onUidProcAdjChanged(uid_t uid __unused) {
1699}
1700
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001701void AudioPolicyService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001702 updateUid(&mOverrideUids, uid, active, ActivityManager::PROCESS_STATE_UNKNOWN, insert);
1703}
1704
1705void AudioPolicyService::UidPolicy::notifyService() {
1706 sp<AudioPolicyService> service = mService.promote();
1707 if (service != nullptr) {
1708 service->updateUidStates();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001709 }
1710}
1711
Eric Laurente8c8b432018-10-17 10:08:02 -07001712void AudioPolicyService::UidPolicy::updateUid(std::unordered_map<uid_t,
1713 std::pair<bool, int>> *uids,
1714 uid_t uid,
1715 bool active,
1716 int state,
1717 bool insert) {
1718 if (isServiceUid(uid)) {
1719 return;
1720 }
1721 bool wasActive = isUidActive(uid);
1722 int previousState = getUidState(uid);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001723 {
1724 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001725 updateUidLocked(uids, uid, active, state, insert);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001726 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001727 if (wasActive != isUidActive(uid) || state != previousState) {
1728 notifyService();
1729 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001730}
1731
Eric Laurente8c8b432018-10-17 10:08:02 -07001732void AudioPolicyService::UidPolicy::updateUidLocked(std::unordered_map<uid_t,
1733 std::pair<bool, int>> *uids,
1734 uid_t uid,
1735 bool active,
1736 int state,
1737 bool insert) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001738 auto it = uids->find(uid);
1739 if (it != uids->end()) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001740 if (insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001741 if (state == ActivityManager::PROCESS_STATE_UNKNOWN) {
1742 it->second.first = active;
1743 }
1744 if (it->second.first) {
1745 it->second.second = state;
1746 } else {
1747 it->second.second = ActivityManager::PROCESS_STATE_UNKNOWN;
1748 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001749 } else {
1750 uids->erase(it);
1751 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001752 } else if (insert && (state == ActivityManager::PROCESS_STATE_UNKNOWN)) {
1753 uids->insert(std::pair<uid_t, std::pair<bool, int>>(uid,
1754 std::pair<bool, int>(active, state)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001755 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001756}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001757
Eric Laurent4eb58f12018-12-07 16:41:02 -08001758bool AudioPolicyService::UidPolicy::isA11yOnTop() {
lihong80e1f56e2022-08-25 11:15:33 +08001759 Mutex::Autolock _l(mLock);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001760 for (const auto &uid : mCachedUids) {
Eric Laurent47670c92019-08-28 16:59:05 -07001761 if (!isA11yUid(uid.first)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001762 continue;
1763 }
Amith Yamasanibcbb3002019-01-23 13:53:33 -08001764 if (uid.second.second >= ActivityManager::PROCESS_STATE_TOP
1765 && uid.second.second <= ActivityManager::PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001766 return true;
1767 }
1768 }
1769 return false;
1770}
1771
Eric Laurentb78763e2018-10-17 10:08:02 -07001772bool AudioPolicyService::UidPolicy::isA11yUid(uid_t uid)
1773{
1774 std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid);
1775 return it != mA11yUids.end();
1776}
1777
Oscar Azucena829d90d2022-01-28 17:17:56 -08001778void AudioPolicyService::UidPolicy::setAssistantUids(const std::vector<uid_t>& uids) {
1779 mAssistantUids.clear();
1780 mAssistantUids = uids;
1781}
1782
1783bool AudioPolicyService::UidPolicy::isAssistantUid(uid_t uid)
1784{
1785 std::vector<uid_t>::iterator it = find(mAssistantUids.begin(), mAssistantUids.end(), uid);
1786 return it != mAssistantUids.end();
1787}
1788
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001789void AudioPolicyService::UidPolicy::setActiveAssistantUids(const std::vector<uid_t>& activeUids) {
1790 mActiveAssistantUids = activeUids;
1791}
1792
1793bool AudioPolicyService::UidPolicy::isActiveAssistantUid(uid_t uid)
1794{
1795 std::vector<uid_t>::iterator it = find(mActiveAssistantUids.begin(),
1796 mActiveAssistantUids.end(), uid);
1797 return it != mActiveAssistantUids.end();
1798}
1799
Oscar Azucena829d90d2022-01-28 17:17:56 -08001800void AudioPolicyService::UidPolicy::dumpInternals(int fd) {
1801 const size_t SIZE = 256;
1802 char buffer[SIZE];
1803 String8 result;
1804 auto appendUidsToResult = [&](const char* title, const std::vector<uid_t> &uids) {
1805 snprintf(buffer, SIZE, "\t%s: \n", title);
1806 result.append(buffer);
1807 int counter = 0;
1808 if (uids.empty()) {
1809 snprintf(buffer, SIZE, "\t\tNo UIDs present.\n");
1810 result.append(buffer);
1811 return;
1812 }
1813 for (const auto &uid : uids) {
1814 snprintf(buffer, SIZE, "\t\tUID[%d]=%d\n", counter++, uid);
1815 result.append(buffer);
1816 }
1817 };
1818
1819 snprintf(buffer, SIZE, "UID Policy:\n");
1820 result.append(buffer);
1821 snprintf(buffer, SIZE, "\tmObserverRegistered=%s\n",(mObserverRegistered ? "True":"False"));
1822 result.append(buffer);
1823
1824 appendUidsToResult("Assistants UIDs", mAssistantUids);
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001825 appendUidsToResult("Active Assistants UIDs", mActiveAssistantUids);
Oscar Azucena829d90d2022-01-28 17:17:56 -08001826
1827 appendUidsToResult("Accessibility UIDs", mA11yUids);
1828
1829 snprintf(buffer, SIZE, "\tInput Method Service UID=%d\n", mCurrentImeUid);
1830 result.append(buffer);
1831
1832 snprintf(buffer, SIZE, "\tIs RTT Enabled: %s\n", (mRttEnabled ? "True":"False"));
1833 result.append(buffer);
1834
1835 write(fd, result.string(), result.size());
1836}
1837
Michael Groovercfd28302018-12-11 19:16:46 -08001838// ----------- AudioPolicyService::SensorPrivacyService implementation ----------
1839void AudioPolicyService::SensorPrivacyPolicy::registerSelf() {
1840 SensorPrivacyManager spm;
1841 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
Eric Laurent35cd7932022-11-17 11:47:19 +01001842 (void)spm.addToggleSensorPrivacyListener(this);
Michael Groovercfd28302018-12-11 19:16:46 -08001843 spm.addSensorPrivacyListener(this);
1844}
1845
1846void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
1847 SensorPrivacyManager spm;
1848 spm.removeSensorPrivacyListener(this);
Eric Laurent35cd7932022-11-17 11:47:19 +01001849 spm.removeToggleSensorPrivacyListener(this);
Michael Groovercfd28302018-12-11 19:16:46 -08001850}
1851
1852bool AudioPolicyService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1853 return mSensorPrivacyEnabled;
1854}
1855
Evan Seversond8dc6832022-01-27 10:47:03 -08001856binder::Status AudioPolicyService::SensorPrivacyPolicy::onSensorPrivacyChanged(
1857 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Groovercfd28302018-12-11 19:16:46 -08001858 mSensorPrivacyEnabled = enabled;
1859 sp<AudioPolicyService> service = mService.promote();
1860 if (service != nullptr) {
1861 service->updateUidStates();
1862 }
1863 return binder::Status::ok();
1864}
1865
Eric Laurented726cc2021-07-01 14:26:41 +02001866// ----------- AudioPolicyService::OpRecordAudioMonitor implementation ----------
1867
1868// static
1869sp<AudioPolicyService::OpRecordAudioMonitor>
1870AudioPolicyService::OpRecordAudioMonitor::createIfNeeded(
1871 const AttributionSourceState& attributionSource, const audio_attributes_t& attr,
1872 wp<AudioCommandThread> commandThread)
1873{
Eric Laurent987ce102021-07-05 12:11:51 +02001874 if (isAudioServerOrRootUid(attributionSource.uid)) {
1875 ALOGV("not silencing record for audio or root source %s",
Eric Laurented726cc2021-07-01 14:26:41 +02001876 attributionSource.toString().c_str());
1877 return nullptr;
1878 }
1879
1880 if (!AudioPolicyService::isAppOpSource(attr.source)) {
1881 ALOGD("not monitoring app op for uid %d and source %d",
1882 attributionSource.uid, attr.source);
1883 return nullptr;
1884 }
1885
1886 if (!attributionSource.packageName.has_value()
1887 || attributionSource.packageName.value().size() == 0) {
1888 return nullptr;
1889 }
1890 return new OpRecordAudioMonitor(attributionSource, getOpForSource(attr.source), commandThread);
1891}
1892
1893AudioPolicyService::OpRecordAudioMonitor::OpRecordAudioMonitor(
1894 const AttributionSourceState& attributionSource, int32_t appOp,
1895 wp<AudioCommandThread> commandThread) :
1896 mHasOp(true), mAttributionSource(attributionSource), mAppOp(appOp),
1897 mCommandThread(commandThread)
1898{
1899}
1900
1901AudioPolicyService::OpRecordAudioMonitor::~OpRecordAudioMonitor()
1902{
1903 if (mOpCallback != 0) {
1904 mAppOpsManager.stopWatchingMode(mOpCallback);
1905 }
1906 mOpCallback.clear();
1907}
1908
1909void AudioPolicyService::OpRecordAudioMonitor::onFirstRef()
1910{
1911 checkOp();
1912 mOpCallback = new RecordAudioOpCallback(this);
1913 ALOGV("start watching op %d for %s", mAppOp, mAttributionSource.toString().c_str());
1914 // TODO: We need to always watch AppOpsManager::OP_RECORD_AUDIO too
1915 // since it controls the mic permission for legacy apps.
1916 mAppOpsManager.startWatchingMode(mAppOp, VALUE_OR_FATAL(aidl2legacy_string_view_String16(
1917 mAttributionSource.packageName.value_or(""))),
1918 mOpCallback);
1919}
1920
1921bool AudioPolicyService::OpRecordAudioMonitor::hasOp() const {
1922 return mHasOp.load();
1923}
1924
1925// Called by RecordAudioOpCallback when the app op corresponding to this OpRecordAudioMonitor
1926// is updated in AppOp callback and in onFirstRef()
1927// Note this method is never called (and never to be) for audio server / root track
1928// due to the UID in createIfNeeded(). As a result for those record track, it's:
1929// - not called from constructor,
1930// - not called from RecordAudioOpCallback because the callback is not installed in this case
1931void AudioPolicyService::OpRecordAudioMonitor::checkOp(bool updateUidStates)
1932{
1933 // TODO: We need to always check AppOpsManager::OP_RECORD_AUDIO too
1934 // since it controls the mic permission for legacy apps.
1935 const int32_t mode = mAppOpsManager.checkOp(mAppOp,
1936 mAttributionSource.uid, VALUE_OR_FATAL(aidl2legacy_string_view_String16(
1937 mAttributionSource.packageName.value_or(""))));
1938 const bool hasIt = (mode == AppOpsManager::MODE_ALLOWED);
1939 // verbose logging only log when appOp changed
1940 ALOGI_IF(hasIt != mHasOp.load(),
1941 "App op %d missing, %ssilencing record %s",
1942 mAppOp, hasIt ? "un" : "", mAttributionSource.toString().c_str());
1943 mHasOp.store(hasIt);
1944
1945 if (updateUidStates) {
1946 sp<AudioCommandThread> commandThread = mCommandThread.promote();
1947 if (commandThread != nullptr) {
1948 commandThread->updateUidStatesCommand();
1949 }
1950 }
1951}
1952
1953AudioPolicyService::OpRecordAudioMonitor::RecordAudioOpCallback::RecordAudioOpCallback(
1954 const wp<OpRecordAudioMonitor>& monitor) : mMonitor(monitor)
1955{ }
1956
1957void AudioPolicyService::OpRecordAudioMonitor::RecordAudioOpCallback::opChanged(int32_t op,
1958 const String16& packageName __unused) {
1959 sp<OpRecordAudioMonitor> monitor = mMonitor.promote();
1960 if (monitor != NULL) {
1961 if (op != monitor->getOp()) {
1962 return;
1963 }
1964 monitor->checkOp(true);
1965 }
1966}
1967
1968
Mathias Agopian65ab4712010-07-14 17:59:35 -07001969// ----------- AudioPolicyService::AudioCommandThread implementation ----------
1970
Eric Laurentbfb1b832013-01-07 09:53:42 -08001971AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
1972 const wp<AudioPolicyService>& service)
1973 : Thread(false), mName(name), mService(service)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001974{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001975}
1976
1977
1978AudioPolicyService::AudioCommandThread::~AudioCommandThread()
1979{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001980 if (!mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001981 release_wake_lock(mName.string());
1982 }
1983 mAudioCommands.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001984}
1985
1986void AudioPolicyService::AudioCommandThread::onFirstRef()
1987{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001988 run(mName.string(), ANDROID_PRIORITY_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001989}
1990
1991bool AudioPolicyService::AudioCommandThread::threadLoop()
1992{
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001993 nsecs_t waitTime = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001994
1995 mLock.lock();
1996 while (!exitPending())
1997 {
Eric Laurent59a89232014-06-08 14:14:17 -07001998 sp<AudioPolicyService> svc;
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07001999 int numTimesBecameEmpty = 0;
Eric Laurent59a89232014-06-08 14:14:17 -07002000 while (!mAudioCommands.isEmpty() && !exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002001 nsecs_t curTime = systemTime();
2002 // commands are sorted by increasing time stamp: execute them from index 0 and up
2003 if (mAudioCommands[0]->mTime <= curTime) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002004 sp<AudioCommand> command = mAudioCommands[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07002005 mAudioCommands.removeAt(0);
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07002006 if (mAudioCommands.isEmpty()) {
2007 ++numTimesBecameEmpty;
2008 }
Eric Laurent0ede8922014-05-09 18:04:42 -07002009 mLastCommand = command;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002010
2011 switch (command->mCommand) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002012 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002013 VolumeData *data = (VolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01002014 ALOGV("AudioCommandThread() processing set volume stream %d, \
Eric Laurentde070132010-07-13 04:45:46 -07002015 volume %f, output %d", data->mStream, data->mVolume, data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07002016 mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07002017 command->mStatus = AudioSystem::setStreamVolume(data->mStream,
2018 data->mVolume,
2019 data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07002020 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002021 }break;
2022 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002023 ParametersData *data = (ParametersData *)command->mParam.get();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002024 ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
2025 data->mKeyValuePairs.string(), data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07002026 mLock.unlock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002027 command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
Andy Hungfe726a62018-09-27 15:17:25 -07002028 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002029 }break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002030 case SET_VOICE_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002031 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01002032 ALOGV("AudioCommandThread() processing set voice volume volume %f",
Eric Laurentde070132010-07-13 04:45:46 -07002033 data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07002034 mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002035 command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07002036 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002037 }break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002038 case STOP_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002039 StopOutputData *data = (StopOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002040 ALOGV("AudioCommandThread() processing stop output portId %d",
2041 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07002042 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002043 if (svc == 0) {
2044 break;
2045 }
2046 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002047 svc->doStopOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002048 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002049 }break;
2050 case RELEASE_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002051 ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002052 ALOGV("AudioCommandThread() processing release output portId %d",
2053 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07002054 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002055 if (svc == 0) {
2056 break;
2057 }
2058 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002059 svc->doReleaseOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002060 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002061 }break;
Eric Laurent951f4552014-05-20 10:48:17 -07002062 case CREATE_AUDIO_PATCH: {
2063 CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
2064 ALOGV("AudioCommandThread() processing create audio patch");
2065 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
2066 if (af == 0) {
2067 command->mStatus = PERMISSION_DENIED;
2068 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07002069 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07002070 command->mStatus = af->createAudioPatch(&data->mPatch, &data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07002071 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07002072 }
2073 } break;
2074 case RELEASE_AUDIO_PATCH: {
2075 ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
2076 ALOGV("AudioCommandThread() processing release audio patch");
2077 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
2078 if (af == 0) {
2079 command->mStatus = PERMISSION_DENIED;
2080 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07002081 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07002082 command->mStatus = af->releaseAudioPatch(data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07002083 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07002084 }
2085 } break;
Eric Laurentb52c1522014-05-20 11:27:36 -07002086 case UPDATE_AUDIOPORT_LIST: {
2087 ALOGV("AudioCommandThread() processing update audio port list");
Eric Laurent59a89232014-06-08 14:14:17 -07002088 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07002089 if (svc == 0) {
2090 break;
2091 }
2092 mLock.unlock();
2093 svc->doOnAudioPortListUpdate();
2094 mLock.lock();
2095 }break;
2096 case UPDATE_AUDIOPATCH_LIST: {
2097 ALOGV("AudioCommandThread() processing update audio patch list");
Eric Laurent59a89232014-06-08 14:14:17 -07002098 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07002099 if (svc == 0) {
2100 break;
2101 }
2102 mLock.unlock();
2103 svc->doOnAudioPatchListUpdate();
2104 mLock.lock();
2105 }break;
François Gaffiecfe17322018-11-07 13:41:29 +01002106 case CHANGED_AUDIOVOLUMEGROUP: {
2107 AudioVolumeGroupData *data =
2108 static_cast<AudioVolumeGroupData *>(command->mParam.get());
2109 ALOGV("AudioCommandThread() processing update audio volume group");
2110 svc = mService.promote();
2111 if (svc == 0) {
2112 break;
2113 }
2114 mLock.unlock();
2115 svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
2116 mLock.lock();
2117 }break;
Eric Laurente1715a42014-05-20 11:30:42 -07002118 case SET_AUDIOPORT_CONFIG: {
2119 SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
2120 ALOGV("AudioCommandThread() processing set port config");
2121 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
2122 if (af == 0) {
2123 command->mStatus = PERMISSION_DENIED;
2124 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07002125 mLock.unlock();
Eric Laurente1715a42014-05-20 11:30:42 -07002126 command->mStatus = af->setAudioPortConfig(&data->mConfig);
Andy Hungfe726a62018-09-27 15:17:25 -07002127 mLock.lock();
Eric Laurente1715a42014-05-20 11:30:42 -07002128 }
2129 } break;
Jean-Michel Trivide801052015-04-14 19:10:14 -07002130 case DYN_POLICY_MIX_STATE_UPDATE: {
2131 DynPolicyMixStateUpdateData *data =
2132 (DynPolicyMixStateUpdateData *)command->mParam.get();
Jean-Michel Trivide801052015-04-14 19:10:14 -07002133 ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
2134 data->mRegId.string(), data->mState);
2135 svc = mService.promote();
2136 if (svc == 0) {
2137 break;
2138 }
2139 mLock.unlock();
2140 svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
2141 mLock.lock();
2142 } break;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002143 case RECORDING_CONFIGURATION_UPDATE: {
2144 RecordingConfigurationUpdateData *data =
2145 (RecordingConfigurationUpdateData *)command->mParam.get();
2146 ALOGV("AudioCommandThread() processing recording configuration update");
2147 svc = mService.promote();
2148 if (svc == 0) {
2149 break;
2150 }
2151 mLock.unlock();
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002152 svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -08002153 &data->mClientConfig, data->mClientEffects,
2154 &data->mDeviceConfig, data->mEffects,
2155 data->mPatchHandle, data->mSource);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002156 mLock.lock();
2157 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002158 case SET_EFFECT_SUSPENDED: {
2159 SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
2160 ALOGV("AudioCommandThread() processing set effect suspended");
2161 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
2162 if (af != 0) {
2163 mLock.unlock();
2164 af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
2165 mLock.lock();
2166 }
2167 } break;
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002168 case AUDIO_MODULES_UPDATE: {
2169 ALOGV("AudioCommandThread() processing audio modules update");
2170 svc = mService.promote();
2171 if (svc == 0) {
2172 break;
2173 }
2174 mLock.unlock();
2175 svc->doOnNewAudioModulesAvailable();
2176 mLock.lock();
2177 } break;
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002178 case ROUTING_UPDATED: {
2179 ALOGV("AudioCommandThread() processing routing update");
2180 svc = mService.promote();
2181 if (svc == 0) {
2182 break;
2183 }
2184 mLock.unlock();
2185 svc->doOnRoutingUpdated();
2186 mLock.lock();
2187 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002188
Eric Laurented726cc2021-07-01 14:26:41 +02002189 case UPDATE_UID_STATES: {
2190 ALOGV("AudioCommandThread() processing updateUID states");
2191 svc = mService.promote();
2192 if (svc == 0) {
2193 break;
2194 }
2195 mLock.unlock();
2196 svc->updateUidStates();
2197 mLock.lock();
2198 } break;
2199
Eric Laurent15903592022-02-24 20:44:36 +01002200 case CHECK_SPATIALIZER_OUTPUT: {
2201 ALOGV("AudioCommandThread() processing check spatializer");
Eric Laurent81dd0f52021-07-05 11:54:40 +02002202 svc = mService.promote();
2203 if (svc == 0) {
2204 break;
2205 }
2206 mLock.unlock();
2207 svc->doOnCheckSpatializer();
2208 mLock.lock();
2209 } break;
2210
Eric Laurent15903592022-02-24 20:44:36 +01002211 case UPDATE_ACTIVE_SPATIALIZER_TRACKS: {
2212 ALOGV("AudioCommandThread() processing update spatializer tracks");
2213 svc = mService.promote();
2214 if (svc == 0) {
2215 break;
2216 }
2217 mLock.unlock();
2218 svc->doOnUpdateActiveSpatializerTracks();
2219 mLock.lock();
2220 } break;
2221
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002222 case VOL_RANGE_INIT_REQUEST: {
2223 ALOGV("AudioCommandThread() processing volume range init request");
2224 svc = mService.promote();
2225 if (svc == 0) {
2226 break;
2227 }
2228 mLock.unlock();
2229 svc->doOnVolumeRangeInitRequest();
2230 mLock.lock();
2231 } break;
2232
Mathias Agopian65ab4712010-07-14 17:59:35 -07002233 default:
Steve Block5ff1dd52012-01-05 23:22:43 +00002234 ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002235 }
Eric Laurent0ede8922014-05-09 18:04:42 -07002236 {
2237 Mutex::Autolock _l(command->mLock);
2238 if (command->mWaitStatus) {
2239 command->mWaitStatus = false;
2240 command->mCond.signal();
2241 }
2242 }
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002243 waitTime = -1;
Zach Janga754b4f2015-10-27 01:29:34 +00002244 // release mLock before releasing strong reference on the service as
2245 // AudioPolicyService destructor calls AudioCommandThread::exit() which
2246 // acquires mLock.
2247 mLock.unlock();
2248 svc.clear();
2249 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002250 } else {
2251 waitTime = mAudioCommands[0]->mTime - curTime;
2252 break;
2253 }
2254 }
Zach Janga754b4f2015-10-27 01:29:34 +00002255
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07002256 // release delayed commands wake lock as many times as we made the queue is
2257 // empty during popping.
2258 while (numTimesBecameEmpty--) {
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002259 release_wake_lock(mName.string());
Zach Janga754b4f2015-10-27 01:29:34 +00002260 }
2261
2262 // At this stage we have either an empty command queue or the first command in the queue
2263 // has a finite delay. So unless we are exiting it is safe to wait.
2264 if (!exitPending()) {
Eric Laurent59a89232014-06-08 14:14:17 -07002265 ALOGV("AudioCommandThread() going to sleep");
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002266 if (waitTime == -1) {
2267 mWaitWorkCV.wait(mLock);
2268 } else {
2269 mWaitWorkCV.waitRelative(mLock, waitTime);
2270 }
Eric Laurent59a89232014-06-08 14:14:17 -07002271 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002272 }
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002273 // release delayed commands wake lock before quitting
2274 if (!mAudioCommands.isEmpty()) {
2275 release_wake_lock(mName.string());
2276 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002277 mLock.unlock();
2278 return false;
2279}
2280
2281status_t AudioPolicyService::AudioCommandThread::dump(int fd)
2282{
2283 const size_t SIZE = 256;
2284 char buffer[SIZE];
2285 String8 result;
2286
Mikhail Naganov12b716c2020-04-30 22:37:43 +00002287 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002288 if (!locked) {
2289 String8 result2(kCmdDeadlockedString);
2290 write(fd, result2.string(), result2.size());
2291 }
2292
2293 snprintf(buffer, SIZE, "- Commands:\n");
2294 result = String8(buffer);
2295 result.append(" Command Time Wait pParam\n");
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002296 for (size_t i = 0; i < mAudioCommands.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002297 mAudioCommands[i]->dump(buffer, SIZE);
2298 result.append(buffer);
2299 }
2300 result.append(" Last Command\n");
Eric Laurent0ede8922014-05-09 18:04:42 -07002301 if (mLastCommand != 0) {
2302 mLastCommand->dump(buffer, SIZE);
2303 result.append(buffer);
2304 } else {
2305 result.append(" none\n");
2306 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002307
2308 write(fd, result.string(), result.size());
2309
Mikhail Naganov12b716c2020-04-30 22:37:43 +00002310 dumpReleaseLock(mLock, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002311
2312 return NO_ERROR;
2313}
2314
Glenn Kastenfff6d712012-01-12 16:38:12 -08002315status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
Eric Laurentde070132010-07-13 04:45:46 -07002316 float volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002317 audio_io_handle_t output,
Eric Laurentde070132010-07-13 04:45:46 -07002318 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002319{
Eric Laurent0ede8922014-05-09 18:04:42 -07002320 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002321 command->mCommand = SET_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002322 sp<VolumeData> data = new VolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002323 data->mStream = stream;
2324 data->mVolume = volume;
2325 data->mIO = output;
2326 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002327 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002328 ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
Eric Laurentde070132010-07-13 04:45:46 -07002329 stream, volume, output);
Eric Laurent0ede8922014-05-09 18:04:42 -07002330 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002331}
2332
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002333status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
Dima Zavinfce7a472011-04-19 22:30:36 -07002334 const char *keyValuePairs,
Eric Laurentde070132010-07-13 04:45:46 -07002335 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002336{
Eric Laurent0ede8922014-05-09 18:04:42 -07002337 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002338 command->mCommand = SET_PARAMETERS;
Eric Laurent0ede8922014-05-09 18:04:42 -07002339 sp<ParametersData> data = new ParametersData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002340 data->mIO = ioHandle;
Dima Zavinfce7a472011-04-19 22:30:36 -07002341 data->mKeyValuePairs = String8(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002342 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002343 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002344 ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
Dima Zavinfce7a472011-04-19 22:30:36 -07002345 keyValuePairs, ioHandle, delayMs);
Eric Laurent0ede8922014-05-09 18:04:42 -07002346 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002347}
2348
2349status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
2350{
Eric Laurent0ede8922014-05-09 18:04:42 -07002351 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002352 command->mCommand = SET_VOICE_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002353 sp<VoiceVolumeData> data = new VoiceVolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002354 data->mVolume = volume;
2355 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002356 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002357 ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
Eric Laurent0ede8922014-05-09 18:04:42 -07002358 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002359}
2360
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002361void AudioPolicyService::AudioCommandThread::setEffectSuspendedCommand(int effectId,
2362 audio_session_t sessionId,
2363 bool suspended)
2364{
2365 sp<AudioCommand> command = new AudioCommand();
2366 command->mCommand = SET_EFFECT_SUSPENDED;
2367 sp<SetEffectSuspendedData> data = new SetEffectSuspendedData();
2368 data->mEffectId = effectId;
2369 data->mSessionId = sessionId;
2370 data->mSuspended = suspended;
2371 command->mParam = data;
2372 ALOGV("AudioCommandThread() adding set suspended effectId %d sessionId %d suspended %d",
2373 effectId, sessionId, suspended);
2374 sendCommand(command);
2375}
2376
2377
Eric Laurentd7fe0862018-07-14 16:48:01 -07002378void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002379{
Eric Laurent0ede8922014-05-09 18:04:42 -07002380 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002381 command->mCommand = STOP_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002382 sp<StopOutputData> data = new StopOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002383 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002384 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002385 ALOGV("AudioCommandThread() adding stop output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002386 sendCommand(command);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002387}
2388
Eric Laurentd7fe0862018-07-14 16:48:01 -07002389void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002390{
Eric Laurent0ede8922014-05-09 18:04:42 -07002391 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002392 command->mCommand = RELEASE_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002393 sp<ReleaseOutputData> data = new ReleaseOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002394 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002395 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002396 ALOGV("AudioCommandThread() adding release output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002397 sendCommand(command);
2398}
2399
Eric Laurent951f4552014-05-20 10:48:17 -07002400status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
2401 const struct audio_patch *patch,
2402 audio_patch_handle_t *handle,
2403 int delayMs)
2404{
2405 status_t status = NO_ERROR;
2406
2407 sp<AudioCommand> command = new AudioCommand();
2408 command->mCommand = CREATE_AUDIO_PATCH;
2409 CreateAudioPatchData *data = new CreateAudioPatchData();
2410 data->mPatch = *patch;
2411 data->mHandle = *handle;
2412 command->mParam = data;
2413 command->mWaitStatus = true;
2414 ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
2415 status = sendCommand(command, delayMs);
2416 if (status == NO_ERROR) {
2417 *handle = data->mHandle;
2418 }
2419 return status;
2420}
2421
2422status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
2423 int delayMs)
2424{
2425 sp<AudioCommand> command = new AudioCommand();
2426 command->mCommand = RELEASE_AUDIO_PATCH;
2427 ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
2428 data->mHandle = handle;
2429 command->mParam = data;
2430 command->mWaitStatus = true;
2431 ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
2432 return sendCommand(command, delayMs);
2433}
2434
Eric Laurentb52c1522014-05-20 11:27:36 -07002435void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
2436{
2437 sp<AudioCommand> command = new AudioCommand();
2438 command->mCommand = UPDATE_AUDIOPORT_LIST;
2439 ALOGV("AudioCommandThread() adding update audio port list");
2440 sendCommand(command);
2441}
2442
Eric Laurented726cc2021-07-01 14:26:41 +02002443void AudioPolicyService::AudioCommandThread::updateUidStatesCommand()
2444{
2445 sp<AudioCommand> command = new AudioCommand();
2446 command->mCommand = UPDATE_UID_STATES;
2447 ALOGV("AudioCommandThread() adding update UID states");
2448 sendCommand(command);
2449}
2450
Eric Laurentb52c1522014-05-20 11:27:36 -07002451void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
2452{
2453 sp<AudioCommand>command = new AudioCommand();
2454 command->mCommand = UPDATE_AUDIOPATCH_LIST;
2455 ALOGV("AudioCommandThread() adding update audio patch list");
2456 sendCommand(command);
2457}
2458
François Gaffiecfe17322018-11-07 13:41:29 +01002459void AudioPolicyService::AudioCommandThread::changeAudioVolumeGroupCommand(volume_group_t group,
2460 int flags)
2461{
2462 sp<AudioCommand>command = new AudioCommand();
2463 command->mCommand = CHANGED_AUDIOVOLUMEGROUP;
2464 AudioVolumeGroupData *data= new AudioVolumeGroupData();
2465 data->mGroup = group;
2466 data->mFlags = flags;
2467 command->mParam = data;
2468 ALOGV("AudioCommandThread() adding audio volume group changed");
2469 sendCommand(command);
2470}
2471
Eric Laurente1715a42014-05-20 11:30:42 -07002472status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
2473 const struct audio_port_config *config, int delayMs)
2474{
2475 sp<AudioCommand> command = new AudioCommand();
2476 command->mCommand = SET_AUDIOPORT_CONFIG;
2477 SetAudioPortConfigData *data = new SetAudioPortConfigData();
2478 data->mConfig = *config;
2479 command->mParam = data;
2480 command->mWaitStatus = true;
2481 ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
2482 return sendCommand(command, delayMs);
2483}
2484
Jean-Michel Trivide801052015-04-14 19:10:14 -07002485void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002486 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -07002487{
2488 sp<AudioCommand> command = new AudioCommand();
2489 command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
2490 DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
2491 data->mRegId = regId;
2492 data->mState = state;
2493 command->mParam = data;
2494 ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
2495 regId.string(), state);
2496 sendCommand(command);
2497}
2498
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002499void AudioPolicyService::AudioCommandThread::recordingConfigurationUpdateCommand(
Eric Laurenta9f86652018-11-28 17:23:11 -08002500 int event,
2501 const record_client_info_t *clientInfo,
2502 const audio_config_base_t *clientConfig,
2503 std::vector<effect_descriptor_t> clientEffects,
2504 const audio_config_base_t *deviceConfig,
2505 std::vector<effect_descriptor_t> effects,
2506 audio_patch_handle_t patchHandle,
2507 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002508{
2509 sp<AudioCommand>command = new AudioCommand();
2510 command->mCommand = RECORDING_CONFIGURATION_UPDATE;
2511 RecordingConfigurationUpdateData *data = new RecordingConfigurationUpdateData();
2512 data->mEvent = event;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002513 data->mClientInfo = *clientInfo;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002514 data->mClientConfig = *clientConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002515 data->mClientEffects = clientEffects;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002516 data->mDeviceConfig = *deviceConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002517 data->mEffects = effects;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002518 data->mPatchHandle = patchHandle;
Eric Laurenta9f86652018-11-28 17:23:11 -08002519 data->mSource = source;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002520 command->mParam = data;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002521 ALOGV("AudioCommandThread() adding recording configuration update event %d, source %d uid %u",
2522 event, clientInfo->source, clientInfo->uid);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002523 sendCommand(command);
2524}
2525
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002526void AudioPolicyService::AudioCommandThread::audioModulesUpdateCommand()
2527{
2528 sp<AudioCommand> command = new AudioCommand();
2529 command->mCommand = AUDIO_MODULES_UPDATE;
2530 sendCommand(command);
2531}
2532
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002533void AudioPolicyService::AudioCommandThread::routingChangedCommand()
2534{
2535 sp<AudioCommand>command = new AudioCommand();
2536 command->mCommand = ROUTING_UPDATED;
2537 ALOGV("AudioCommandThread() adding routing update");
2538 sendCommand(command);
2539}
2540
Eric Laurent81dd0f52021-07-05 11:54:40 +02002541void AudioPolicyService::AudioCommandThread::checkSpatializerCommand()
2542{
2543 sp<AudioCommand>command = new AudioCommand();
Eric Laurent15903592022-02-24 20:44:36 +01002544 command->mCommand = CHECK_SPATIALIZER_OUTPUT;
Eric Laurent81dd0f52021-07-05 11:54:40 +02002545 ALOGV("AudioCommandThread() adding check spatializer");
2546 sendCommand(command);
2547}
2548
Eric Laurent15903592022-02-24 20:44:36 +01002549void AudioPolicyService::AudioCommandThread::updateActiveSpatializerTracksCommand()
2550{
2551 sp<AudioCommand>command = new AudioCommand();
2552 command->mCommand = UPDATE_ACTIVE_SPATIALIZER_TRACKS;
2553 ALOGV("AudioCommandThread() adding update active spatializer tracks");
2554 sendCommand(command);
2555}
2556
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002557void AudioPolicyService::AudioCommandThread::volRangeInitReqCommand()
2558{
2559 sp<AudioCommand>command = new AudioCommand();
2560 command->mCommand = VOL_RANGE_INIT_REQUEST;
2561 ALOGV("AudioCommandThread() adding volume range init request");
2562 sendCommand(command);
2563}
2564
Eric Laurent0ede8922014-05-09 18:04:42 -07002565status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
2566{
2567 {
2568 Mutex::Autolock _l(mLock);
2569 insertCommand_l(command, delayMs);
2570 mWaitWorkCV.signal();
2571 }
2572 Mutex::Autolock _l(command->mLock);
2573 while (command->mWaitStatus) {
2574 nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
2575 if (command->mCond.waitRelative(command->mLock, timeOutNs) != NO_ERROR) {
2576 command->mStatus = TIMED_OUT;
2577 command->mWaitStatus = false;
2578 }
2579 }
2580 return command->mStatus;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002581}
2582
Mathias Agopian65ab4712010-07-14 17:59:35 -07002583// insertCommand_l() must be called with mLock held
Eric Laurent0ede8922014-05-09 18:04:42 -07002584void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002585{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002586 ssize_t i; // not size_t because i will count down to -1
Eric Laurent0ede8922014-05-09 18:04:42 -07002587 Vector < sp<AudioCommand> > removedCommands;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002588 command->mTime = systemTime() + milliseconds(delayMs);
2589
2590 // acquire wake lock to make sure delayed commands are processed
Eric Laurentbfb1b832013-01-07 09:53:42 -08002591 if (mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002592 acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.string());
2593 }
2594
2595 // check same pending commands with later time stamps and eliminate them
Ivan Lozano5ff158f2017-10-30 09:06:24 -07002596 for (i = (ssize_t)mAudioCommands.size()-1; i >= 0; i--) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002597 sp<AudioCommand> command2 = mAudioCommands[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07002598 // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
2599 if (command2->mTime <= command->mTime) break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002600
2601 // create audio patch or release audio patch commands are equivalent
2602 // with regard to filtering
2603 if ((command->mCommand == CREATE_AUDIO_PATCH) ||
2604 (command->mCommand == RELEASE_AUDIO_PATCH)) {
2605 if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
2606 (command2->mCommand != RELEASE_AUDIO_PATCH)) {
2607 continue;
2608 }
2609 } else if (command2->mCommand != command->mCommand) continue;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002610
2611 switch (command->mCommand) {
2612 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002613 ParametersData *data = (ParametersData *)command->mParam.get();
2614 ParametersData *data2 = (ParametersData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002615 if (data->mIO != data2->mIO) break;
Steve Block3856b092011-10-20 11:56:00 +01002616 ALOGV("Comparing parameter command %s to new command %s",
Eric Laurentde070132010-07-13 04:45:46 -07002617 data2->mKeyValuePairs.string(), data->mKeyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002618 AudioParameter param = AudioParameter(data->mKeyValuePairs);
2619 AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
2620 for (size_t j = 0; j < param.size(); j++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002621 String8 key;
2622 String8 value;
2623 param.getAt(j, key, value);
2624 for (size_t k = 0; k < param2.size(); k++) {
2625 String8 key2;
2626 String8 value2;
2627 param2.getAt(k, key2, value2);
2628 if (key2 == key) {
2629 param2.remove(key2);
2630 ALOGV("Filtering out parameter %s", key2.string());
2631 break;
2632 }
2633 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002634 }
2635 // if all keys have been filtered out, remove the command.
2636 // otherwise, update the key value pairs
2637 if (param2.size() == 0) {
2638 removedCommands.add(command2);
2639 } else {
2640 data2->mKeyValuePairs = param2.toString();
2641 }
Eric Laurent21e54562013-09-23 12:08:05 -07002642 command->mTime = command2->mTime;
2643 // force delayMs to non 0 so that code below does not request to wait for
2644 // command status as the command is now delayed
2645 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002646 } break;
2647
2648 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002649 VolumeData *data = (VolumeData *)command->mParam.get();
2650 VolumeData *data2 = (VolumeData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002651 if (data->mIO != data2->mIO) break;
2652 if (data->mStream != data2->mStream) break;
Steve Block3856b092011-10-20 11:56:00 +01002653 ALOGV("Filtering out volume command on output %d for stream %d",
Eric Laurentde070132010-07-13 04:45:46 -07002654 data->mIO, data->mStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002655 removedCommands.add(command2);
Eric Laurent21e54562013-09-23 12:08:05 -07002656 command->mTime = command2->mTime;
2657 // force delayMs to non 0 so that code below does not request to wait for
2658 // command status as the command is now delayed
2659 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002660 } break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002661
Eric Laurentbaf35fe2016-07-27 15:36:53 -07002662 case SET_VOICE_VOLUME: {
2663 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
2664 VoiceVolumeData *data2 = (VoiceVolumeData *)command2->mParam.get();
2665 ALOGV("Filtering out voice volume command value %f replaced by %f",
2666 data2->mVolume, data->mVolume);
2667 removedCommands.add(command2);
2668 command->mTime = command2->mTime;
2669 // force delayMs to non 0 so that code below does not request to wait for
2670 // command status as the command is now delayed
2671 delayMs = 1;
2672 } break;
2673
Eric Laurente45b48a2014-09-04 16:40:57 -07002674 case CREATE_AUDIO_PATCH:
2675 case RELEASE_AUDIO_PATCH: {
2676 audio_patch_handle_t handle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002677 struct audio_patch patch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002678 if (command->mCommand == CREATE_AUDIO_PATCH) {
2679 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002680 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002681 } else {
2682 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
Mikhail Naganov7be71d22018-05-23 16:51:46 -07002683 memset(&patch, 0, sizeof(patch));
Eric Laurente45b48a2014-09-04 16:40:57 -07002684 }
2685 audio_patch_handle_t handle2;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002686 struct audio_patch patch2;
Eric Laurente45b48a2014-09-04 16:40:57 -07002687 if (command2->mCommand == CREATE_AUDIO_PATCH) {
2688 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002689 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002690 } else {
2691 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
Glenn Kastenf60b6b62015-07-06 10:53:26 -07002692 memset(&patch2, 0, sizeof(patch2));
Eric Laurente45b48a2014-09-04 16:40:57 -07002693 }
2694 if (handle != handle2) break;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002695 /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
2696 same output. */
2697 if( (command->mCommand == CREATE_AUDIO_PATCH) &&
2698 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
2699 bool isOutputDiff = false;
2700 if (patch.num_sources == patch2.num_sources) {
2701 for (unsigned count = 0; count < patch.num_sources; count++) {
2702 if (patch.sources[count].id != patch2.sources[count].id) {
2703 isOutputDiff = true;
2704 break;
2705 }
2706 }
2707 if (isOutputDiff)
2708 break;
2709 }
2710 }
Eric Laurente45b48a2014-09-04 16:40:57 -07002711 ALOGV("Filtering out %s audio patch command for handle %d",
2712 (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
2713 removedCommands.add(command2);
2714 command->mTime = command2->mTime;
2715 // force delayMs to non 0 so that code below does not request to wait for
2716 // command status as the command is now delayed
2717 delayMs = 1;
2718 } break;
2719
Jean-Michel Trivide801052015-04-14 19:10:14 -07002720 case DYN_POLICY_MIX_STATE_UPDATE: {
2721
2722 } break;
2723
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002724 case RECORDING_CONFIGURATION_UPDATE: {
2725
2726 } break;
2727
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002728 case ROUTING_UPDATED: {
2729
2730 } break;
2731
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002732 case VOL_RANGE_INIT_REQUEST: {
2733 // command may come from different requests, do not filter
2734 } break;
2735
Mathias Agopian65ab4712010-07-14 17:59:35 -07002736 default:
2737 break;
2738 }
2739 }
2740
2741 // remove filtered commands
2742 for (size_t j = 0; j < removedCommands.size(); j++) {
2743 // removed commands always have time stamps greater than current command
2744 for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002745 if (mAudioCommands[k].get() == removedCommands[j].get()) {
Steve Block3856b092011-10-20 11:56:00 +01002746 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002747 mAudioCommands.removeAt(k);
2748 break;
2749 }
2750 }
2751 }
2752 removedCommands.clear();
2753
Eric Laurentaa79bef2015-01-15 14:33:51 -08002754 // Disable wait for status if delay is not 0.
2755 // Except for create audio patch command because the returned patch handle
2756 // is needed by audio policy manager
2757 if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
Eric Laurentcec4abb2012-07-03 12:23:02 -07002758 command->mWaitStatus = false;
2759 }
Eric Laurentcec4abb2012-07-03 12:23:02 -07002760
Mathias Agopian65ab4712010-07-14 17:59:35 -07002761 // insert command at the right place according to its time stamp
Eric Laurent1e693b52014-07-09 15:03:28 -07002762 ALOGV("inserting command: %d at index %zd, num commands %zu",
2763 command->mCommand, i+1, mAudioCommands.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002764 mAudioCommands.insertAt(command, i + 1);
2765}
2766
2767void AudioPolicyService::AudioCommandThread::exit()
2768{
Steve Block3856b092011-10-20 11:56:00 +01002769 ALOGV("AudioCommandThread::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002770 {
2771 AutoMutex _l(mLock);
2772 requestExit();
2773 mWaitWorkCV.signal();
2774 }
Zach Janga754b4f2015-10-27 01:29:34 +00002775 // Note that we can call it from the thread loop if all other references have been released
2776 // but it will safely return WOULD_BLOCK in this case
Mathias Agopian65ab4712010-07-14 17:59:35 -07002777 requestExitAndWait();
2778}
2779
2780void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
2781{
2782 snprintf(buffer, size, " %02d %06d.%03d %01u %p\n",
2783 mCommand,
2784 (int)ns2s(mTime),
2785 (int)ns2ms(mTime)%1000,
2786 mWaitStatus,
Eric Laurent0ede8922014-05-09 18:04:42 -07002787 mParam.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002788}
2789
Dima Zavinfce7a472011-04-19 22:30:36 -07002790/******* helpers for the service_ops callbacks defined below *********/
2791void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
2792 const char *keyValuePairs,
2793 int delayMs)
2794{
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002795 mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
Dima Zavinfce7a472011-04-19 22:30:36 -07002796 delayMs);
2797}
2798
2799int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
2800 float volume,
2801 audio_io_handle_t output,
2802 int delayMs)
2803{
Glenn Kastenfff6d712012-01-12 16:38:12 -08002804 return (int)mAudioCommandThread->volumeCommand(stream, volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002805 output, delayMs);
Dima Zavinfce7a472011-04-19 22:30:36 -07002806}
2807
Dima Zavinfce7a472011-04-19 22:30:36 -07002808int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
2809{
2810 return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
2811}
2812
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002813void AudioPolicyService::setEffectSuspended(int effectId,
2814 audio_session_t sessionId,
2815 bool suspended)
2816{
2817 mAudioCommandThread->setEffectSuspendedCommand(effectId, sessionId, suspended);
2818}
2819
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002820Status AudioPolicyService::onNewAudioModulesAvailable()
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002821{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07002822 mOutputCommandThread->audioModulesUpdateCommand();
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002823 return Status::ok();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002824}
2825
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002826
Dima Zavinfce7a472011-04-19 22:30:36 -07002827extern "C" {
Eric Laurent2d388ec2014-03-07 13:25:54 -08002828audio_module_handle_t aps_load_hw_module(void *service __unused,
2829 const char *name);
2830audio_io_handle_t aps_open_output(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002831 audio_devices_t *pDevices,
2832 uint32_t *pSamplingRate,
2833 audio_format_t *pFormat,
2834 audio_channel_mask_t *pChannelMask,
2835 uint32_t *pLatencyMs,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002836 audio_output_flags_t flags);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002837
Eric Laurent2d388ec2014-03-07 13:25:54 -08002838audio_io_handle_t aps_open_output_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002839 audio_module_handle_t module,
2840 audio_devices_t *pDevices,
2841 uint32_t *pSamplingRate,
2842 audio_format_t *pFormat,
2843 audio_channel_mask_t *pChannelMask,
2844 uint32_t *pLatencyMs,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002845 audio_output_flags_t flags,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002846 const audio_offload_info_t *offloadInfo);
2847audio_io_handle_t aps_open_dup_output(void *service __unused,
Dima Zavinfce7a472011-04-19 22:30:36 -07002848 audio_io_handle_t output1,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002849 audio_io_handle_t output2);
2850int aps_close_output(void *service __unused, audio_io_handle_t output);
2851int aps_suspend_output(void *service __unused, audio_io_handle_t output);
2852int aps_restore_output(void *service __unused, audio_io_handle_t output);
2853audio_io_handle_t aps_open_input(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002854 audio_devices_t *pDevices,
2855 uint32_t *pSamplingRate,
2856 audio_format_t *pFormat,
2857 audio_channel_mask_t *pChannelMask,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002858 audio_in_acoustics_t acoustics __unused);
2859audio_io_handle_t aps_open_input_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002860 audio_module_handle_t module,
2861 audio_devices_t *pDevices,
2862 uint32_t *pSamplingRate,
2863 audio_format_t *pFormat,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002864 audio_channel_mask_t *pChannelMask);
2865int aps_close_input(void *service __unused, audio_io_handle_t input);
2866int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
Glenn Kastend848eb42016-03-08 13:42:11 -08002867int aps_move_effects(void *service __unused, audio_session_t session,
Dima Zavinfce7a472011-04-19 22:30:36 -07002868 audio_io_handle_t src_output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002869 audio_io_handle_t dst_output);
2870char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
2871 const char *keys);
2872void aps_set_parameters(void *service, audio_io_handle_t io_handle,
2873 const char *kv_pairs, int delay_ms);
2874int aps_set_stream_volume(void *service, audio_stream_type_t stream,
Dima Zavinfce7a472011-04-19 22:30:36 -07002875 float volume, audio_io_handle_t output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002876 int delay_ms);
Eric Laurent2d388ec2014-03-07 13:25:54 -08002877int aps_set_voice_volume(void *service, float volume, int delay_ms);
2878};
Dima Zavinfce7a472011-04-19 22:30:36 -07002879
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08002880} // namespace android