blob: 48997db9e567b1e2b4831ea6400cf84f3b502f96 [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) \
140BINDER_METHOD_ENTRY(listAudioProductStrategies) \
141BINDER_METHOD_ENTRY(getProductStrategyFromAudioAttributes) \
142BINDER_METHOD_ENTRY(listAudioVolumeGroups) \
143BINDER_METHOD_ENTRY(getVolumeGroupFromAudioAttributes) \
144BINDER_METHOD_ENTRY(setRttEnabled) \
145BINDER_METHOD_ENTRY(isCallScreenModeSupported) \
146BINDER_METHOD_ENTRY(setDevicesRoleForStrategy) \
147BINDER_METHOD_ENTRY(removeDevicesRoleForStrategy) \
148BINDER_METHOD_ENTRY(getDevicesForRoleAndStrategy) \
149BINDER_METHOD_ENTRY(setDevicesRoleForCapturePreset) \
150BINDER_METHOD_ENTRY(addDevicesRoleForCapturePreset) \
151BINDER_METHOD_ENTRY(removeDevicesRoleForCapturePreset) \
152BINDER_METHOD_ENTRY(clearDevicesRoleForCapturePreset) \
153BINDER_METHOD_ENTRY(getDevicesForRoleAndCapturePreset) \
154BINDER_METHOD_ENTRY(registerSoundTriggerCaptureStateListener) \
155BINDER_METHOD_ENTRY(getSpatializer) \
156BINDER_METHOD_ENTRY(canBeSpatialized) \
157BINDER_METHOD_ENTRY(getDirectPlaybackSupport) \
jiabina84c3d32022-12-02 18:59:55 +0000158BINDER_METHOD_ENTRY(getDirectProfilesForAttributes) \
159BINDER_METHOD_ENTRY(getSupportedMixerAttributes) \
160BINDER_METHOD_ENTRY(setPreferredMixerAttributes) \
161BINDER_METHOD_ENTRY(getPreferredMixerAttributes) \
162BINDER_METHOD_ENTRY(clearPreferredMixerAttributes) \
Andy Hungc747c532022-03-07 21:41:14 -0800163
164// singleton for Binder Method Statistics for IAudioPolicyService
165static auto& getIAudioPolicyServiceStatistics() {
166 using Code = int;
167
168#pragma push_macro("BINDER_METHOD_ENTRY")
169#undef BINDER_METHOD_ENTRY
170#define BINDER_METHOD_ENTRY(ENTRY) \
171 {(Code)media::BnAudioPolicyService::TRANSACTION_##ENTRY, #ENTRY},
172
173 static mediautils::MethodStatistics<Code> methodStatistics{
174 IAUDIOPOLICYSERVICE_BINDER_METHOD_MACRO_LIST
175 METHOD_STATISTICS_BINDER_CODE_NAMES(Code)
176 };
177#pragma pop_macro("BINDER_METHOD_ENTRY")
178
179 return methodStatistics;
180}
181
Mathias Agopian65ab4712010-07-14 17:59:35 -0700182// ----------------------------------------------------------------------------
183
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530184static AudioPolicyInterface* createAudioPolicyManager(AudioPolicyClientInterface *clientInterface)
185{
186 AudioPolicyManager *apm = new AudioPolicyManager(clientInterface);
187 status_t status = apm->initialize();
188 if (status != NO_ERROR) {
189 delete apm;
190 apm = nullptr;
191 }
192 return apm;
193}
194
195static void destroyAudioPolicyManager(AudioPolicyInterface *interface)
196{
197 delete interface;
198}
199// ----------------------------------------------------------------------------
200
Mathias Agopian65ab4712010-07-14 17:59:35 -0700201AudioPolicyService::AudioPolicyService()
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -0700202 : BnAudioPolicyService(),
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -0700203 mAudioPolicyManager(NULL),
204 mAudioPolicyClient(NULL),
205 mPhoneState(AUDIO_MODE_INVALID),
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530206 mCaptureStateNotifier(false),
207 mCreateAudioPolicyManager(createAudioPolicyManager),
208 mDestroyAudioPolicyManager(destroyAudioPolicyManager) {
Andy Hung225aef62022-12-06 16:33:20 -0800209 setMinSchedulerPolicy(SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530210}
211
212void AudioPolicyService::loadAudioPolicyManager()
213{
214 mLibraryHandle = dlopen(kAudioPolicyManagerCustomPath, RTLD_NOW);
215 if (mLibraryHandle != nullptr) {
216 ALOGI("%s loading %s", __func__, kAudioPolicyManagerCustomPath);
217 mCreateAudioPolicyManager = reinterpret_cast<CreateAudioPolicyManagerInstance>
218 (dlsym(mLibraryHandle, "createAudioPolicyManager"));
219 const char *lastError = dlerror();
220 ALOGW_IF(mCreateAudioPolicyManager == nullptr, "%s createAudioPolicyManager is null %s",
221 __func__, lastError != nullptr ? lastError : "no error");
222
223 mDestroyAudioPolicyManager = reinterpret_cast<DestroyAudioPolicyManagerInstance>(
224 dlsym(mLibraryHandle, "destroyAudioPolicyManager"));
225 lastError = dlerror();
226 ALOGW_IF(mDestroyAudioPolicyManager == nullptr, "%s destroyAudioPolicyManager is null %s",
227 __func__, lastError != nullptr ? lastError : "no error");
228 if (mCreateAudioPolicyManager == nullptr || mDestroyAudioPolicyManager == nullptr){
229 unloadAudioPolicyManager();
230 LOG_ALWAYS_FATAL("could not find audiopolicymanager interface methods");
231 }
232 }
Eric Laurentf5ada6e2014-10-09 17:49:00 -0700233}
234
235void AudioPolicyService::onFirstRef()
236{
Andy Hungd47aca22022-03-15 11:50:51 -0700237 // Log an AudioPolicy "constructor" mediametrics event on first ref.
238 // This records the time it takes to load the audio modules and devices.
239 mediametrics::Defer defer([beginNs = systemTime()] {
240 mediametrics::LogItem(AMEDIAMETRICS_KEY_AUDIO_POLICY)
241 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CTOR)
242 .set(AMEDIAMETRICS_PROP_EXECUTIONTIMENS, (int64_t)(systemTime() - beginNs))
243 .record(); });
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700244 {
245 Mutex::Autolock _l(mLock);
Eric Laurent93575202011-01-18 18:39:02 -0800246
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700247 // start audio commands thread
248 mAudioCommandThread = new AudioCommandThread(String8("ApmAudio"), this);
249 // start output activity command thread
250 mOutputCommandThread = new AudioCommandThread(String8("ApmOutput"), this);
Eric Laurentdce54a12014-03-10 12:19:46 -0700251
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700252 mAudioPolicyClient = new AudioPolicyClient(this);
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530253
254 loadAudioPolicyManager();
255 mAudioPolicyManager = mCreateAudioPolicyManager(mAudioPolicyClient);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700256 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200257
bryant_liuba2b4392014-06-11 16:49:30 +0800258 // load audio processing modules
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000259 sp<AudioPolicyEffects> audioPolicyEffects = new AudioPolicyEffects();
260 sp<UidPolicy> uidPolicy = new UidPolicy(this);
261 sp<SensorPrivacyPolicy> sensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700262 {
263 Mutex::Autolock _l(mLock);
264 mAudioPolicyEffects = audioPolicyEffects;
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000265 mUidPolicy = uidPolicy;
266 mSensorPrivacyPolicy = sensorPrivacyPolicy;
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700267 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000268 uidPolicy->registerSelf();
269 sensorPrivacyPolicy->registerSelf();
Eric Laurentd66d7a12021-07-13 13:35:32 +0200270
Eric Laurent81dd0f52021-07-05 11:54:40 +0200271 // Create spatializer if supported
Eric Laurent52b0bd52021-09-27 15:25:40 +0200272 if (mAudioPolicyManager != nullptr) {
273 Mutex::Autolock _l(mLock);
274 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
275 AudioDeviceTypeAddrVector devices;
276 bool hasSpatializer = mAudioPolicyManager->canBeSpatialized(&attr, nullptr, devices);
277 if (hasSpatializer) {
278 mSpatializer = Spatializer::create(this);
279 }
Andy Hung8aa43c02022-09-13 18:53:06 -0700280 if (mSpatializer == nullptr) {
281 // No spatializer created, signal the reason: NO_INIT a failure, OK means intended.
282 const status_t createStatus = hasSpatializer ? NO_INIT : OK;
283 Spatializer::sendEmptyCreateSpatializerMetricWithStatus(createStatus);
284 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200285 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200286 AudioSystem::audioPolicyReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700287}
288
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530289void AudioPolicyService::unloadAudioPolicyManager()
290{
291 ALOGV("%s ", __func__);
292 if (mLibraryHandle != nullptr) {
293 dlclose(mLibraryHandle);
294 }
295 mLibraryHandle = nullptr;
296 mCreateAudioPolicyManager = nullptr;
297 mDestroyAudioPolicyManager = nullptr;
298}
299
Mathias Agopian65ab4712010-07-14 17:59:35 -0700300AudioPolicyService::~AudioPolicyService()
301{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700302 mAudioCommandThread->exit();
Eric Laurent657ff612014-05-07 11:58:24 -0700303 mOutputCommandThread->exit();
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700304
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530305 mDestroyAudioPolicyManager(mAudioPolicyManager);
306 unloadAudioPolicyManager();
307
Eric Laurentdce54a12014-03-10 12:19:46 -0700308 delete mAudioPolicyClient;
Eric Laurentb52c1522014-05-20 11:27:36 -0700309
310 mNotificationClients.clear();
bryant_liuba2b4392014-06-11 16:49:30 +0800311 mAudioPolicyEffects.clear();
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800312
313 mUidPolicy->unregisterSelf();
Michael Groovercfd28302018-12-11 19:16:46 -0800314 mSensorPrivacyPolicy->unregisterSelf();
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000315
316 mUidPolicy.clear();
Michael Groovercfd28302018-12-11 19:16:46 -0800317 mSensorPrivacyPolicy.clear();
Eric Laurentb52c1522014-05-20 11:27:36 -0700318}
319
320// A notification client is always registered by AudioSystem when the client process
321// connects to AudioPolicyService.
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800322Status AudioPolicyService::registerClient(const sp<media::IAudioPolicyServiceClient>& client)
Eric Laurentb52c1522014-05-20 11:27:36 -0700323{
Eric Laurent12590252015-08-21 18:40:20 -0700324 if (client == 0) {
325 ALOGW("%s got NULL client", __FUNCTION__);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800326 return Status::ok();
Eric Laurent12590252015-08-21 18:40:20 -0700327 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800328 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700329
330 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800331 pid_t pid = IPCThreadState::self()->getCallingPid();
332 int64_t token = ((int64_t)uid<<32) | pid;
333
334 if (mNotificationClients.indexOfKey(token) < 0) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700335 sp<NotificationClient> notificationClient = new NotificationClient(this,
336 client,
luochaojiang908c7d72018-06-21 14:58:04 +0800337 uid,
338 pid);
339 ALOGV("registerClient() client %p, uid %d pid %d", client.get(), uid, pid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700340
luochaojiang908c7d72018-06-21 14:58:04 +0800341 mNotificationClients.add(token, notificationClient);
Eric Laurentb52c1522014-05-20 11:27:36 -0700342
Marco Nelissenf8880202014-11-14 07:58:25 -0800343 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurentb52c1522014-05-20 11:27:36 -0700344 binder->linkToDeath(notificationClient);
345 }
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800346 return Status::ok();
Eric Laurentb52c1522014-05-20 11:27:36 -0700347}
348
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800349Status AudioPolicyService::setAudioPortCallbacksEnabled(bool enabled)
Eric Laurente8726fe2015-06-26 09:39:24 -0700350{
351 Mutex::Autolock _l(mNotificationClientsLock);
352
353 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800354 pid_t pid = IPCThreadState::self()->getCallingPid();
355 int64_t token = ((int64_t)uid<<32) | pid;
356
357 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800358 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700359 }
luochaojiang908c7d72018-06-21 14:58:04 +0800360 mNotificationClients.valueFor(token)->setAudioPortCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800361 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700362}
363
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800364Status AudioPolicyService::setAudioVolumeGroupCallbacksEnabled(bool enabled)
François Gaffiecfe17322018-11-07 13:41:29 +0100365{
366 Mutex::Autolock _l(mNotificationClientsLock);
367
368 uid_t uid = IPCThreadState::self()->getCallingUid();
369 pid_t pid = IPCThreadState::self()->getCallingPid();
370 int64_t token = ((int64_t)uid<<32) | pid;
371
372 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800373 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100374 }
375 mNotificationClients.valueFor(token)->setAudioVolumeGroupCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800376 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100377}
378
Eric Laurentb52c1522014-05-20 11:27:36 -0700379// removeNotificationClient() is called when the client process dies.
luochaojiang908c7d72018-06-21 14:58:04 +0800380void AudioPolicyService::removeNotificationClient(uid_t uid, pid_t pid)
Eric Laurentb52c1522014-05-20 11:27:36 -0700381{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000382 bool hasSameUid = false;
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800383 {
384 Mutex::Autolock _l(mNotificationClientsLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800385 int64_t token = ((int64_t)uid<<32) | pid;
386 mNotificationClients.removeItem(token);
luochaojiang908c7d72018-06-21 14:58:04 +0800387 for (size_t i = 0; i < mNotificationClients.size(); i++) {
388 if (mNotificationClients.valueAt(i)->uid() == uid) {
389 hasSameUid = true;
390 break;
391 }
392 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000393 }
394 {
395 Mutex::Autolock _l(mLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800396 if (mAudioPolicyManager && !hasSameUid) {
Eric Laurent10b71232018-04-13 18:14:44 -0700397 // called from binder death notification: no need to clear caller identity
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700398 mAudioPolicyManager->releaseResourcesForUid(uid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700399 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800400 }
Eric Laurentb52c1522014-05-20 11:27:36 -0700401}
402
403void AudioPolicyService::onAudioPortListUpdate()
404{
405 mOutputCommandThread->updateAudioPortListCommand();
406}
407
408void AudioPolicyService::doOnAudioPortListUpdate()
409{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800410 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700411 for (size_t i = 0; i < mNotificationClients.size(); i++) {
412 mNotificationClients.valueAt(i)->onAudioPortListUpdate();
413 }
414}
415
416void AudioPolicyService::onAudioPatchListUpdate()
417{
418 mOutputCommandThread->updateAudioPatchListCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700419}
420
Eric Laurentb52c1522014-05-20 11:27:36 -0700421void AudioPolicyService::doOnAudioPatchListUpdate()
422{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800423 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700424 for (size_t i = 0; i < mNotificationClients.size(); i++) {
425 mNotificationClients.valueAt(i)->onAudioPatchListUpdate();
426 }
427}
428
François Gaffiecfe17322018-11-07 13:41:29 +0100429void AudioPolicyService::onAudioVolumeGroupChanged(volume_group_t group, int flags)
430{
431 mOutputCommandThread->changeAudioVolumeGroupCommand(group, flags);
432}
433
434void AudioPolicyService::doOnAudioVolumeGroupChanged(volume_group_t group, int flags)
435{
436 Mutex::Autolock _l(mNotificationClientsLock);
437 for (size_t i = 0; i < mNotificationClients.size(); i++) {
438 mNotificationClients.valueAt(i)->onAudioVolumeGroupChanged(group, flags);
439 }
440}
441
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700442void AudioPolicyService::onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700443{
444 ALOGV("AudioPolicyService::onDynamicPolicyMixStateUpdate(%s, %d)",
445 regId.string(), state);
446 mOutputCommandThread->dynamicPolicyMixStateUpdateCommand(regId, state);
447}
448
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700449void AudioPolicyService::doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700450{
451 Mutex::Autolock _l(mNotificationClientsLock);
452 for (size_t i = 0; i < mNotificationClients.size(); i++) {
453 mNotificationClients.valueAt(i)->onDynamicPolicyMixStateUpdate(regId, state);
454 }
455}
456
Eric Laurenta9f86652018-11-28 17:23:11 -0800457void AudioPolicyService::onRecordingConfigurationUpdate(
458 int event,
459 const record_client_info_t *clientInfo,
460 const audio_config_base_t *clientConfig,
461 std::vector<effect_descriptor_t> clientEffects,
462 const audio_config_base_t *deviceConfig,
463 std::vector<effect_descriptor_t> effects,
464 audio_patch_handle_t patchHandle,
465 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800466{
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800467 mOutputCommandThread->recordingConfigurationUpdateCommand(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800468 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800469}
470
Eric Laurenta9f86652018-11-28 17:23:11 -0800471void AudioPolicyService::doOnRecordingConfigurationUpdate(
472 int event,
473 const record_client_info_t *clientInfo,
474 const audio_config_base_t *clientConfig,
475 std::vector<effect_descriptor_t> clientEffects,
476 const audio_config_base_t *deviceConfig,
477 std::vector<effect_descriptor_t> effects,
478 audio_patch_handle_t patchHandle,
479 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800480{
481 Mutex::Autolock _l(mNotificationClientsLock);
482 for (size_t i = 0; i < mNotificationClients.size(); i++) {
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800483 mNotificationClients.valueAt(i)->onRecordingConfigurationUpdate(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800484 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800485 }
486}
487
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700488void AudioPolicyService::onRoutingUpdated()
489{
490 mOutputCommandThread->routingChangedCommand();
491}
492
493void AudioPolicyService::doOnRoutingUpdated()
494{
495 Mutex::Autolock _l(mNotificationClientsLock);
496 for (size_t i = 0; i < mNotificationClients.size(); i++) {
497 mNotificationClients.valueAt(i)->onRoutingUpdated();
498 }
499}
500
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000501void AudioPolicyService::onVolumeRangeInitRequest()
502{
503 mOutputCommandThread->volRangeInitReqCommand();
504}
505
506void AudioPolicyService::doOnVolumeRangeInitRequest()
507{
508 Mutex::Autolock _l(mNotificationClientsLock);
509 for (size_t i = 0; i < mNotificationClients.size(); i++) {
510 mNotificationClients.valueAt(i)->onVolumeRangeInitRequest();
511 }
512}
513
Eric Laurent81dd0f52021-07-05 11:54:40 +0200514void AudioPolicyService::onCheckSpatializer()
515{
516 Mutex::Autolock _l(mLock);
Eric Laurent39095982021-08-24 18:29:27 +0200517 onCheckSpatializer_l();
518}
519
520void AudioPolicyService::onCheckSpatializer_l()
521{
522 if (mSpatializer != nullptr) {
523 mOutputCommandThread->checkSpatializerCommand();
524 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200525}
526
527void AudioPolicyService::doOnCheckSpatializer()
528{
Eric Laurentd6bee3a2022-08-31 16:07:50 +0200529 ALOGV("%s mSpatializer %p level %d",
530 __func__, mSpatializer.get(), (int)mSpatializer->getLevel());
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200531
Eric Laurent39095982021-08-24 18:29:27 +0200532 if (mSpatializer != nullptr) {
Eric Laurent52b0bd52021-09-27 15:25:40 +0200533 // Note: mSpatializer != nullptr => mAudioPolicyManager != nullptr
Eric Laurent39095982021-08-24 18:29:27 +0200534 if (mSpatializer->getLevel() != media::SpatializationLevel::NONE) {
535 audio_io_handle_t currentOutput = mSpatializer->getOutput();
536 audio_io_handle_t newOutput;
537 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
538 audio_config_base_t config = mSpatializer->getAudioInConfig();
Eric Laurent21270b62022-07-04 15:11:29 +0200539
540 Mutex::Autolock _l(mLock);
Eric Laurent39095982021-08-24 18:29:27 +0200541 status_t status =
542 mAudioPolicyManager->getSpatializerOutput(&config, &attr, &newOutput);
Eric Laurentb4f42a92022-01-17 17:37:31 +0100543 ALOGV("%s currentOutput %d newOutput %d channel_mask %#x",
544 __func__, currentOutput, newOutput, config.channel_mask);
Eric Laurent39095982021-08-24 18:29:27 +0200545 if (status == NO_ERROR && currentOutput == newOutput) {
546 return;
547 }
Eric Laurent15903592022-02-24 20:44:36 +0100548 size_t numActiveTracks = countActiveClientsOnOutput_l(newOutput);
Eric Laurent39095982021-08-24 18:29:27 +0200549 mLock.unlock();
550 // It is OK to call detachOutput() is none is already attached.
551 mSpatializer->detachOutput();
Eric Laurent21270b62022-07-04 15:11:29 +0200552 if (status == NO_ERROR && newOutput != AUDIO_IO_HANDLE_NONE) {
553 status = mSpatializer->attachOutput(newOutput, numActiveTracks);
Eric Laurent39095982021-08-24 18:29:27 +0200554 }
Eric Laurent39095982021-08-24 18:29:27 +0200555 mLock.lock();
556 if (status != NO_ERROR) {
557 mAudioPolicyManager->releaseSpatializerOutput(newOutput);
558 }
559 } else if (mSpatializer->getLevel() == media::SpatializationLevel::NONE
560 && mSpatializer->getOutput() != AUDIO_IO_HANDLE_NONE) {
Eric Laurent39095982021-08-24 18:29:27 +0200561 audio_io_handle_t output = mSpatializer->detachOutput();
Eric Laurent21270b62022-07-04 15:11:29 +0200562
Eric Laurent39095982021-08-24 18:29:27 +0200563 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurent21270b62022-07-04 15:11:29 +0200564 Mutex::Autolock _l(mLock);
Eric Laurent39095982021-08-24 18:29:27 +0200565 mAudioPolicyManager->releaseSpatializerOutput(output);
Eric Laurent81dd0f52021-07-05 11:54:40 +0200566 }
567 }
568 }
569}
570
Eric Laurent11094172022-04-05 18:27:42 +0200571size_t AudioPolicyService::countActiveClientsOnOutput_l(
572 audio_io_handle_t output, bool spatializedOnly) {
Eric Laurent15903592022-02-24 20:44:36 +0100573 size_t count = 0;
574 for (size_t i = 0; i < mAudioPlaybackClients.size(); i++) {
575 auto client = mAudioPlaybackClients.valueAt(i);
Eric Laurent11094172022-04-05 18:27:42 +0200576 if (client->io == output && client->active
577 && (!spatializedOnly || client->isSpatialized)) {
Eric Laurent15903592022-02-24 20:44:36 +0100578 count++;
579 }
580 }
581 return count;
582}
583
584void AudioPolicyService::onUpdateActiveSpatializerTracks_l() {
585 if (mSpatializer == nullptr) {
586 return;
587 }
588 mOutputCommandThread->updateActiveSpatializerTracksCommand();
589}
590
591void AudioPolicyService::doOnUpdateActiveSpatializerTracks()
592{
Eric Laurent21270b62022-07-04 15:11:29 +0200593 if (mSpatializer == nullptr) {
594 return;
595 }
596 audio_io_handle_t output = mSpatializer->getOutput();
Eric Laurent7ea0d1b2022-04-01 14:23:44 +0200597 size_t activeClients;
598 {
599 Mutex::Autolock _l(mLock);
Eric Laurent21270b62022-07-04 15:11:29 +0200600 activeClients = countActiveClientsOnOutput_l(output);
Eric Laurent15903592022-02-24 20:44:36 +0100601 }
Eric Laurent21270b62022-07-04 15:11:29 +0200602 mSpatializer->updateActiveTracks(activeClients);
Eric Laurent15903592022-02-24 20:44:36 +0100603}
604
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800605status_t AudioPolicyService::clientCreateAudioPatch(const struct audio_patch *patch,
606 audio_patch_handle_t *handle,
607 int delayMs)
608{
609 return mAudioCommandThread->createAudioPatchCommand(patch, handle, delayMs);
610}
611
612status_t AudioPolicyService::clientReleaseAudioPatch(audio_patch_handle_t handle,
613 int delayMs)
614{
615 return mAudioCommandThread->releaseAudioPatchCommand(handle, delayMs);
616}
617
Eric Laurente1715a42014-05-20 11:30:42 -0700618status_t AudioPolicyService::clientSetAudioPortConfig(const struct audio_port_config *config,
619 int delayMs)
620{
621 return mAudioCommandThread->setAudioPortConfigCommand(config, delayMs);
622}
623
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800624AudioPolicyService::NotificationClient::NotificationClient(
625 const sp<AudioPolicyService>& service,
626 const sp<media::IAudioPolicyServiceClient>& client,
627 uid_t uid,
628 pid_t pid)
luochaojiang908c7d72018-06-21 14:58:04 +0800629 : mService(service), mUid(uid), mPid(pid), mAudioPolicyServiceClient(client),
François Gaffiecfe17322018-11-07 13:41:29 +0100630 mAudioPortCallbacksEnabled(false), mAudioVolumeGroupCallbacksEnabled(false)
Eric Laurentb52c1522014-05-20 11:27:36 -0700631{
632}
633
634AudioPolicyService::NotificationClient::~NotificationClient()
635{
636}
637
638void AudioPolicyService::NotificationClient::binderDied(const wp<IBinder>& who __unused)
639{
640 sp<NotificationClient> keep(this);
641 sp<AudioPolicyService> service = mService.promote();
642 if (service != 0) {
luochaojiang908c7d72018-06-21 14:58:04 +0800643 service->removeNotificationClient(mUid, mPid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700644 }
645}
646
647void AudioPolicyService::NotificationClient::onAudioPortListUpdate()
648{
Eric Laurente8726fe2015-06-26 09:39:24 -0700649 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700650 mAudioPolicyServiceClient->onAudioPortListUpdate();
651 }
652}
653
654void AudioPolicyService::NotificationClient::onAudioPatchListUpdate()
655{
Eric Laurente8726fe2015-06-26 09:39:24 -0700656 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700657 mAudioPolicyServiceClient->onAudioPatchListUpdate();
658 }
659}
Eric Laurent57dae992011-07-24 13:36:09 -0700660
Pattydd807582021-11-04 21:01:03 +0800661void AudioPolicyService::NotificationClient::onAudioVolumeGroupChanged(volume_group_t group,
François Gaffiecfe17322018-11-07 13:41:29 +0100662 int flags)
663{
664 if (mAudioPolicyServiceClient != 0 && mAudioVolumeGroupCallbacksEnabled) {
665 mAudioPolicyServiceClient->onAudioVolumeGroupChanged(group, flags);
666 }
667}
668
669
Jean-Michel Trivide801052015-04-14 19:10:14 -0700670void AudioPolicyService::NotificationClient::onDynamicPolicyMixStateUpdate(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700671 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700672{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700673 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800674 mAudioPolicyServiceClient->onDynamicPolicyMixStateUpdate(
675 legacy2aidl_String8_string(regId).value(), state);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800676 }
677}
678
679void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate(
Eric Laurenta9f86652018-11-28 17:23:11 -0800680 int event,
681 const record_client_info_t *clientInfo,
682 const audio_config_base_t *clientConfig,
683 std::vector<effect_descriptor_t> clientEffects,
684 const audio_config_base_t *deviceConfig,
685 std::vector<effect_descriptor_t> effects,
686 audio_patch_handle_t patchHandle,
687 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800688{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700689 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800690 status_t status = [&]() -> status_t {
691 int32_t eventAidl = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(event));
692 media::RecordClientInfo clientInfoAidl = VALUE_OR_RETURN_STATUS(
693 legacy2aidl_record_client_info_t_RecordClientInfo(*clientInfo));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700694 AudioConfigBase clientConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700695 legacy2aidl_audio_config_base_t_AudioConfigBase(
696 *clientConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800697 std::vector<media::EffectDescriptor> clientEffectsAidl = VALUE_OR_RETURN_STATUS(
698 convertContainer<std::vector<media::EffectDescriptor>>(
699 clientEffects,
700 legacy2aidl_effect_descriptor_t_EffectDescriptor));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700701 AudioConfigBase deviceConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700702 legacy2aidl_audio_config_base_t_AudioConfigBase(
703 *deviceConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800704 std::vector<media::EffectDescriptor> effectsAidl = VALUE_OR_RETURN_STATUS(
705 convertContainer<std::vector<media::EffectDescriptor>>(
706 effects,
707 legacy2aidl_effect_descriptor_t_EffectDescriptor));
708 int32_t patchHandleAidl = VALUE_OR_RETURN_STATUS(
709 legacy2aidl_audio_patch_handle_t_int32_t(patchHandle));
Mikhail Naganovddceecc2021-09-03 13:58:56 -0700710 media::audio::common::AudioSource sourceAidl = VALUE_OR_RETURN_STATUS(
711 legacy2aidl_audio_source_t_AudioSource(source));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800712 return aidl_utils::statusTFromBinderStatus(
713 mAudioPolicyServiceClient->onRecordingConfigurationUpdate(eventAidl,
714 clientInfoAidl,
715 clientConfigAidl,
716 clientEffectsAidl,
717 deviceConfigAidl,
718 effectsAidl,
719 patchHandleAidl,
720 sourceAidl));
721 }();
722 ALOGW_IF(status != OK, "onRecordingConfigurationUpdate() failed: %d", status);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700723 }
724}
725
Eric Laurente8726fe2015-06-26 09:39:24 -0700726void AudioPolicyService::NotificationClient::setAudioPortCallbacksEnabled(bool enabled)
727{
728 mAudioPortCallbacksEnabled = enabled;
729}
730
François Gaffiecfe17322018-11-07 13:41:29 +0100731void AudioPolicyService::NotificationClient::setAudioVolumeGroupCallbacksEnabled(bool enabled)
732{
733 mAudioVolumeGroupCallbacksEnabled = enabled;
734}
Eric Laurente8726fe2015-06-26 09:39:24 -0700735
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700736void AudioPolicyService::NotificationClient::onRoutingUpdated()
737{
738 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
739 mAudioPolicyServiceClient->onRoutingUpdated();
740 }
741}
742
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +0000743void AudioPolicyService::NotificationClient::onVolumeRangeInitRequest()
744{
745 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
746 mAudioPolicyServiceClient->onVolumeRangeInitRequest();
747 }
748}
749
Mathias Agopian65ab4712010-07-14 17:59:35 -0700750void AudioPolicyService::binderDied(const wp<IBinder>& who) {
Glenn Kasten411e4472012-11-02 10:00:06 -0700751 ALOGW("binderDied() %p, calling pid %d", who.unsafe_get(),
Eric Laurentde070132010-07-13 04:45:46 -0700752 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700753}
754
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000755static bool dumpTryLock(Mutex& mutex) ACQUIRE(mutex) NO_THREAD_SAFETY_ANALYSIS
Mathias Agopian65ab4712010-07-14 17:59:35 -0700756{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000757 return mutex.timedLock(kDumpLockTimeoutNs) == NO_ERROR;
758}
759
760static void dumpReleaseLock(Mutex& mutex, bool locked) RELEASE(mutex) NO_THREAD_SAFETY_ANALYSIS
761{
762 if (locked) mutex.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700763}
764
765status_t AudioPolicyService::dumpInternals(int fd)
766{
767 const size_t SIZE = 256;
768 char buffer[SIZE];
769 String8 result;
770
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000771 snprintf(buffer, SIZE, "Supported System Usages:\n ");
Hayden Gomes524159d2019-12-23 14:41:47 -0800772 result.append(buffer);
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000773 std::stringstream msg;
774 size_t i = 0;
775 for (auto usage : mSupportedSystemUsages) {
776 if (i++ != 0) msg << ", ";
777 if (const char* strUsage = audio_usage_to_string(usage); strUsage) {
778 msg << strUsage;
779 } else {
780 msg << usage << " (unknown)";
781 }
Hayden Gomes524159d2019-12-23 14:41:47 -0800782 }
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000783 if (i == 0) {
784 msg << "None";
785 }
786 msg << std::endl;
787 result.append(msg.str().c_str());
Hayden Gomes524159d2019-12-23 14:41:47 -0800788
Mathias Agopian65ab4712010-07-14 17:59:35 -0700789 write(fd, result.string(), result.size());
Oscar Azucena829d90d2022-01-28 17:17:56 -0800790
791 mUidPolicy->dumpInternals(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700792 return NO_ERROR;
793}
794
Eric Laurente8c8b432018-10-17 10:08:02 -0700795void AudioPolicyService::updateUidStates()
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800796{
Eric Laurente8c8b432018-10-17 10:08:02 -0700797 Mutex::Autolock _l(mLock);
798 updateUidStates_l();
799}
800
801void AudioPolicyService::updateUidStates_l()
802{
Eric Laurent4eb58f12018-12-07 16:41:02 -0800803// Go over all active clients and allow capture (does not force silence) in the
804// following cases:
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800805// The client is in the active assistant list
806// AND is TOP
807// AND an accessibility service is TOP
808// AND source is either VOICE_RECOGNITION OR HOTWORD
809// OR there is no active privacy sensitive capture or call
810// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
811// AND source is VOICE_RECOGNITION OR HOTWORD
812// The client is an assistant AND active assistant is not being used
Evan Severson1f700cd2021-02-10 13:10:37 -0800813// AND an accessibility service is on TOP or a RTT call is active
Eric Laurent589171c2019-07-25 18:04:29 -0700814// AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800815// OR there is no active privacy sensitive capture or call
Evan Severson1f700cd2021-02-10 13:10:37 -0800816// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800817// AND is TOP most recent assistant and uses VOICE_RECOGNITION or HOTWORD
818// OR there is no top recent assistant and source is HOTWORD
Evan Severson1f700cd2021-02-10 13:10:37 -0800819// OR The client is an accessibility service
820// AND Is on TOP
821// AND the source is VOICE_RECOGNITION or HOTWORD
822// OR The assistant is not on TOP
Eric Laurent589171c2019-07-25 18:04:29 -0700823// AND there is no active privacy sensitive capture or call
824// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Evan Severson1f700cd2021-02-10 13:10:37 -0800825// AND is on TOP
826// AND the source is VOICE_RECOGNITION or HOTWORD
827// OR the client source is virtual (remote submix, call audio TX or RX...)
828// OR the client source is HOTWORD
829// AND is on TOP
830// OR all active clients are using HOTWORD source
831// AND no call is active
832// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
833// OR the client is the current InputMethodService
834// AND a RTT call is active AND the source is VOICE_RECOGNITION
835// OR Any client
836// AND The assistant is not on TOP
837// AND is on TOP or latest started
838// AND there is no active privacy sensitive capture or call
839// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4eb58f12018-12-07 16:41:02 -0800840
Eric Laurent4e947da2019-10-17 15:24:06 -0700841
Eric Laurent4eb58f12018-12-07 16:41:02 -0800842 sp<AudioRecordClient> topActive;
843 sp<AudioRecordClient> latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800844 sp<AudioRecordClient> topSensitiveActive;
Eric Laurentb809a752020-06-29 09:53:13 -0700845 sp<AudioRecordClient> latestSensitiveActiveOrComm;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800846 sp<AudioRecordClient> latestActiveAssistant;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700847
Eric Laurenta46bedb2018-12-07 18:01:26 -0800848 nsecs_t topStartNs = 0;
849 nsecs_t latestStartNs = 0;
Eric Laurentc21d5692020-02-25 10:24:36 -0800850 nsecs_t topSensitiveStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800851 nsecs_t latestSensitiveStartNs = 0;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800852 nsecs_t latestAssistantStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800853 bool isA11yOnTop = mUidPolicy->isA11yOnTop();
854 bool isAssistantOnTop = false;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800855 bool useActiveAssistantList = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800856 bool isSensitiveActive = false;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700857 bool isInCall = mPhoneState == AUDIO_MODE_IN_CALL;
Eric Laurentc21d5692020-02-25 10:24:36 -0800858 bool isInCommunication = mPhoneState == AUDIO_MODE_IN_COMMUNICATION;
859 bool rttCallActive = (isInCall || isInCommunication)
Eric Laurent6ede98f2019-06-11 14:50:30 -0700860 && mUidPolicy->isRttEnabled();
Eric Laurent4e947da2019-10-17 15:24:06 -0700861 bool onlyHotwordActive = true;
Eric Laurentb809a752020-06-29 09:53:13 -0700862 bool isPhoneStateOwnerActive = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800863
Michael Groovercfd28302018-12-11 19:16:46 -0800864 // if Sensor Privacy is enabled then all recordings should be silenced.
865 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
866 silenceAllRecordings_l();
867 return;
868 }
869
Eric Laurente8c8b432018-10-17 10:08:02 -0700870 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
871 sp<AudioRecordClient> current = mAudioRecordClients[i];
Svet Ganov33761132021-05-13 22:51:08 +0000872 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
873 current->attributionSource.uid));
Evan Severson1f700cd2021-02-10 13:10:37 -0800874 if (!current->active) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700875 continue;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800876 }
Eric Laurent1ff16a72019-03-14 18:35:04 -0700877
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700878 app_state_t appState = apmStatFromAmState(mUidPolicy->getUidState(currentUid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700879 // clients which app is in IDLE state are not eligible for top active or
880 // latest active
881 if (appState == APP_STATE_IDLE) {
882 continue;
883 }
884
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700885 bool isAccessibility = mUidPolicy->isA11yUid(currentUid);
Eric Laurent14a88632020-07-16 12:28:30 -0700886 // Clients capturing for Accessibility services or virtual sources are not considered
Eric Laurentc21d5692020-02-25 10:24:36 -0800887 // for top or latest active to avoid masking regular clients started before
Eric Laurent14a88632020-07-16 12:28:30 -0700888 if (!isAccessibility && !isVirtualSource(current->attributes.source)) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700889 bool isAssistant = mUidPolicy->isAssistantUid(currentUid);
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800890 bool isActiveAssistant = mUidPolicy->isActiveAssistantUid(currentUid);
Eric Laurentc21d5692020-02-25 10:24:36 -0800891 bool isPrivacySensitive =
892 (current->attributes.flags & AUDIO_FLAG_CAPTURE_PRIVATE) != 0;
Eric Laurentb809a752020-06-29 09:53:13 -0700893
Eric Laurentc21d5692020-02-25 10:24:36 -0800894 if (appState == APP_STATE_TOP) {
895 if (isPrivacySensitive) {
896 if (current->startTimeNs > topSensitiveStartNs) {
897 topSensitiveActive = current;
898 topSensitiveStartNs = current->startTimeNs;
899 }
900 } else {
901 if (current->startTimeNs > topStartNs) {
902 topActive = current;
903 topStartNs = current->startTimeNs;
904 }
905 }
906 if (isAssistant) {
907 isAssistantOnTop = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800908 if (isActiveAssistant) {
909 useActiveAssistantList = true;
910 } else if (!useActiveAssistantList) {
911 if (current->startTimeNs > latestAssistantStartNs) {
912 latestActiveAssistant = current;
913 latestAssistantStartNs = current->startTimeNs;
914 }
915 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800916 }
Eric Laurenta46bedb2018-12-07 18:01:26 -0800917 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800918 // Clients capturing for HOTWORD are not considered
919 // for latest active to avoid masking regular clients started before
920 if (!(current->attributes.source == AUDIO_SOURCE_HOTWORD
921 || ((isA11yOnTop || rttCallActive) && isAssistant))) {
922 if (isPrivacySensitive) {
Eric Laurentb809a752020-06-29 09:53:13 -0700923 // if audio mode is IN_COMMUNICATION, make sure the audio mode owner
924 // is marked latest sensitive active even if another app qualifies.
925 if (current->startTimeNs > latestSensitiveStartNs
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700926 || (isInCommunication && currentUid == mPhoneStateOwnerUid)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700927 if (!isInCommunication || latestSensitiveActiveOrComm == nullptr
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700928 || VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000929 latestSensitiveActiveOrComm->attributionSource.uid))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700930 != mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700931 latestSensitiveActiveOrComm = current;
932 latestSensitiveStartNs = current->startTimeNs;
933 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800934 }
935 isSensitiveActive = true;
936 } else {
937 if (current->startTimeNs > latestStartNs) {
938 latestActive = current;
939 latestStartNs = current->startTimeNs;
940 }
941 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800942 }
943 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700944 if (current->attributes.source != AUDIO_SOURCE_HOTWORD) {
945 onlyHotwordActive = false;
946 }
Eric Laurentb0eff0f2021-11-09 16:05:49 +0100947 if (currentUid == mPhoneStateOwnerUid &&
948 !isVirtualSource(current->attributes.source)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700949 isPhoneStateOwnerActive = true;
950 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800951 }
952
Eric Laurent1ff16a72019-03-14 18:35:04 -0700953 // if no active client with UI on Top, consider latest active as top
954 if (topActive == nullptr) {
955 topActive = latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800956 topStartNs = latestStartNs;
957 }
958 if (topSensitiveActive == nullptr) {
Eric Laurentb809a752020-06-29 09:53:13 -0700959 topSensitiveActive = latestSensitiveActiveOrComm;
Eric Laurentc21d5692020-02-25 10:24:36 -0800960 topSensitiveStartNs = latestSensitiveStartNs;
Eric Laurentb809a752020-06-29 09:53:13 -0700961 } else if (latestSensitiveActiveOrComm != nullptr) {
962 // if audio mode is IN_COMMUNICATION, favor audio mode owner over an app with
963 // foreground UI in case both are capturing with privacy sensitive flag.
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700964 uid_t latestActiveUid = VALUE_OR_FATAL(
Svet Ganov33761132021-05-13 22:51:08 +0000965 aidl2legacy_int32_t_uid_t(latestSensitiveActiveOrComm->attributionSource.uid));
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700966 if (isInCommunication && latestActiveUid == mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700967 topSensitiveActive = latestSensitiveActiveOrComm;
968 topSensitiveStartNs = latestSensitiveStartNs;
969 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800970 }
971
972 // If both privacy sensitive and regular capture are active:
973 // if the regular capture is privileged
974 // allow concurrency
975 // else
976 // favor the privacy sensitive case
977 if (topActive != nullptr && topSensitiveActive != nullptr
Ricardo Correa57a37692020-03-23 17:27:25 -0700978 && !topActive->canCaptureOutput) {
Eric Laurentc21d5692020-02-25 10:24:36 -0800979 topActive = nullptr;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800980 }
981
982 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
983 sp<AudioRecordClient> current = mAudioRecordClients[i];
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700984 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000985 current->attributionSource.uid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700986 if (!current->active) {
987 continue;
988 }
989
Eric Laurent4eb58f12018-12-07 16:41:02 -0800990 audio_source_t source = current->attributes.source;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700991 bool isTopOrLatestActive = topActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +0000992 current->attributionSource.uid == topActive->attributionSource.uid;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700993 bool isTopOrLatestSensitive = topSensitiveActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +0000994 current->attributionSource.uid == topSensitiveActive->attributionSource.uid;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800995 bool isTopOrLatestAssistant = latestActiveAssistant == nullptr ? false :
996 current->attributionSource.uid == latestActiveAssistant->attributionSource.uid;
Eric Laurentc21d5692020-02-25 10:24:36 -0800997
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000998 auto canCaptureIfInCallOrCommunication = [&](const auto &recordClient) REQUIRES(mLock) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700999 uid_t recordUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +00001000 recordClient->attributionSource.uid));
Ricardo Correa57a37692020-03-23 17:27:25 -07001001 bool canCaptureCall = recordClient->canCaptureOutput;
Eric Laurentb809a752020-06-29 09:53:13 -07001002 bool canCaptureCommunication = recordClient->canCaptureOutput
1003 || !isPhoneStateOwnerActive
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001004 || recordUid == mPhoneStateOwnerUid;
Eric Laurentb809a752020-06-29 09:53:13 -07001005 return !(isInCall && !canCaptureCall)
1006 && !(isInCommunication && !canCaptureCommunication);
Eric Laurentc21d5692020-02-25 10:24:36 -08001007 };
Eric Laurent1ff16a72019-03-14 18:35:04 -07001008
1009 // By default allow capture if:
1010 // The assistant is not on TOP
Eric Laurenta171e352019-05-07 13:04:45 -07001011 // AND is on TOP or latest started
Eric Laurent1ff16a72019-03-14 18:35:04 -07001012 // AND there is no active privacy sensitive capture or call
1013 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4ab18412022-11-07 16:25:32 +01001014 bool allowSensitiveCapture =
1015 !isSensitiveActive || isTopOrLatestSensitive || current->canCaptureOutput;
Eric Laurent1ff16a72019-03-14 18:35:04 -07001016 bool allowCapture = !isAssistantOnTop
Eric Laurentc21d5692020-02-25 10:24:36 -08001017 && (isTopOrLatestActive || isTopOrLatestSensitive)
Eric Laurent4ab18412022-11-07 16:25:32 +01001018 && allowSensitiveCapture
Eric Laurentc21d5692020-02-25 10:24:36 -08001019 && canCaptureIfInCallOrCommunication(current);
Eric Laurent2dc962b2019-03-01 08:25:25 -08001020
Eric Laurented726cc2021-07-01 14:26:41 +02001021 if (!current->hasOp()) {
1022 // Never allow capture if app op is denied
1023 allowCapture = false;
1024 } else if (isVirtualSource(source)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001025 // Allow capture for virtual (remote submix, call audio TX or RX...) sources
1026 allowCapture = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001027 } else if (!useActiveAssistantList && mUidPolicy->isAssistantUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001028 // For assistant allow capture if:
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001029 // Active assistant list is not being used
1030 // AND accessibility service is on TOP or a RTT call is active
Eric Laurent1ff16a72019-03-14 18:35:04 -07001031 // AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001032 // OR there is no active privacy sensitive capture or call
1033 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
1034 // AND is latest TOP assistant AND
1035 // uses VOICE_RECOGNITION OR uses HOTWORD
1036 // OR there is no TOP assistant and uses HOTWORD
Eric Laurent6ede98f2019-06-11 14:50:30 -07001037 if (isA11yOnTop || rttCallActive) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001038 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001039 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001040 }
Eric Laurent4ab18412022-11-07 16:25:32 +01001041 } else if (allowSensitiveCapture
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001042 && canCaptureIfInCallOrCommunication(current)) {
1043 if (isTopOrLatestAssistant
1044 && (source == AUDIO_SOURCE_VOICE_RECOGNITION
1045 || source == AUDIO_SOURCE_HOTWORD)) {
1046 allowCapture = true;
1047 } else if (!isAssistantOnTop && (source == AUDIO_SOURCE_HOTWORD)) {
1048 allowCapture = true;
1049 }
1050 }
1051 } else if (useActiveAssistantList && mUidPolicy->isActiveAssistantUid(currentUid)) {
1052 // For assistant on active list and on top allow capture if:
1053 // An accessibility service is on TOP
1054 // AND the source is VOICE_RECOGNITION or HOTWORD
1055 // OR there is no active privacy sensitive capture or call
1056 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
1057 // AND uses VOICE_RECOGNITION OR uses HOTWORD
1058 if (isA11yOnTop) {
1059 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
1060 allowCapture = true;
1061 }
Eric Laurent4ab18412022-11-07 16:25:32 +01001062 } else if (allowSensitiveCapture
Eric Laurentc21d5692020-02-25 10:24:36 -08001063 && canCaptureIfInCallOrCommunication(current)) {
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001064 if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) || (source == AUDIO_SOURCE_HOTWORD))
1065 {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001066 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08001067 }
1068 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001069 } else if (mUidPolicy->isA11yUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001070 // For accessibility service allow capture if:
Eric Laurent47670c92019-08-28 16:59:05 -07001071 // The assistant is not on TOP
1072 // AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -07001073 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent47670c92019-08-28 16:59:05 -07001074 // OR
1075 // Is on TOP AND the source is VOICE_RECOGNITION or HOTWORD
1076 if (!isAssistantOnTop
Eric Laurent4ab18412022-11-07 16:25:32 +01001077 && allowSensitiveCapture
Eric Laurentc21d5692020-02-25 10:24:36 -08001078 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent47670c92019-08-28 16:59:05 -07001079 allowCapture = true;
1080 }
Eric Laurent589171c2019-07-25 18:04:29 -07001081 if (isA11yOnTop) {
1082 if (source == AUDIO_SOURCE_VOICE_RECOGNITION || source == AUDIO_SOURCE_HOTWORD) {
1083 allowCapture = true;
1084 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001085 }
Eric Laurent4e947da2019-10-17 15:24:06 -07001086 } else if (source == AUDIO_SOURCE_HOTWORD) {
1087 // For HOTWORD source allow capture when not on TOP if:
1088 // All active clients are using HOTWORD source
1089 // AND no call is active
1090 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurentc21d5692020-02-25 10:24:36 -08001091 if (onlyHotwordActive
1092 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent4e947da2019-10-17 15:24:06 -07001093 allowCapture = true;
1094 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001095 } else if (mUidPolicy->isCurrentImeUid(currentUid)) {
Kohsuke Yatoha623a132020-03-24 20:10:26 -07001096 // For current InputMethodService allow capture if:
1097 // A RTT call is active AND the source is VOICE_RECOGNITION
1098 if (rttCallActive && source == AUDIO_SOURCE_VOICE_RECOGNITION) {
1099 allowCapture = true;
1100 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001101 }
Eric Laurent8c7ef892021-06-10 13:32:16 +02001102 setAppState_l(current,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001103 allowCapture ? apmStatFromAmState(mUidPolicy->getUidState(currentUid)) :
Eric Laurent1ff16a72019-03-14 18:35:04 -07001104 APP_STATE_IDLE);
Eric Laurente8c8b432018-10-17 10:08:02 -07001105 }
1106}
1107
Michael Groovercfd28302018-12-11 19:16:46 -08001108void AudioPolicyService::silenceAllRecordings_l() {
1109 for (size_t i = 0; i < mAudioRecordClients.size(); i++) {
1110 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -07001111 if (!isVirtualSource(current->attributes.source)) {
Eric Laurent8c7ef892021-06-10 13:32:16 +02001112 setAppState_l(current, APP_STATE_IDLE);
Eric Laurent1ff16a72019-03-14 18:35:04 -07001113 }
Michael Groovercfd28302018-12-11 19:16:46 -08001114 }
1115}
1116
Eric Laurente8c8b432018-10-17 10:08:02 -07001117/* static */
1118app_state_t AudioPolicyService::apmStatFromAmState(int amState) {
Eric Laurent1ff16a72019-03-14 18:35:04 -07001119
1120 if (amState == ActivityManager::PROCESS_STATE_UNKNOWN) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001121 return APP_STATE_IDLE;
Eric Laurent1ff16a72019-03-14 18:35:04 -07001122 } else if (amState <= ActivityManager::PROCESS_STATE_TOP) {
1123 // include persistent services
1124 return APP_STATE_TOP;
Eric Laurente8c8b432018-10-17 10:08:02 -07001125 }
1126 return APP_STATE_FOREGROUND;
1127}
1128
Eric Laurent4eb58f12018-12-07 16:41:02 -08001129/* static */
Eric Laurent2dc962b2019-03-01 08:25:25 -08001130bool AudioPolicyService::isVirtualSource(audio_source_t source)
Eric Laurent4eb58f12018-12-07 16:41:02 -08001131{
1132 switch (source) {
1133 case AUDIO_SOURCE_VOICE_UPLINK:
1134 case AUDIO_SOURCE_VOICE_DOWNLINK:
1135 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent2dc962b2019-03-01 08:25:25 -08001136 case AUDIO_SOURCE_REMOTE_SUBMIX:
1137 case AUDIO_SOURCE_FM_TUNER:
Eric Laurent68eb2122020-04-30 17:40:57 -07001138 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent4eb58f12018-12-07 16:41:02 -08001139 return true;
1140 default:
1141 break;
1142 }
1143 return false;
1144}
1145
Eric Laurented726cc2021-07-01 14:26:41 +02001146/* static */
1147bool AudioPolicyService::isAppOpSource(audio_source_t source)
1148{
1149 switch (source) {
1150 case AUDIO_SOURCE_FM_TUNER:
1151 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent637bd202021-09-22 11:17:11 +02001152 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurented726cc2021-07-01 14:26:41 +02001153 return false;
1154 default:
1155 break;
1156 }
1157 return true;
1158}
1159
Eric Laurent8c7ef892021-06-10 13:32:16 +02001160void AudioPolicyService::setAppState_l(sp<AudioRecordClient> client, app_state_t state)
Eric Laurente8c8b432018-10-17 10:08:02 -07001161{
1162 AutoCallerClear acc;
1163
1164 if (mAudioPolicyManager) {
Eric Laurent8c7ef892021-06-10 13:32:16 +02001165 mAudioPolicyManager->setAppState(client->portId, state);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001166 }
1167 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1168 if (af) {
Eric Laurentf32108e2018-10-04 17:22:04 -07001169 bool silenced = state == APP_STATE_IDLE;
Eric Laurent8c7ef892021-06-10 13:32:16 +02001170 if (client->silenced != silenced) {
1171 if (client->active) {
1172 if (silenced) {
1173 finishRecording(client->attributionSource, client->attributes.source);
1174 } else {
1175 std::stringstream msg;
1176 msg << "Audio recording un-silenced on session " << client->session;
1177 if (!startRecording(client->attributionSource, String16(msg.str().c_str()),
1178 client->attributes.source)) {
1179 silenced = true;
1180 }
1181 }
1182 }
1183 af->setRecordSilenced(client->portId, silenced);
1184 client->silenced = silenced;
1185 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001186 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001187}
1188
Glenn Kasten0f11b512014-01-31 16:18:54 -08001189status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001190{
Glenn Kasten44deb052012-02-05 18:09:08 -08001191 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001192 dumpPermissionDenial(fd);
1193 } else {
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001194 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001195 if (!locked) {
1196 String8 result(kDeadlockedString);
1197 write(fd, result.string(), result.size());
1198 }
1199
1200 dumpInternals(fd);
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001201
1202 String8 actPtr = String8::format("AudioCommandThread: %p\n", mAudioCommandThread.get());
1203 write(fd, actPtr.string(), actPtr.size());
Glenn Kasten9d1f02d2012-02-08 17:47:58 -08001204 if (mAudioCommandThread != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001205 mAudioCommandThread->dump(fd);
1206 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001207
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001208 String8 octPtr = String8::format("OutputCommandThread: %p\n", mOutputCommandThread.get());
1209 write(fd, octPtr.string(), octPtr.size());
1210 if (mOutputCommandThread != 0) {
1211 mOutputCommandThread->dump(fd);
1212 }
1213
Eric Laurentdce54a12014-03-10 12:19:46 -07001214 if (mAudioPolicyManager) {
1215 mAudioPolicyManager->dump(fd);
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001216 } else {
1217 String8 apmPtr = String8::format("AudioPolicyManager: %p\n", mAudioPolicyManager);
1218 write(fd, apmPtr.string(), apmPtr.size());
Eric Laurentdce54a12014-03-10 12:19:46 -07001219 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001220
Kevin Rocard8be94972019-02-22 13:26:25 -08001221 mPackageManager.dump(fd);
1222
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001223 dumpReleaseLock(mLock, locked);
Andy Hungc747c532022-03-07 21:41:14 -08001224
Shunkai Yao59b27bc2022-07-22 18:42:27 +00001225 if (mSpatializer != nullptr) {
1226 std::string dumpString = mSpatializer->toString(1 /* level */);
1227 write(fd, dumpString.c_str(), dumpString.size());
1228 } else {
1229 String8 spatializerPtr = String8::format("Spatializer no supportted on this device\n");
1230 write(fd, spatializerPtr.c_str(), spatializerPtr.size());
1231 }
1232
Andy Hungc747c532022-03-07 21:41:14 -08001233 {
1234 std::string timeCheckStats = getIAudioPolicyServiceStatistics().dump();
1235 dprintf(fd, "\nIAudioPolicyService binder call profile\n");
1236 write(fd, timeCheckStats.c_str(), timeCheckStats.size());
1237 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001238 }
1239 return NO_ERROR;
1240}
1241
1242status_t AudioPolicyService::dumpPermissionDenial(int fd)
1243{
1244 const size_t SIZE = 256;
1245 char buffer[SIZE];
1246 String8 result;
1247 snprintf(buffer, SIZE, "Permission Denial: "
1248 "can't dump AudioPolicyService from pid=%d, uid=%d\n",
1249 IPCThreadState::self()->getCallingPid(),
1250 IPCThreadState::self()->getCallingUid());
1251 result.append(buffer);
1252 write(fd, result.string(), result.size());
1253 return NO_ERROR;
1254}
1255
1256status_t AudioPolicyService::onTransact(
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001257 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001258 // make sure transactions reserved to AudioFlinger do not come from other processes
1259 switch (code) {
1260 case TRANSACTION_startOutput:
1261 case TRANSACTION_stopOutput:
1262 case TRANSACTION_releaseOutput:
1263 case TRANSACTION_getInputForAttr:
1264 case TRANSACTION_startInput:
1265 case TRANSACTION_stopInput:
1266 case TRANSACTION_releaseInput:
1267 case TRANSACTION_getOutputForEffect:
1268 case TRANSACTION_registerEffect:
1269 case TRANSACTION_unregisterEffect:
1270 case TRANSACTION_setEffectEnabled:
1271 case TRANSACTION_getStrategyForStream:
1272 case TRANSACTION_getOutputForAttr:
1273 case TRANSACTION_moveEffectsToIo:
1274 ALOGW("%s: transaction %d received from PID %d",
1275 __func__, code, IPCThreadState::self()->getCallingPid());
1276 return INVALID_OPERATION;
1277 default:
1278 break;
1279 }
1280
1281 // make sure the following transactions come from system components
1282 switch (code) {
1283 case TRANSACTION_setDeviceConnectionState:
1284 case TRANSACTION_handleDeviceConfigChange:
1285 case TRANSACTION_setPhoneState:
1286//FIXME: Allow setForceUse calls from system apps until a better use case routing API is available
1287// case TRANSACTION_setForceUse:
1288 case TRANSACTION_initStreamVolume:
1289 case TRANSACTION_setStreamVolumeIndex:
1290 case TRANSACTION_setVolumeIndexForAttributes:
1291 case TRANSACTION_getStreamVolumeIndex:
1292 case TRANSACTION_getVolumeIndexForAttributes:
1293 case TRANSACTION_getMinVolumeIndexForAttributes:
1294 case TRANSACTION_getMaxVolumeIndexForAttributes:
1295 case TRANSACTION_isStreamActive:
1296 case TRANSACTION_isStreamActiveRemotely:
1297 case TRANSACTION_isSourceActive:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001298 case TRANSACTION_registerPolicyMixes:
1299 case TRANSACTION_setMasterMono:
1300 case TRANSACTION_getSurroundFormats:
Kriti Dang6537def2021-03-02 13:46:59 +01001301 case TRANSACTION_getReportedSurroundFormats:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001302 case TRANSACTION_setSurroundFormatEnabled:
Oscar Azucena829d90d2022-01-28 17:17:56 -08001303 case TRANSACTION_setAssistantServicesUids:
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001304 case TRANSACTION_setActiveAssistantServicesUids:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001305 case TRANSACTION_setA11yServicesUids:
1306 case TRANSACTION_setUidDeviceAffinities:
1307 case TRANSACTION_removeUidDeviceAffinities:
1308 case TRANSACTION_setUserIdDeviceAffinities:
1309 case TRANSACTION_removeUserIdDeviceAffinities:
Pattydd807582021-11-04 21:01:03 +08001310 case TRANSACTION_getHwOffloadFormatsSupportedForBluetoothMedia:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001311 case TRANSACTION_listAudioVolumeGroups:
1312 case TRANSACTION_getVolumeGroupFromAudioAttributes:
1313 case TRANSACTION_acquireSoundTriggerSession:
1314 case TRANSACTION_releaseSoundTriggerSession:
1315 case TRANSACTION_setRttEnabled:
1316 case TRANSACTION_isCallScreenModeSupported:
1317 case TRANSACTION_setDevicesRoleForStrategy:
1318 case TRANSACTION_setSupportedSystemUsages:
1319 case TRANSACTION_removeDevicesRoleForStrategy:
1320 case TRANSACTION_getDevicesForRoleAndStrategy:
1321 case TRANSACTION_getDevicesForAttributes:
1322 case TRANSACTION_setAllowedCapturePolicy:
1323 case TRANSACTION_onNewAudioModulesAvailable:
1324 case TRANSACTION_setCurrentImeUid:
1325 case TRANSACTION_registerSoundTriggerCaptureStateListener:
1326 case TRANSACTION_setDevicesRoleForCapturePreset:
1327 case TRANSACTION_addDevicesRoleForCapturePreset:
1328 case TRANSACTION_removeDevicesRoleForCapturePreset:
1329 case TRANSACTION_clearDevicesRoleForCapturePreset:
Eric Laurent81dd0f52021-07-05 11:54:40 +02001330 case TRANSACTION_getDevicesForRoleAndCapturePreset:
jiabina84c3d32022-12-02 18:59:55 +00001331 case TRANSACTION_getSpatializer:
1332 case TRANSACTION_setPreferredMixerAttributes:
1333 case TRANSACTION_clearPreferredMixerAttributes: {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001334 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
1335 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
1336 __func__, code, IPCThreadState::self()->getCallingPid(),
1337 IPCThreadState::self()->getCallingUid());
1338 return INVALID_OPERATION;
1339 }
1340 } break;
1341 default:
1342 break;
1343 }
1344
Andy Hungc747c532022-03-07 21:41:14 -08001345 const std::string methodName = getIAudioPolicyServiceStatistics().getMethodForCode(code);
1346 mediautils::TimeCheck check(
1347 std::string("IAudioPolicyService::").append(methodName),
1348 [code, methodName](bool timeout, float elapsedMs) { // don't move methodName.
1349 if (timeout) {
1350 mediametrics::LogItem(AMEDIAMETRICS_KEY_AUDIO_POLICY)
1351 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_TIMEOUT)
1352 .set(AMEDIAMETRICS_PROP_METHODCODE, int64_t(code))
1353 .set(AMEDIAMETRICS_PROP_METHODNAME, methodName.c_str())
1354 .record();
1355 } else {
1356 getIAudioPolicyServiceStatistics().event(code, elapsedMs);
1357 }
Andy Hung741b3dd2022-06-13 19:49:43 -07001358 }, mediautils::TimeCheck::kDefaultTimeoutDuration,
1359 mediautils::TimeCheck::kDefaultSecondChanceDuration,
1360 true /* crashOnTimeout */);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001361
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001362 switch (code) {
1363 case SHELL_COMMAND_TRANSACTION: {
1364 int in = data.readFileDescriptor();
1365 int out = data.readFileDescriptor();
1366 int err = data.readFileDescriptor();
1367 int argc = data.readInt32();
1368 Vector<String16> args;
1369 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
1370 args.add(data.readString16());
1371 }
1372 sp<IBinder> unusedCallback;
1373 sp<IResultReceiver> resultReceiver;
1374 status_t status;
1375 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
1376 return status;
1377 }
1378 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
1379 return status;
1380 }
1381 status = shellCommand(in, out, err, args);
1382 if (resultReceiver != nullptr) {
1383 resultReceiver->send(status);
1384 }
1385 return NO_ERROR;
1386 }
1387 }
1388
Mathias Agopian65ab4712010-07-14 17:59:35 -07001389 return BnAudioPolicyService::onTransact(code, data, reply, flags);
1390}
1391
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001392// ------------------- Shell command implementation -------------------
1393
1394// NOTE: This is a remote API - make sure all args are validated
1395status_t AudioPolicyService::shellCommand(int in, int out, int err, Vector<String16>& args) {
1396 if (!checkCallingPermission(sManageAudioPolicyPermission, nullptr, nullptr)) {
1397 return PERMISSION_DENIED;
1398 }
1399 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
1400 return BAD_VALUE;
1401 }
jovanakbe066e12019-09-02 11:54:39 -07001402 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001403 return handleSetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001404 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001405 return handleResetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001406 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001407 return handleGetUidState(args, out, err);
Eric Laurent269acb42021-04-23 16:53:22 +02001408 } else if (args.size() >= 1 && args[0] == String16("purge_permission-cache")) {
1409 purgePermissionCache();
1410 return NO_ERROR;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001411 } else if (args.size() == 1 && args[0] == String16("help")) {
1412 printHelp(out);
1413 return NO_ERROR;
1414 }
1415 printHelp(err);
1416 return BAD_VALUE;
1417}
1418
jovanakbe066e12019-09-02 11:54:39 -07001419static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1420 if (userId < 0) {
1421 ALOGE("Invalid user: %d", userId);
1422 dprintf(err, "Invalid user: %d\n", userId);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001423 return BAD_VALUE;
1424 }
jovanakbe066e12019-09-02 11:54:39 -07001425
1426 PermissionController pc;
1427 uid = pc.getPackageUid(packageName, 0);
1428 if (uid <= 0) {
1429 ALOGE("Unknown package: '%s'", String8(packageName).string());
1430 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1431 return BAD_VALUE;
1432 }
1433
1434 uid = multiuser_get_uid(userId, uid);
1435 return NO_ERROR;
1436}
1437
1438status_t AudioPolicyService::handleSetUidState(Vector<String16>& args, int err) {
1439 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
1440 if (!(args.size() == 3 || args.size() == 5)) {
1441 printHelp(err);
1442 return BAD_VALUE;
1443 }
1444
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001445 bool active = false;
1446 if (args[2] == String16("active")) {
1447 active = true;
1448 } else if ((args[2] != String16("idle"))) {
1449 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
1450 return BAD_VALUE;
1451 }
jovanakbe066e12019-09-02 11:54:39 -07001452
1453 int userId = 0;
1454 if (args.size() >= 5 && args[3] == String16("--user")) {
1455 userId = atoi(String8(args[4]));
1456 }
1457
1458 uid_t uid;
1459 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1460 return BAD_VALUE;
1461 }
1462
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001463 sp<UidPolicy> uidPolicy;
1464 {
1465 Mutex::Autolock _l(mLock);
1466 uidPolicy = mUidPolicy;
1467 }
1468 if (uidPolicy) {
1469 uidPolicy->addOverrideUid(uid, active);
1470 return NO_ERROR;
1471 }
1472 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001473}
1474
1475status_t AudioPolicyService::handleResetUidState(Vector<String16>& args, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001476 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1477 if (!(args.size() == 2 || args.size() == 4)) {
1478 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001479 return BAD_VALUE;
1480 }
jovanakbe066e12019-09-02 11:54:39 -07001481
1482 int userId = 0;
1483 if (args.size() >= 4 && args[2] == String16("--user")) {
1484 userId = atoi(String8(args[3]));
1485 }
1486
1487 uid_t uid;
1488 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1489 return BAD_VALUE;
1490 }
1491
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001492 sp<UidPolicy> uidPolicy;
1493 {
1494 Mutex::Autolock _l(mLock);
1495 uidPolicy = mUidPolicy;
1496 }
1497 if (uidPolicy) {
1498 uidPolicy->removeOverrideUid(uid);
1499 return NO_ERROR;
1500 }
1501 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001502}
1503
1504status_t AudioPolicyService::handleGetUidState(Vector<String16>& args, int out, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001505 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1506 if (!(args.size() == 2 || args.size() == 4)) {
1507 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001508 return BAD_VALUE;
1509 }
jovanakbe066e12019-09-02 11:54:39 -07001510
1511 int userId = 0;
1512 if (args.size() >= 4 && args[2] == String16("--user")) {
1513 userId = atoi(String8(args[3]));
1514 }
1515
1516 uid_t uid;
1517 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1518 return BAD_VALUE;
1519 }
1520
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001521 sp<UidPolicy> uidPolicy;
1522 {
1523 Mutex::Autolock _l(mLock);
1524 uidPolicy = mUidPolicy;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001525 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001526 if (uidPolicy) {
1527 return dprintf(out, uidPolicy->isUidActive(uid) ? "active\n" : "idle\n");
1528 }
1529 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001530}
1531
1532status_t AudioPolicyService::printHelp(int out) {
1533 return dprintf(out, "Audio policy service commands:\n"
jovanakbe066e12019-09-02 11:54:39 -07001534 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
1535 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
1536 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001537 " help print this message\n");
1538}
1539
1540// ----------- AudioPolicyService::UidPolicy implementation ----------
1541
1542void AudioPolicyService::UidPolicy::registerSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001543 status_t res = mAm.linkToDeath(this);
1544 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001545 | ActivityManager::UID_OBSERVER_IDLE
Eric Laurente8c8b432018-10-17 10:08:02 -07001546 | ActivityManager::UID_OBSERVER_ACTIVE
1547 | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001548 ActivityManager::PROCESS_STATE_UNKNOWN,
1549 String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001550 if (!res) {
1551 Mutex::Autolock _l(mLock);
1552 mObserverRegistered = true;
1553 } else {
1554 ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001555
Steven Moreland2f348142019-07-02 15:59:07 -07001556 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001557 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001558}
1559
1560void AudioPolicyService::UidPolicy::unregisterSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001561 mAm.unlinkToDeath(this);
1562 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001563 Mutex::Autolock _l(mLock);
1564 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001565}
1566
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001567void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
1568 Mutex::Autolock _l(mLock);
1569 mCachedUids.clear();
1570 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001571}
1572
Eric Laurente8c8b432018-10-17 10:08:02 -07001573void AudioPolicyService::UidPolicy::checkRegistered() {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001574 bool needToReregister = false;
1575 {
1576 Mutex::Autolock _l(mLock);
1577 needToReregister = !mObserverRegistered;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001578 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001579 if (needToReregister) {
1580 // Looks like ActivityManager has died previously, attempt to re-register.
1581 registerSelf();
1582 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001583}
1584
1585bool AudioPolicyService::UidPolicy::isUidActive(uid_t uid) {
1586 if (isServiceUid(uid)) return true;
1587 checkRegistered();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001588 {
1589 Mutex::Autolock _l(mLock);
1590 auto overrideIter = mOverrideUids.find(uid);
1591 if (overrideIter != mOverrideUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001592 return overrideIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001593 }
1594 // In an absense of the ActivityManager, assume everything to be active.
1595 if (!mObserverRegistered) return true;
1596 auto cacheIter = mCachedUids.find(uid);
Mikhail Naganoveba668a2018-04-05 08:13:15 -07001597 if (cacheIter != mCachedUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001598 return cacheIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001599 }
1600 }
1601 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001602 bool active = am.isUidActive(uid, String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001603 {
1604 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001605 mCachedUids.insert(std::pair<uid_t,
1606 std::pair<bool, int>>(uid, std::pair<bool, int>(active,
1607 ActivityManager::PROCESS_STATE_UNKNOWN)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001608 }
1609 return active;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001610}
1611
Eric Laurente8c8b432018-10-17 10:08:02 -07001612int AudioPolicyService::UidPolicy::getUidState(uid_t uid) {
1613 if (isServiceUid(uid)) {
1614 return ActivityManager::PROCESS_STATE_TOP;
1615 }
1616 checkRegistered();
1617 {
1618 Mutex::Autolock _l(mLock);
1619 auto overrideIter = mOverrideUids.find(uid);
1620 if (overrideIter != mOverrideUids.end()) {
1621 if (overrideIter->second.first) {
1622 if (overrideIter->second.second != ActivityManager::PROCESS_STATE_UNKNOWN) {
1623 return overrideIter->second.second;
1624 } else {
1625 auto cacheIter = mCachedUids.find(uid);
1626 if (cacheIter != mCachedUids.end()) {
1627 return cacheIter->second.second;
1628 }
1629 }
1630 }
1631 return ActivityManager::PROCESS_STATE_UNKNOWN;
1632 }
1633 // In an absense of the ActivityManager, assume everything to be active.
1634 if (!mObserverRegistered) {
1635 return ActivityManager::PROCESS_STATE_TOP;
1636 }
1637 auto cacheIter = mCachedUids.find(uid);
1638 if (cacheIter != mCachedUids.end()) {
1639 if (cacheIter->second.first) {
1640 return cacheIter->second.second;
1641 } else {
1642 return ActivityManager::PROCESS_STATE_UNKNOWN;
1643 }
1644 }
1645 }
1646 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001647 bool active = am.isUidActive(uid, String16("audioserver"));
Eric Laurente8c8b432018-10-17 10:08:02 -07001648 int state = ActivityManager::PROCESS_STATE_UNKNOWN;
1649 if (active) {
1650 state = am.getUidProcessState(uid, String16("audioserver"));
1651 }
1652 {
1653 Mutex::Autolock _l(mLock);
1654 mCachedUids.insert(std::pair<uid_t,
1655 std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
1656 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001657
Eric Laurente8c8b432018-10-17 10:08:02 -07001658 return state;
1659}
1660
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001661void AudioPolicyService::UidPolicy::onUidActive(uid_t uid) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001662 updateUid(&mCachedUids, uid, true, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001663}
1664
1665void AudioPolicyService::UidPolicy::onUidGone(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001666 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, false);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001667}
1668
1669void AudioPolicyService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001670 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001671}
1672
Eric Laurente8c8b432018-10-17 10:08:02 -07001673void AudioPolicyService::UidPolicy::onUidStateChanged(uid_t uid,
1674 int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07001675 int64_t procStateSeq __unused,
1676 int32_t capability __unused) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001677 if (procState != ActivityManager::PROCESS_STATE_UNKNOWN) {
1678 updateUid(&mCachedUids, uid, true, procState, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001679 }
1680}
1681
Austin Borger65577682022-02-17 00:25:43 +00001682void AudioPolicyService::UidPolicy::onUidProcAdjChanged(uid_t uid __unused) {
1683}
1684
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001685void AudioPolicyService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001686 updateUid(&mOverrideUids, uid, active, ActivityManager::PROCESS_STATE_UNKNOWN, insert);
1687}
1688
1689void AudioPolicyService::UidPolicy::notifyService() {
1690 sp<AudioPolicyService> service = mService.promote();
1691 if (service != nullptr) {
1692 service->updateUidStates();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001693 }
1694}
1695
Eric Laurente8c8b432018-10-17 10:08:02 -07001696void AudioPolicyService::UidPolicy::updateUid(std::unordered_map<uid_t,
1697 std::pair<bool, int>> *uids,
1698 uid_t uid,
1699 bool active,
1700 int state,
1701 bool insert) {
1702 if (isServiceUid(uid)) {
1703 return;
1704 }
1705 bool wasActive = isUidActive(uid);
1706 int previousState = getUidState(uid);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001707 {
1708 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001709 updateUidLocked(uids, uid, active, state, insert);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001710 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001711 if (wasActive != isUidActive(uid) || state != previousState) {
1712 notifyService();
1713 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001714}
1715
Eric Laurente8c8b432018-10-17 10:08:02 -07001716void AudioPolicyService::UidPolicy::updateUidLocked(std::unordered_map<uid_t,
1717 std::pair<bool, int>> *uids,
1718 uid_t uid,
1719 bool active,
1720 int state,
1721 bool insert) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001722 auto it = uids->find(uid);
1723 if (it != uids->end()) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001724 if (insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001725 if (state == ActivityManager::PROCESS_STATE_UNKNOWN) {
1726 it->second.first = active;
1727 }
1728 if (it->second.first) {
1729 it->second.second = state;
1730 } else {
1731 it->second.second = ActivityManager::PROCESS_STATE_UNKNOWN;
1732 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001733 } else {
1734 uids->erase(it);
1735 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001736 } else if (insert && (state == ActivityManager::PROCESS_STATE_UNKNOWN)) {
1737 uids->insert(std::pair<uid_t, std::pair<bool, int>>(uid,
1738 std::pair<bool, int>(active, state)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001739 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001740}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001741
Eric Laurent4eb58f12018-12-07 16:41:02 -08001742bool AudioPolicyService::UidPolicy::isA11yOnTop() {
lihong80e1f56e2022-08-25 11:15:33 +08001743 Mutex::Autolock _l(mLock);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001744 for (const auto &uid : mCachedUids) {
Eric Laurent47670c92019-08-28 16:59:05 -07001745 if (!isA11yUid(uid.first)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001746 continue;
1747 }
Amith Yamasanibcbb3002019-01-23 13:53:33 -08001748 if (uid.second.second >= ActivityManager::PROCESS_STATE_TOP
1749 && uid.second.second <= ActivityManager::PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001750 return true;
1751 }
1752 }
1753 return false;
1754}
1755
Eric Laurentb78763e2018-10-17 10:08:02 -07001756bool AudioPolicyService::UidPolicy::isA11yUid(uid_t uid)
1757{
1758 std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid);
1759 return it != mA11yUids.end();
1760}
1761
Oscar Azucena829d90d2022-01-28 17:17:56 -08001762void AudioPolicyService::UidPolicy::setAssistantUids(const std::vector<uid_t>& uids) {
1763 mAssistantUids.clear();
1764 mAssistantUids = uids;
1765}
1766
1767bool AudioPolicyService::UidPolicy::isAssistantUid(uid_t uid)
1768{
1769 std::vector<uid_t>::iterator it = find(mAssistantUids.begin(), mAssistantUids.end(), uid);
1770 return it != mAssistantUids.end();
1771}
1772
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001773void AudioPolicyService::UidPolicy::setActiveAssistantUids(const std::vector<uid_t>& activeUids) {
1774 mActiveAssistantUids = activeUids;
1775}
1776
1777bool AudioPolicyService::UidPolicy::isActiveAssistantUid(uid_t uid)
1778{
1779 std::vector<uid_t>::iterator it = find(mActiveAssistantUids.begin(),
1780 mActiveAssistantUids.end(), uid);
1781 return it != mActiveAssistantUids.end();
1782}
1783
Oscar Azucena829d90d2022-01-28 17:17:56 -08001784void AudioPolicyService::UidPolicy::dumpInternals(int fd) {
1785 const size_t SIZE = 256;
1786 char buffer[SIZE];
1787 String8 result;
1788 auto appendUidsToResult = [&](const char* title, const std::vector<uid_t> &uids) {
1789 snprintf(buffer, SIZE, "\t%s: \n", title);
1790 result.append(buffer);
1791 int counter = 0;
1792 if (uids.empty()) {
1793 snprintf(buffer, SIZE, "\t\tNo UIDs present.\n");
1794 result.append(buffer);
1795 return;
1796 }
1797 for (const auto &uid : uids) {
1798 snprintf(buffer, SIZE, "\t\tUID[%d]=%d\n", counter++, uid);
1799 result.append(buffer);
1800 }
1801 };
1802
1803 snprintf(buffer, SIZE, "UID Policy:\n");
1804 result.append(buffer);
1805 snprintf(buffer, SIZE, "\tmObserverRegistered=%s\n",(mObserverRegistered ? "True":"False"));
1806 result.append(buffer);
1807
1808 appendUidsToResult("Assistants UIDs", mAssistantUids);
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001809 appendUidsToResult("Active Assistants UIDs", mActiveAssistantUids);
Oscar Azucena829d90d2022-01-28 17:17:56 -08001810
1811 appendUidsToResult("Accessibility UIDs", mA11yUids);
1812
1813 snprintf(buffer, SIZE, "\tInput Method Service UID=%d\n", mCurrentImeUid);
1814 result.append(buffer);
1815
1816 snprintf(buffer, SIZE, "\tIs RTT Enabled: %s\n", (mRttEnabled ? "True":"False"));
1817 result.append(buffer);
1818
1819 write(fd, result.string(), result.size());
1820}
1821
Michael Groovercfd28302018-12-11 19:16:46 -08001822// ----------- AudioPolicyService::SensorPrivacyService implementation ----------
1823void AudioPolicyService::SensorPrivacyPolicy::registerSelf() {
1824 SensorPrivacyManager spm;
1825 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
Eric Laurent35cd7932022-11-17 11:47:19 +01001826 (void)spm.addToggleSensorPrivacyListener(this);
Michael Groovercfd28302018-12-11 19:16:46 -08001827 spm.addSensorPrivacyListener(this);
1828}
1829
1830void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
1831 SensorPrivacyManager spm;
1832 spm.removeSensorPrivacyListener(this);
Eric Laurent35cd7932022-11-17 11:47:19 +01001833 spm.removeToggleSensorPrivacyListener(this);
Michael Groovercfd28302018-12-11 19:16:46 -08001834}
1835
1836bool AudioPolicyService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1837 return mSensorPrivacyEnabled;
1838}
1839
Evan Seversond8dc6832022-01-27 10:47:03 -08001840binder::Status AudioPolicyService::SensorPrivacyPolicy::onSensorPrivacyChanged(
1841 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Groovercfd28302018-12-11 19:16:46 -08001842 mSensorPrivacyEnabled = enabled;
1843 sp<AudioPolicyService> service = mService.promote();
1844 if (service != nullptr) {
1845 service->updateUidStates();
1846 }
1847 return binder::Status::ok();
1848}
1849
Eric Laurented726cc2021-07-01 14:26:41 +02001850// ----------- AudioPolicyService::OpRecordAudioMonitor implementation ----------
1851
1852// static
1853sp<AudioPolicyService::OpRecordAudioMonitor>
1854AudioPolicyService::OpRecordAudioMonitor::createIfNeeded(
1855 const AttributionSourceState& attributionSource, const audio_attributes_t& attr,
1856 wp<AudioCommandThread> commandThread)
1857{
Eric Laurent987ce102021-07-05 12:11:51 +02001858 if (isAudioServerOrRootUid(attributionSource.uid)) {
1859 ALOGV("not silencing record for audio or root source %s",
Eric Laurented726cc2021-07-01 14:26:41 +02001860 attributionSource.toString().c_str());
1861 return nullptr;
1862 }
1863
1864 if (!AudioPolicyService::isAppOpSource(attr.source)) {
1865 ALOGD("not monitoring app op for uid %d and source %d",
1866 attributionSource.uid, attr.source);
1867 return nullptr;
1868 }
1869
1870 if (!attributionSource.packageName.has_value()
1871 || attributionSource.packageName.value().size() == 0) {
1872 return nullptr;
1873 }
1874 return new OpRecordAudioMonitor(attributionSource, getOpForSource(attr.source), commandThread);
1875}
1876
1877AudioPolicyService::OpRecordAudioMonitor::OpRecordAudioMonitor(
1878 const AttributionSourceState& attributionSource, int32_t appOp,
1879 wp<AudioCommandThread> commandThread) :
1880 mHasOp(true), mAttributionSource(attributionSource), mAppOp(appOp),
1881 mCommandThread(commandThread)
1882{
1883}
1884
1885AudioPolicyService::OpRecordAudioMonitor::~OpRecordAudioMonitor()
1886{
1887 if (mOpCallback != 0) {
1888 mAppOpsManager.stopWatchingMode(mOpCallback);
1889 }
1890 mOpCallback.clear();
1891}
1892
1893void AudioPolicyService::OpRecordAudioMonitor::onFirstRef()
1894{
1895 checkOp();
1896 mOpCallback = new RecordAudioOpCallback(this);
1897 ALOGV("start watching op %d for %s", mAppOp, mAttributionSource.toString().c_str());
1898 // TODO: We need to always watch AppOpsManager::OP_RECORD_AUDIO too
1899 // since it controls the mic permission for legacy apps.
1900 mAppOpsManager.startWatchingMode(mAppOp, VALUE_OR_FATAL(aidl2legacy_string_view_String16(
1901 mAttributionSource.packageName.value_or(""))),
1902 mOpCallback);
1903}
1904
1905bool AudioPolicyService::OpRecordAudioMonitor::hasOp() const {
1906 return mHasOp.load();
1907}
1908
1909// Called by RecordAudioOpCallback when the app op corresponding to this OpRecordAudioMonitor
1910// is updated in AppOp callback and in onFirstRef()
1911// Note this method is never called (and never to be) for audio server / root track
1912// due to the UID in createIfNeeded(). As a result for those record track, it's:
1913// - not called from constructor,
1914// - not called from RecordAudioOpCallback because the callback is not installed in this case
1915void AudioPolicyService::OpRecordAudioMonitor::checkOp(bool updateUidStates)
1916{
1917 // TODO: We need to always check AppOpsManager::OP_RECORD_AUDIO too
1918 // since it controls the mic permission for legacy apps.
1919 const int32_t mode = mAppOpsManager.checkOp(mAppOp,
1920 mAttributionSource.uid, VALUE_OR_FATAL(aidl2legacy_string_view_String16(
1921 mAttributionSource.packageName.value_or(""))));
1922 const bool hasIt = (mode == AppOpsManager::MODE_ALLOWED);
1923 // verbose logging only log when appOp changed
1924 ALOGI_IF(hasIt != mHasOp.load(),
1925 "App op %d missing, %ssilencing record %s",
1926 mAppOp, hasIt ? "un" : "", mAttributionSource.toString().c_str());
1927 mHasOp.store(hasIt);
1928
1929 if (updateUidStates) {
1930 sp<AudioCommandThread> commandThread = mCommandThread.promote();
1931 if (commandThread != nullptr) {
1932 commandThread->updateUidStatesCommand();
1933 }
1934 }
1935}
1936
1937AudioPolicyService::OpRecordAudioMonitor::RecordAudioOpCallback::RecordAudioOpCallback(
1938 const wp<OpRecordAudioMonitor>& monitor) : mMonitor(monitor)
1939{ }
1940
1941void AudioPolicyService::OpRecordAudioMonitor::RecordAudioOpCallback::opChanged(int32_t op,
1942 const String16& packageName __unused) {
1943 sp<OpRecordAudioMonitor> monitor = mMonitor.promote();
1944 if (monitor != NULL) {
1945 if (op != monitor->getOp()) {
1946 return;
1947 }
1948 monitor->checkOp(true);
1949 }
1950}
1951
1952
Mathias Agopian65ab4712010-07-14 17:59:35 -07001953// ----------- AudioPolicyService::AudioCommandThread implementation ----------
1954
Eric Laurentbfb1b832013-01-07 09:53:42 -08001955AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
1956 const wp<AudioPolicyService>& service)
1957 : Thread(false), mName(name), mService(service)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001958{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001959}
1960
1961
1962AudioPolicyService::AudioCommandThread::~AudioCommandThread()
1963{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001964 if (!mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001965 release_wake_lock(mName.string());
1966 }
1967 mAudioCommands.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001968}
1969
1970void AudioPolicyService::AudioCommandThread::onFirstRef()
1971{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001972 run(mName.string(), ANDROID_PRIORITY_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001973}
1974
1975bool AudioPolicyService::AudioCommandThread::threadLoop()
1976{
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001977 nsecs_t waitTime = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001978
1979 mLock.lock();
1980 while (!exitPending())
1981 {
Eric Laurent59a89232014-06-08 14:14:17 -07001982 sp<AudioPolicyService> svc;
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07001983 int numTimesBecameEmpty = 0;
Eric Laurent59a89232014-06-08 14:14:17 -07001984 while (!mAudioCommands.isEmpty() && !exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001985 nsecs_t curTime = systemTime();
1986 // commands are sorted by increasing time stamp: execute them from index 0 and up
1987 if (mAudioCommands[0]->mTime <= curTime) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001988 sp<AudioCommand> command = mAudioCommands[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001989 mAudioCommands.removeAt(0);
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07001990 if (mAudioCommands.isEmpty()) {
1991 ++numTimesBecameEmpty;
1992 }
Eric Laurent0ede8922014-05-09 18:04:42 -07001993 mLastCommand = command;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001994
1995 switch (command->mCommand) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001996 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001997 VolumeData *data = (VolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001998 ALOGV("AudioCommandThread() processing set volume stream %d, \
Eric Laurentde070132010-07-13 04:45:46 -07001999 volume %f, output %d", data->mStream, data->mVolume, data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07002000 mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07002001 command->mStatus = AudioSystem::setStreamVolume(data->mStream,
2002 data->mVolume,
2003 data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07002004 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002005 }break;
2006 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002007 ParametersData *data = (ParametersData *)command->mParam.get();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002008 ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
2009 data->mKeyValuePairs.string(), data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07002010 mLock.unlock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002011 command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
Andy Hungfe726a62018-09-27 15:17:25 -07002012 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002013 }break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002014 case SET_VOICE_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002015 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01002016 ALOGV("AudioCommandThread() processing set voice volume volume %f",
Eric Laurentde070132010-07-13 04:45:46 -07002017 data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07002018 mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002019 command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07002020 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002021 }break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002022 case STOP_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002023 StopOutputData *data = (StopOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002024 ALOGV("AudioCommandThread() processing stop output portId %d",
2025 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07002026 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002027 if (svc == 0) {
2028 break;
2029 }
2030 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002031 svc->doStopOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002032 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002033 }break;
2034 case RELEASE_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002035 ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002036 ALOGV("AudioCommandThread() processing release output portId %d",
2037 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07002038 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002039 if (svc == 0) {
2040 break;
2041 }
2042 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002043 svc->doReleaseOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002044 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002045 }break;
Eric Laurent951f4552014-05-20 10:48:17 -07002046 case CREATE_AUDIO_PATCH: {
2047 CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
2048 ALOGV("AudioCommandThread() processing create audio patch");
2049 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
2050 if (af == 0) {
2051 command->mStatus = PERMISSION_DENIED;
2052 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07002053 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07002054 command->mStatus = af->createAudioPatch(&data->mPatch, &data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07002055 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07002056 }
2057 } break;
2058 case RELEASE_AUDIO_PATCH: {
2059 ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
2060 ALOGV("AudioCommandThread() processing release audio patch");
2061 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
2062 if (af == 0) {
2063 command->mStatus = PERMISSION_DENIED;
2064 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07002065 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07002066 command->mStatus = af->releaseAudioPatch(data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07002067 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07002068 }
2069 } break;
Eric Laurentb52c1522014-05-20 11:27:36 -07002070 case UPDATE_AUDIOPORT_LIST: {
2071 ALOGV("AudioCommandThread() processing update audio port list");
Eric Laurent59a89232014-06-08 14:14:17 -07002072 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07002073 if (svc == 0) {
2074 break;
2075 }
2076 mLock.unlock();
2077 svc->doOnAudioPortListUpdate();
2078 mLock.lock();
2079 }break;
2080 case UPDATE_AUDIOPATCH_LIST: {
2081 ALOGV("AudioCommandThread() processing update audio patch list");
Eric Laurent59a89232014-06-08 14:14:17 -07002082 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07002083 if (svc == 0) {
2084 break;
2085 }
2086 mLock.unlock();
2087 svc->doOnAudioPatchListUpdate();
2088 mLock.lock();
2089 }break;
François Gaffiecfe17322018-11-07 13:41:29 +01002090 case CHANGED_AUDIOVOLUMEGROUP: {
2091 AudioVolumeGroupData *data =
2092 static_cast<AudioVolumeGroupData *>(command->mParam.get());
2093 ALOGV("AudioCommandThread() processing update audio volume group");
2094 svc = mService.promote();
2095 if (svc == 0) {
2096 break;
2097 }
2098 mLock.unlock();
2099 svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
2100 mLock.lock();
2101 }break;
Eric Laurente1715a42014-05-20 11:30:42 -07002102 case SET_AUDIOPORT_CONFIG: {
2103 SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
2104 ALOGV("AudioCommandThread() processing set port config");
2105 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
2106 if (af == 0) {
2107 command->mStatus = PERMISSION_DENIED;
2108 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07002109 mLock.unlock();
Eric Laurente1715a42014-05-20 11:30:42 -07002110 command->mStatus = af->setAudioPortConfig(&data->mConfig);
Andy Hungfe726a62018-09-27 15:17:25 -07002111 mLock.lock();
Eric Laurente1715a42014-05-20 11:30:42 -07002112 }
2113 } break;
Jean-Michel Trivide801052015-04-14 19:10:14 -07002114 case DYN_POLICY_MIX_STATE_UPDATE: {
2115 DynPolicyMixStateUpdateData *data =
2116 (DynPolicyMixStateUpdateData *)command->mParam.get();
Jean-Michel Trivide801052015-04-14 19:10:14 -07002117 ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
2118 data->mRegId.string(), data->mState);
2119 svc = mService.promote();
2120 if (svc == 0) {
2121 break;
2122 }
2123 mLock.unlock();
2124 svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
2125 mLock.lock();
2126 } break;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002127 case RECORDING_CONFIGURATION_UPDATE: {
2128 RecordingConfigurationUpdateData *data =
2129 (RecordingConfigurationUpdateData *)command->mParam.get();
2130 ALOGV("AudioCommandThread() processing recording configuration update");
2131 svc = mService.promote();
2132 if (svc == 0) {
2133 break;
2134 }
2135 mLock.unlock();
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002136 svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -08002137 &data->mClientConfig, data->mClientEffects,
2138 &data->mDeviceConfig, data->mEffects,
2139 data->mPatchHandle, data->mSource);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002140 mLock.lock();
2141 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002142 case SET_EFFECT_SUSPENDED: {
2143 SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
2144 ALOGV("AudioCommandThread() processing set effect suspended");
2145 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
2146 if (af != 0) {
2147 mLock.unlock();
2148 af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
2149 mLock.lock();
2150 }
2151 } break;
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002152 case AUDIO_MODULES_UPDATE: {
2153 ALOGV("AudioCommandThread() processing audio modules update");
2154 svc = mService.promote();
2155 if (svc == 0) {
2156 break;
2157 }
2158 mLock.unlock();
2159 svc->doOnNewAudioModulesAvailable();
2160 mLock.lock();
2161 } break;
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002162 case ROUTING_UPDATED: {
2163 ALOGV("AudioCommandThread() processing routing update");
2164 svc = mService.promote();
2165 if (svc == 0) {
2166 break;
2167 }
2168 mLock.unlock();
2169 svc->doOnRoutingUpdated();
2170 mLock.lock();
2171 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002172
Eric Laurented726cc2021-07-01 14:26:41 +02002173 case UPDATE_UID_STATES: {
2174 ALOGV("AudioCommandThread() processing updateUID states");
2175 svc = mService.promote();
2176 if (svc == 0) {
2177 break;
2178 }
2179 mLock.unlock();
2180 svc->updateUidStates();
2181 mLock.lock();
2182 } break;
2183
Eric Laurent15903592022-02-24 20:44:36 +01002184 case CHECK_SPATIALIZER_OUTPUT: {
2185 ALOGV("AudioCommandThread() processing check spatializer");
Eric Laurent81dd0f52021-07-05 11:54:40 +02002186 svc = mService.promote();
2187 if (svc == 0) {
2188 break;
2189 }
2190 mLock.unlock();
2191 svc->doOnCheckSpatializer();
2192 mLock.lock();
2193 } break;
2194
Eric Laurent15903592022-02-24 20:44:36 +01002195 case UPDATE_ACTIVE_SPATIALIZER_TRACKS: {
2196 ALOGV("AudioCommandThread() processing update spatializer tracks");
2197 svc = mService.promote();
2198 if (svc == 0) {
2199 break;
2200 }
2201 mLock.unlock();
2202 svc->doOnUpdateActiveSpatializerTracks();
2203 mLock.lock();
2204 } break;
2205
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002206 case VOL_RANGE_INIT_REQUEST: {
2207 ALOGV("AudioCommandThread() processing volume range init request");
2208 svc = mService.promote();
2209 if (svc == 0) {
2210 break;
2211 }
2212 mLock.unlock();
2213 svc->doOnVolumeRangeInitRequest();
2214 mLock.lock();
2215 } break;
2216
Mathias Agopian65ab4712010-07-14 17:59:35 -07002217 default:
Steve Block5ff1dd52012-01-05 23:22:43 +00002218 ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002219 }
Eric Laurent0ede8922014-05-09 18:04:42 -07002220 {
2221 Mutex::Autolock _l(command->mLock);
2222 if (command->mWaitStatus) {
2223 command->mWaitStatus = false;
2224 command->mCond.signal();
2225 }
2226 }
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002227 waitTime = -1;
Zach Janga754b4f2015-10-27 01:29:34 +00002228 // release mLock before releasing strong reference on the service as
2229 // AudioPolicyService destructor calls AudioCommandThread::exit() which
2230 // acquires mLock.
2231 mLock.unlock();
2232 svc.clear();
2233 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002234 } else {
2235 waitTime = mAudioCommands[0]->mTime - curTime;
2236 break;
2237 }
2238 }
Zach Janga754b4f2015-10-27 01:29:34 +00002239
Ytai Ben-Tsvi6958b022022-04-26 15:45:53 -07002240 // release delayed commands wake lock as many times as we made the queue is
2241 // empty during popping.
2242 while (numTimesBecameEmpty--) {
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002243 release_wake_lock(mName.string());
Zach Janga754b4f2015-10-27 01:29:34 +00002244 }
2245
2246 // At this stage we have either an empty command queue or the first command in the queue
2247 // has a finite delay. So unless we are exiting it is safe to wait.
2248 if (!exitPending()) {
Eric Laurent59a89232014-06-08 14:14:17 -07002249 ALOGV("AudioCommandThread() going to sleep");
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002250 if (waitTime == -1) {
2251 mWaitWorkCV.wait(mLock);
2252 } else {
2253 mWaitWorkCV.waitRelative(mLock, waitTime);
2254 }
Eric Laurent59a89232014-06-08 14:14:17 -07002255 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002256 }
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002257 // release delayed commands wake lock before quitting
2258 if (!mAudioCommands.isEmpty()) {
2259 release_wake_lock(mName.string());
2260 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002261 mLock.unlock();
2262 return false;
2263}
2264
2265status_t AudioPolicyService::AudioCommandThread::dump(int fd)
2266{
2267 const size_t SIZE = 256;
2268 char buffer[SIZE];
2269 String8 result;
2270
Mikhail Naganov12b716c2020-04-30 22:37:43 +00002271 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002272 if (!locked) {
2273 String8 result2(kCmdDeadlockedString);
2274 write(fd, result2.string(), result2.size());
2275 }
2276
2277 snprintf(buffer, SIZE, "- Commands:\n");
2278 result = String8(buffer);
2279 result.append(" Command Time Wait pParam\n");
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002280 for (size_t i = 0; i < mAudioCommands.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002281 mAudioCommands[i]->dump(buffer, SIZE);
2282 result.append(buffer);
2283 }
2284 result.append(" Last Command\n");
Eric Laurent0ede8922014-05-09 18:04:42 -07002285 if (mLastCommand != 0) {
2286 mLastCommand->dump(buffer, SIZE);
2287 result.append(buffer);
2288 } else {
2289 result.append(" none\n");
2290 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002291
2292 write(fd, result.string(), result.size());
2293
Mikhail Naganov12b716c2020-04-30 22:37:43 +00002294 dumpReleaseLock(mLock, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002295
2296 return NO_ERROR;
2297}
2298
Glenn Kastenfff6d712012-01-12 16:38:12 -08002299status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
Eric Laurentde070132010-07-13 04:45:46 -07002300 float volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002301 audio_io_handle_t output,
Eric Laurentde070132010-07-13 04:45:46 -07002302 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002303{
Eric Laurent0ede8922014-05-09 18:04:42 -07002304 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002305 command->mCommand = SET_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002306 sp<VolumeData> data = new VolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002307 data->mStream = stream;
2308 data->mVolume = volume;
2309 data->mIO = output;
2310 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002311 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002312 ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
Eric Laurentde070132010-07-13 04:45:46 -07002313 stream, volume, output);
Eric Laurent0ede8922014-05-09 18:04:42 -07002314 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002315}
2316
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002317status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
Dima Zavinfce7a472011-04-19 22:30:36 -07002318 const char *keyValuePairs,
Eric Laurentde070132010-07-13 04:45:46 -07002319 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002320{
Eric Laurent0ede8922014-05-09 18:04:42 -07002321 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002322 command->mCommand = SET_PARAMETERS;
Eric Laurent0ede8922014-05-09 18:04:42 -07002323 sp<ParametersData> data = new ParametersData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002324 data->mIO = ioHandle;
Dima Zavinfce7a472011-04-19 22:30:36 -07002325 data->mKeyValuePairs = String8(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002326 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 parameter string %s, io %d ,delay %d",
Dima Zavinfce7a472011-04-19 22:30:36 -07002329 keyValuePairs, ioHandle, delayMs);
Eric Laurent0ede8922014-05-09 18:04:42 -07002330 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002331}
2332
2333status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
2334{
Eric Laurent0ede8922014-05-09 18:04:42 -07002335 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002336 command->mCommand = SET_VOICE_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002337 sp<VoiceVolumeData> data = new VoiceVolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002338 data->mVolume = volume;
2339 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002340 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002341 ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
Eric Laurent0ede8922014-05-09 18:04:42 -07002342 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002343}
2344
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002345void AudioPolicyService::AudioCommandThread::setEffectSuspendedCommand(int effectId,
2346 audio_session_t sessionId,
2347 bool suspended)
2348{
2349 sp<AudioCommand> command = new AudioCommand();
2350 command->mCommand = SET_EFFECT_SUSPENDED;
2351 sp<SetEffectSuspendedData> data = new SetEffectSuspendedData();
2352 data->mEffectId = effectId;
2353 data->mSessionId = sessionId;
2354 data->mSuspended = suspended;
2355 command->mParam = data;
2356 ALOGV("AudioCommandThread() adding set suspended effectId %d sessionId %d suspended %d",
2357 effectId, sessionId, suspended);
2358 sendCommand(command);
2359}
2360
2361
Eric Laurentd7fe0862018-07-14 16:48:01 -07002362void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002363{
Eric Laurent0ede8922014-05-09 18:04:42 -07002364 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002365 command->mCommand = STOP_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002366 sp<StopOutputData> data = new StopOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002367 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002368 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002369 ALOGV("AudioCommandThread() adding stop output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002370 sendCommand(command);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002371}
2372
Eric Laurentd7fe0862018-07-14 16:48:01 -07002373void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002374{
Eric Laurent0ede8922014-05-09 18:04:42 -07002375 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002376 command->mCommand = RELEASE_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002377 sp<ReleaseOutputData> data = new ReleaseOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002378 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002379 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002380 ALOGV("AudioCommandThread() adding release output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002381 sendCommand(command);
2382}
2383
Eric Laurent951f4552014-05-20 10:48:17 -07002384status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
2385 const struct audio_patch *patch,
2386 audio_patch_handle_t *handle,
2387 int delayMs)
2388{
2389 status_t status = NO_ERROR;
2390
2391 sp<AudioCommand> command = new AudioCommand();
2392 command->mCommand = CREATE_AUDIO_PATCH;
2393 CreateAudioPatchData *data = new CreateAudioPatchData();
2394 data->mPatch = *patch;
2395 data->mHandle = *handle;
2396 command->mParam = data;
2397 command->mWaitStatus = true;
2398 ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
2399 status = sendCommand(command, delayMs);
2400 if (status == NO_ERROR) {
2401 *handle = data->mHandle;
2402 }
2403 return status;
2404}
2405
2406status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
2407 int delayMs)
2408{
2409 sp<AudioCommand> command = new AudioCommand();
2410 command->mCommand = RELEASE_AUDIO_PATCH;
2411 ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
2412 data->mHandle = handle;
2413 command->mParam = data;
2414 command->mWaitStatus = true;
2415 ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
2416 return sendCommand(command, delayMs);
2417}
2418
Eric Laurentb52c1522014-05-20 11:27:36 -07002419void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
2420{
2421 sp<AudioCommand> command = new AudioCommand();
2422 command->mCommand = UPDATE_AUDIOPORT_LIST;
2423 ALOGV("AudioCommandThread() adding update audio port list");
2424 sendCommand(command);
2425}
2426
Eric Laurented726cc2021-07-01 14:26:41 +02002427void AudioPolicyService::AudioCommandThread::updateUidStatesCommand()
2428{
2429 sp<AudioCommand> command = new AudioCommand();
2430 command->mCommand = UPDATE_UID_STATES;
2431 ALOGV("AudioCommandThread() adding update UID states");
2432 sendCommand(command);
2433}
2434
Eric Laurentb52c1522014-05-20 11:27:36 -07002435void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
2436{
2437 sp<AudioCommand>command = new AudioCommand();
2438 command->mCommand = UPDATE_AUDIOPATCH_LIST;
2439 ALOGV("AudioCommandThread() adding update audio patch list");
2440 sendCommand(command);
2441}
2442
François Gaffiecfe17322018-11-07 13:41:29 +01002443void AudioPolicyService::AudioCommandThread::changeAudioVolumeGroupCommand(volume_group_t group,
2444 int flags)
2445{
2446 sp<AudioCommand>command = new AudioCommand();
2447 command->mCommand = CHANGED_AUDIOVOLUMEGROUP;
2448 AudioVolumeGroupData *data= new AudioVolumeGroupData();
2449 data->mGroup = group;
2450 data->mFlags = flags;
2451 command->mParam = data;
2452 ALOGV("AudioCommandThread() adding audio volume group changed");
2453 sendCommand(command);
2454}
2455
Eric Laurente1715a42014-05-20 11:30:42 -07002456status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
2457 const struct audio_port_config *config, int delayMs)
2458{
2459 sp<AudioCommand> command = new AudioCommand();
2460 command->mCommand = SET_AUDIOPORT_CONFIG;
2461 SetAudioPortConfigData *data = new SetAudioPortConfigData();
2462 data->mConfig = *config;
2463 command->mParam = data;
2464 command->mWaitStatus = true;
2465 ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
2466 return sendCommand(command, delayMs);
2467}
2468
Jean-Michel Trivide801052015-04-14 19:10:14 -07002469void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002470 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -07002471{
2472 sp<AudioCommand> command = new AudioCommand();
2473 command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
2474 DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
2475 data->mRegId = regId;
2476 data->mState = state;
2477 command->mParam = data;
2478 ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
2479 regId.string(), state);
2480 sendCommand(command);
2481}
2482
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002483void AudioPolicyService::AudioCommandThread::recordingConfigurationUpdateCommand(
Eric Laurenta9f86652018-11-28 17:23:11 -08002484 int event,
2485 const record_client_info_t *clientInfo,
2486 const audio_config_base_t *clientConfig,
2487 std::vector<effect_descriptor_t> clientEffects,
2488 const audio_config_base_t *deviceConfig,
2489 std::vector<effect_descriptor_t> effects,
2490 audio_patch_handle_t patchHandle,
2491 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002492{
2493 sp<AudioCommand>command = new AudioCommand();
2494 command->mCommand = RECORDING_CONFIGURATION_UPDATE;
2495 RecordingConfigurationUpdateData *data = new RecordingConfigurationUpdateData();
2496 data->mEvent = event;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002497 data->mClientInfo = *clientInfo;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002498 data->mClientConfig = *clientConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002499 data->mClientEffects = clientEffects;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002500 data->mDeviceConfig = *deviceConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002501 data->mEffects = effects;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002502 data->mPatchHandle = patchHandle;
Eric Laurenta9f86652018-11-28 17:23:11 -08002503 data->mSource = source;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002504 command->mParam = data;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002505 ALOGV("AudioCommandThread() adding recording configuration update event %d, source %d uid %u",
2506 event, clientInfo->source, clientInfo->uid);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002507 sendCommand(command);
2508}
2509
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002510void AudioPolicyService::AudioCommandThread::audioModulesUpdateCommand()
2511{
2512 sp<AudioCommand> command = new AudioCommand();
2513 command->mCommand = AUDIO_MODULES_UPDATE;
2514 sendCommand(command);
2515}
2516
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002517void AudioPolicyService::AudioCommandThread::routingChangedCommand()
2518{
2519 sp<AudioCommand>command = new AudioCommand();
2520 command->mCommand = ROUTING_UPDATED;
2521 ALOGV("AudioCommandThread() adding routing update");
2522 sendCommand(command);
2523}
2524
Eric Laurent81dd0f52021-07-05 11:54:40 +02002525void AudioPolicyService::AudioCommandThread::checkSpatializerCommand()
2526{
2527 sp<AudioCommand>command = new AudioCommand();
Eric Laurent15903592022-02-24 20:44:36 +01002528 command->mCommand = CHECK_SPATIALIZER_OUTPUT;
Eric Laurent81dd0f52021-07-05 11:54:40 +02002529 ALOGV("AudioCommandThread() adding check spatializer");
2530 sendCommand(command);
2531}
2532
Eric Laurent15903592022-02-24 20:44:36 +01002533void AudioPolicyService::AudioCommandThread::updateActiveSpatializerTracksCommand()
2534{
2535 sp<AudioCommand>command = new AudioCommand();
2536 command->mCommand = UPDATE_ACTIVE_SPATIALIZER_TRACKS;
2537 ALOGV("AudioCommandThread() adding update active spatializer tracks");
2538 sendCommand(command);
2539}
2540
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002541void AudioPolicyService::AudioCommandThread::volRangeInitReqCommand()
2542{
2543 sp<AudioCommand>command = new AudioCommand();
2544 command->mCommand = VOL_RANGE_INIT_REQUEST;
2545 ALOGV("AudioCommandThread() adding volume range init request");
2546 sendCommand(command);
2547}
2548
Eric Laurent0ede8922014-05-09 18:04:42 -07002549status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
2550{
2551 {
2552 Mutex::Autolock _l(mLock);
2553 insertCommand_l(command, delayMs);
2554 mWaitWorkCV.signal();
2555 }
2556 Mutex::Autolock _l(command->mLock);
2557 while (command->mWaitStatus) {
2558 nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
2559 if (command->mCond.waitRelative(command->mLock, timeOutNs) != NO_ERROR) {
2560 command->mStatus = TIMED_OUT;
2561 command->mWaitStatus = false;
2562 }
2563 }
2564 return command->mStatus;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002565}
2566
Mathias Agopian65ab4712010-07-14 17:59:35 -07002567// insertCommand_l() must be called with mLock held
Eric Laurent0ede8922014-05-09 18:04:42 -07002568void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002569{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002570 ssize_t i; // not size_t because i will count down to -1
Eric Laurent0ede8922014-05-09 18:04:42 -07002571 Vector < sp<AudioCommand> > removedCommands;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002572 command->mTime = systemTime() + milliseconds(delayMs);
2573
2574 // acquire wake lock to make sure delayed commands are processed
Eric Laurentbfb1b832013-01-07 09:53:42 -08002575 if (mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002576 acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.string());
2577 }
2578
2579 // check same pending commands with later time stamps and eliminate them
Ivan Lozano5ff158f2017-10-30 09:06:24 -07002580 for (i = (ssize_t)mAudioCommands.size()-1; i >= 0; i--) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002581 sp<AudioCommand> command2 = mAudioCommands[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07002582 // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
2583 if (command2->mTime <= command->mTime) break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002584
2585 // create audio patch or release audio patch commands are equivalent
2586 // with regard to filtering
2587 if ((command->mCommand == CREATE_AUDIO_PATCH) ||
2588 (command->mCommand == RELEASE_AUDIO_PATCH)) {
2589 if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
2590 (command2->mCommand != RELEASE_AUDIO_PATCH)) {
2591 continue;
2592 }
2593 } else if (command2->mCommand != command->mCommand) continue;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002594
2595 switch (command->mCommand) {
2596 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002597 ParametersData *data = (ParametersData *)command->mParam.get();
2598 ParametersData *data2 = (ParametersData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002599 if (data->mIO != data2->mIO) break;
Steve Block3856b092011-10-20 11:56:00 +01002600 ALOGV("Comparing parameter command %s to new command %s",
Eric Laurentde070132010-07-13 04:45:46 -07002601 data2->mKeyValuePairs.string(), data->mKeyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002602 AudioParameter param = AudioParameter(data->mKeyValuePairs);
2603 AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
2604 for (size_t j = 0; j < param.size(); j++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002605 String8 key;
2606 String8 value;
2607 param.getAt(j, key, value);
2608 for (size_t k = 0; k < param2.size(); k++) {
2609 String8 key2;
2610 String8 value2;
2611 param2.getAt(k, key2, value2);
2612 if (key2 == key) {
2613 param2.remove(key2);
2614 ALOGV("Filtering out parameter %s", key2.string());
2615 break;
2616 }
2617 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002618 }
2619 // if all keys have been filtered out, remove the command.
2620 // otherwise, update the key value pairs
2621 if (param2.size() == 0) {
2622 removedCommands.add(command2);
2623 } else {
2624 data2->mKeyValuePairs = param2.toString();
2625 }
Eric Laurent21e54562013-09-23 12:08:05 -07002626 command->mTime = command2->mTime;
2627 // force delayMs to non 0 so that code below does not request to wait for
2628 // command status as the command is now delayed
2629 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002630 } break;
2631
2632 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002633 VolumeData *data = (VolumeData *)command->mParam.get();
2634 VolumeData *data2 = (VolumeData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002635 if (data->mIO != data2->mIO) break;
2636 if (data->mStream != data2->mStream) break;
Steve Block3856b092011-10-20 11:56:00 +01002637 ALOGV("Filtering out volume command on output %d for stream %d",
Eric Laurentde070132010-07-13 04:45:46 -07002638 data->mIO, data->mStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002639 removedCommands.add(command2);
Eric Laurent21e54562013-09-23 12:08:05 -07002640 command->mTime = command2->mTime;
2641 // force delayMs to non 0 so that code below does not request to wait for
2642 // command status as the command is now delayed
2643 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002644 } break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002645
Eric Laurentbaf35fe2016-07-27 15:36:53 -07002646 case SET_VOICE_VOLUME: {
2647 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
2648 VoiceVolumeData *data2 = (VoiceVolumeData *)command2->mParam.get();
2649 ALOGV("Filtering out voice volume command value %f replaced by %f",
2650 data2->mVolume, data->mVolume);
2651 removedCommands.add(command2);
2652 command->mTime = command2->mTime;
2653 // force delayMs to non 0 so that code below does not request to wait for
2654 // command status as the command is now delayed
2655 delayMs = 1;
2656 } break;
2657
Eric Laurente45b48a2014-09-04 16:40:57 -07002658 case CREATE_AUDIO_PATCH:
2659 case RELEASE_AUDIO_PATCH: {
2660 audio_patch_handle_t handle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002661 struct audio_patch patch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002662 if (command->mCommand == CREATE_AUDIO_PATCH) {
2663 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002664 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002665 } else {
2666 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
Mikhail Naganov7be71d22018-05-23 16:51:46 -07002667 memset(&patch, 0, sizeof(patch));
Eric Laurente45b48a2014-09-04 16:40:57 -07002668 }
2669 audio_patch_handle_t handle2;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002670 struct audio_patch patch2;
Eric Laurente45b48a2014-09-04 16:40:57 -07002671 if (command2->mCommand == CREATE_AUDIO_PATCH) {
2672 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002673 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002674 } else {
2675 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
Glenn Kastenf60b6b62015-07-06 10:53:26 -07002676 memset(&patch2, 0, sizeof(patch2));
Eric Laurente45b48a2014-09-04 16:40:57 -07002677 }
2678 if (handle != handle2) break;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002679 /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
2680 same output. */
2681 if( (command->mCommand == CREATE_AUDIO_PATCH) &&
2682 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
2683 bool isOutputDiff = false;
2684 if (patch.num_sources == patch2.num_sources) {
2685 for (unsigned count = 0; count < patch.num_sources; count++) {
2686 if (patch.sources[count].id != patch2.sources[count].id) {
2687 isOutputDiff = true;
2688 break;
2689 }
2690 }
2691 if (isOutputDiff)
2692 break;
2693 }
2694 }
Eric Laurente45b48a2014-09-04 16:40:57 -07002695 ALOGV("Filtering out %s audio patch command for handle %d",
2696 (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
2697 removedCommands.add(command2);
2698 command->mTime = command2->mTime;
2699 // force delayMs to non 0 so that code below does not request to wait for
2700 // command status as the command is now delayed
2701 delayMs = 1;
2702 } break;
2703
Jean-Michel Trivide801052015-04-14 19:10:14 -07002704 case DYN_POLICY_MIX_STATE_UPDATE: {
2705
2706 } break;
2707
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002708 case RECORDING_CONFIGURATION_UPDATE: {
2709
2710 } break;
2711
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002712 case ROUTING_UPDATED: {
2713
2714 } break;
2715
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002716 case VOL_RANGE_INIT_REQUEST: {
2717 // command may come from different requests, do not filter
2718 } break;
2719
Mathias Agopian65ab4712010-07-14 17:59:35 -07002720 default:
2721 break;
2722 }
2723 }
2724
2725 // remove filtered commands
2726 for (size_t j = 0; j < removedCommands.size(); j++) {
2727 // removed commands always have time stamps greater than current command
2728 for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002729 if (mAudioCommands[k].get() == removedCommands[j].get()) {
Steve Block3856b092011-10-20 11:56:00 +01002730 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002731 mAudioCommands.removeAt(k);
2732 break;
2733 }
2734 }
2735 }
2736 removedCommands.clear();
2737
Eric Laurentaa79bef2015-01-15 14:33:51 -08002738 // Disable wait for status if delay is not 0.
2739 // Except for create audio patch command because the returned patch handle
2740 // is needed by audio policy manager
2741 if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
Eric Laurentcec4abb2012-07-03 12:23:02 -07002742 command->mWaitStatus = false;
2743 }
Eric Laurentcec4abb2012-07-03 12:23:02 -07002744
Mathias Agopian65ab4712010-07-14 17:59:35 -07002745 // insert command at the right place according to its time stamp
Eric Laurent1e693b52014-07-09 15:03:28 -07002746 ALOGV("inserting command: %d at index %zd, num commands %zu",
2747 command->mCommand, i+1, mAudioCommands.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002748 mAudioCommands.insertAt(command, i + 1);
2749}
2750
2751void AudioPolicyService::AudioCommandThread::exit()
2752{
Steve Block3856b092011-10-20 11:56:00 +01002753 ALOGV("AudioCommandThread::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002754 {
2755 AutoMutex _l(mLock);
2756 requestExit();
2757 mWaitWorkCV.signal();
2758 }
Zach Janga754b4f2015-10-27 01:29:34 +00002759 // Note that we can call it from the thread loop if all other references have been released
2760 // but it will safely return WOULD_BLOCK in this case
Mathias Agopian65ab4712010-07-14 17:59:35 -07002761 requestExitAndWait();
2762}
2763
2764void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
2765{
2766 snprintf(buffer, size, " %02d %06d.%03d %01u %p\n",
2767 mCommand,
2768 (int)ns2s(mTime),
2769 (int)ns2ms(mTime)%1000,
2770 mWaitStatus,
Eric Laurent0ede8922014-05-09 18:04:42 -07002771 mParam.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002772}
2773
Dima Zavinfce7a472011-04-19 22:30:36 -07002774/******* helpers for the service_ops callbacks defined below *********/
2775void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
2776 const char *keyValuePairs,
2777 int delayMs)
2778{
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002779 mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
Dima Zavinfce7a472011-04-19 22:30:36 -07002780 delayMs);
2781}
2782
2783int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
2784 float volume,
2785 audio_io_handle_t output,
2786 int delayMs)
2787{
Glenn Kastenfff6d712012-01-12 16:38:12 -08002788 return (int)mAudioCommandThread->volumeCommand(stream, volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002789 output, delayMs);
Dima Zavinfce7a472011-04-19 22:30:36 -07002790}
2791
Dima Zavinfce7a472011-04-19 22:30:36 -07002792int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
2793{
2794 return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
2795}
2796
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002797void AudioPolicyService::setEffectSuspended(int effectId,
2798 audio_session_t sessionId,
2799 bool suspended)
2800{
2801 mAudioCommandThread->setEffectSuspendedCommand(effectId, sessionId, suspended);
2802}
2803
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002804Status AudioPolicyService::onNewAudioModulesAvailable()
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002805{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07002806 mOutputCommandThread->audioModulesUpdateCommand();
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002807 return Status::ok();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002808}
2809
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002810
Dima Zavinfce7a472011-04-19 22:30:36 -07002811extern "C" {
Eric Laurent2d388ec2014-03-07 13:25:54 -08002812audio_module_handle_t aps_load_hw_module(void *service __unused,
2813 const char *name);
2814audio_io_handle_t aps_open_output(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002815 audio_devices_t *pDevices,
2816 uint32_t *pSamplingRate,
2817 audio_format_t *pFormat,
2818 audio_channel_mask_t *pChannelMask,
2819 uint32_t *pLatencyMs,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002820 audio_output_flags_t flags);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002821
Eric Laurent2d388ec2014-03-07 13:25:54 -08002822audio_io_handle_t aps_open_output_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002823 audio_module_handle_t module,
2824 audio_devices_t *pDevices,
2825 uint32_t *pSamplingRate,
2826 audio_format_t *pFormat,
2827 audio_channel_mask_t *pChannelMask,
2828 uint32_t *pLatencyMs,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002829 audio_output_flags_t flags,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002830 const audio_offload_info_t *offloadInfo);
2831audio_io_handle_t aps_open_dup_output(void *service __unused,
Dima Zavinfce7a472011-04-19 22:30:36 -07002832 audio_io_handle_t output1,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002833 audio_io_handle_t output2);
2834int aps_close_output(void *service __unused, audio_io_handle_t output);
2835int aps_suspend_output(void *service __unused, audio_io_handle_t output);
2836int aps_restore_output(void *service __unused, audio_io_handle_t output);
2837audio_io_handle_t aps_open_input(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002838 audio_devices_t *pDevices,
2839 uint32_t *pSamplingRate,
2840 audio_format_t *pFormat,
2841 audio_channel_mask_t *pChannelMask,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002842 audio_in_acoustics_t acoustics __unused);
2843audio_io_handle_t aps_open_input_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002844 audio_module_handle_t module,
2845 audio_devices_t *pDevices,
2846 uint32_t *pSamplingRate,
2847 audio_format_t *pFormat,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002848 audio_channel_mask_t *pChannelMask);
2849int aps_close_input(void *service __unused, audio_io_handle_t input);
2850int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
Glenn Kastend848eb42016-03-08 13:42:11 -08002851int aps_move_effects(void *service __unused, audio_session_t session,
Dima Zavinfce7a472011-04-19 22:30:36 -07002852 audio_io_handle_t src_output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002853 audio_io_handle_t dst_output);
2854char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
2855 const char *keys);
2856void aps_set_parameters(void *service, audio_io_handle_t io_handle,
2857 const char *kv_pairs, int delay_ms);
2858int aps_set_stream_volume(void *service, audio_stream_type_t stream,
Dima Zavinfce7a472011-04-19 22:30:36 -07002859 float volume, audio_io_handle_t output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002860 int delay_ms);
Eric Laurent2d388ec2014-03-07 13:25:54 -08002861int aps_set_voice_volume(void *service, float volume, int delay_ms);
2862};
Dima Zavinfce7a472011-04-19 22:30:36 -07002863
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08002864} // namespace android