blob: 9b08044e8ad9f30d24c74a02247f6bba4cf4701a [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 Hungab7ef302018-05-15 19:35:29 -070042#include <mediautils/ServiceUtilities.h>
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -080043#include <mediautils/TimeCheck.h>
Michael Groovercfd28302018-12-11 19:16:46 -080044#include <sensorprivacy/SensorPrivacyManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045
Dima Zavin64760242011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070047#include <system/audio_policy.h>
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053048#include <AudioPolicyManager.h>
Mikhail Naganov61a4fac2016-10-13 14:44:18 -070049
Mathias Agopian65ab4712010-07-14 17:59:35 -070050namespace android {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -080051using binder::Status;
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
Glenn Kasten8dad0e32012-01-09 08:41:22 -080053static const char kDeadlockedString[] = "AudioPolicyService may be deadlocked\n";
54static const char kCmdDeadlockedString[] = "AudioPolicyService command thread may be deadlocked\n";
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053055static const char kAudioPolicyManagerCustomPath[] = "libaudiopolicymanagercustom.so";
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Mikhail Naganov959e2d02019-03-28 11:08:19 -070057static const int kDumpLockTimeoutNs = 1 * NANOS_PER_SECOND;
Mathias Agopian65ab4712010-07-14 17:59:35 -070058
Eric Laurent0ede8922014-05-09 18:04:42 -070059static const nsecs_t kAudioCommandTimeoutNs = seconds(3); // 3 seconds
Christer Fletcher5fa8c4b2013-01-18 15:27:03 +010060
Svet Ganovf4ddfef2018-01-16 07:37:58 -080061static const String16 sManageAudioPolicyPermission("android.permission.MANAGE_AUDIO_POLICY");
Dima Zavinfce7a472011-04-19 22:30:36 -070062
Mathias Agopian65ab4712010-07-14 17:59:35 -070063// ----------------------------------------------------------------------------
64
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053065static AudioPolicyInterface* createAudioPolicyManager(AudioPolicyClientInterface *clientInterface)
66{
67 AudioPolicyManager *apm = new AudioPolicyManager(clientInterface);
68 status_t status = apm->initialize();
69 if (status != NO_ERROR) {
70 delete apm;
71 apm = nullptr;
72 }
73 return apm;
74}
75
76static void destroyAudioPolicyManager(AudioPolicyInterface *interface)
77{
78 delete interface;
79}
80// ----------------------------------------------------------------------------
81
Mathias Agopian65ab4712010-07-14 17:59:35 -070082AudioPolicyService::AudioPolicyService()
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -070083 : BnAudioPolicyService(),
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -070084 mAudioPolicyManager(NULL),
85 mAudioPolicyClient(NULL),
86 mPhoneState(AUDIO_MODE_INVALID),
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053087 mCaptureStateNotifier(false),
88 mCreateAudioPolicyManager(createAudioPolicyManager),
89 mDestroyAudioPolicyManager(destroyAudioPolicyManager) {
90}
91
92void AudioPolicyService::loadAudioPolicyManager()
93{
94 mLibraryHandle = dlopen(kAudioPolicyManagerCustomPath, RTLD_NOW);
95 if (mLibraryHandle != nullptr) {
96 ALOGI("%s loading %s", __func__, kAudioPolicyManagerCustomPath);
97 mCreateAudioPolicyManager = reinterpret_cast<CreateAudioPolicyManagerInstance>
98 (dlsym(mLibraryHandle, "createAudioPolicyManager"));
99 const char *lastError = dlerror();
100 ALOGW_IF(mCreateAudioPolicyManager == nullptr, "%s createAudioPolicyManager is null %s",
101 __func__, lastError != nullptr ? lastError : "no error");
102
103 mDestroyAudioPolicyManager = reinterpret_cast<DestroyAudioPolicyManagerInstance>(
104 dlsym(mLibraryHandle, "destroyAudioPolicyManager"));
105 lastError = dlerror();
106 ALOGW_IF(mDestroyAudioPolicyManager == nullptr, "%s destroyAudioPolicyManager is null %s",
107 __func__, lastError != nullptr ? lastError : "no error");
108 if (mCreateAudioPolicyManager == nullptr || mDestroyAudioPolicyManager == nullptr){
109 unloadAudioPolicyManager();
110 LOG_ALWAYS_FATAL("could not find audiopolicymanager interface methods");
111 }
112 }
Eric Laurentf5ada6e2014-10-09 17:49:00 -0700113}
114
115void AudioPolicyService::onFirstRef()
116{
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700117 {
118 Mutex::Autolock _l(mLock);
Eric Laurent93575202011-01-18 18:39:02 -0800119
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700120 // start audio commands thread
121 mAudioCommandThread = new AudioCommandThread(String8("ApmAudio"), this);
122 // start output activity command thread
123 mOutputCommandThread = new AudioCommandThread(String8("ApmOutput"), this);
Eric Laurentdce54a12014-03-10 12:19:46 -0700124
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700125 mAudioPolicyClient = new AudioPolicyClient(this);
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530126
127 loadAudioPolicyManager();
128 mAudioPolicyManager = mCreateAudioPolicyManager(mAudioPolicyClient);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700129 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200130
bryant_liuba2b4392014-06-11 16:49:30 +0800131 // load audio processing modules
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000132 sp<AudioPolicyEffects> audioPolicyEffects = new AudioPolicyEffects();
133 sp<UidPolicy> uidPolicy = new UidPolicy(this);
134 sp<SensorPrivacyPolicy> sensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700135 {
136 Mutex::Autolock _l(mLock);
137 mAudioPolicyEffects = audioPolicyEffects;
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000138 mUidPolicy = uidPolicy;
139 mSensorPrivacyPolicy = sensorPrivacyPolicy;
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700140 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000141 uidPolicy->registerSelf();
142 sensorPrivacyPolicy->registerSelf();
Eric Laurentd66d7a12021-07-13 13:35:32 +0200143
Eric Laurent81dd0f52021-07-05 11:54:40 +0200144 // Create spatializer if supported
Eric Laurent52b0bd52021-09-27 15:25:40 +0200145 if (mAudioPolicyManager != nullptr) {
146 Mutex::Autolock _l(mLock);
147 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
148 AudioDeviceTypeAddrVector devices;
149 bool hasSpatializer = mAudioPolicyManager->canBeSpatialized(&attr, nullptr, devices);
150 if (hasSpatializer) {
151 mSpatializer = Spatializer::create(this);
152 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200153 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200154 AudioSystem::audioPolicyReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700155}
156
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530157void AudioPolicyService::unloadAudioPolicyManager()
158{
159 ALOGV("%s ", __func__);
160 if (mLibraryHandle != nullptr) {
161 dlclose(mLibraryHandle);
162 }
163 mLibraryHandle = nullptr;
164 mCreateAudioPolicyManager = nullptr;
165 mDestroyAudioPolicyManager = nullptr;
166}
167
Mathias Agopian65ab4712010-07-14 17:59:35 -0700168AudioPolicyService::~AudioPolicyService()
169{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700170 mAudioCommandThread->exit();
Eric Laurent657ff612014-05-07 11:58:24 -0700171 mOutputCommandThread->exit();
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700172
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530173 mDestroyAudioPolicyManager(mAudioPolicyManager);
174 unloadAudioPolicyManager();
175
Eric Laurentdce54a12014-03-10 12:19:46 -0700176 delete mAudioPolicyClient;
Eric Laurentb52c1522014-05-20 11:27:36 -0700177
178 mNotificationClients.clear();
bryant_liuba2b4392014-06-11 16:49:30 +0800179 mAudioPolicyEffects.clear();
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800180
181 mUidPolicy->unregisterSelf();
Michael Groovercfd28302018-12-11 19:16:46 -0800182 mSensorPrivacyPolicy->unregisterSelf();
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000183
184 mUidPolicy.clear();
Michael Groovercfd28302018-12-11 19:16:46 -0800185 mSensorPrivacyPolicy.clear();
Eric Laurentb52c1522014-05-20 11:27:36 -0700186}
187
188// A notification client is always registered by AudioSystem when the client process
189// connects to AudioPolicyService.
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800190Status AudioPolicyService::registerClient(const sp<media::IAudioPolicyServiceClient>& client)
Eric Laurentb52c1522014-05-20 11:27:36 -0700191{
Eric Laurent12590252015-08-21 18:40:20 -0700192 if (client == 0) {
193 ALOGW("%s got NULL client", __FUNCTION__);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800194 return Status::ok();
Eric Laurent12590252015-08-21 18:40:20 -0700195 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800196 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700197
198 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800199 pid_t pid = IPCThreadState::self()->getCallingPid();
200 int64_t token = ((int64_t)uid<<32) | pid;
201
202 if (mNotificationClients.indexOfKey(token) < 0) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700203 sp<NotificationClient> notificationClient = new NotificationClient(this,
204 client,
luochaojiang908c7d72018-06-21 14:58:04 +0800205 uid,
206 pid);
207 ALOGV("registerClient() client %p, uid %d pid %d", client.get(), uid, pid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700208
luochaojiang908c7d72018-06-21 14:58:04 +0800209 mNotificationClients.add(token, notificationClient);
Eric Laurentb52c1522014-05-20 11:27:36 -0700210
Marco Nelissenf8880202014-11-14 07:58:25 -0800211 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurentb52c1522014-05-20 11:27:36 -0700212 binder->linkToDeath(notificationClient);
213 }
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800214 return Status::ok();
Eric Laurentb52c1522014-05-20 11:27:36 -0700215}
216
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800217Status AudioPolicyService::setAudioPortCallbacksEnabled(bool enabled)
Eric Laurente8726fe2015-06-26 09:39:24 -0700218{
219 Mutex::Autolock _l(mNotificationClientsLock);
220
221 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800222 pid_t pid = IPCThreadState::self()->getCallingPid();
223 int64_t token = ((int64_t)uid<<32) | pid;
224
225 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800226 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700227 }
luochaojiang908c7d72018-06-21 14:58:04 +0800228 mNotificationClients.valueFor(token)->setAudioPortCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800229 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700230}
231
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800232Status AudioPolicyService::setAudioVolumeGroupCallbacksEnabled(bool enabled)
François Gaffiecfe17322018-11-07 13:41:29 +0100233{
234 Mutex::Autolock _l(mNotificationClientsLock);
235
236 uid_t uid = IPCThreadState::self()->getCallingUid();
237 pid_t pid = IPCThreadState::self()->getCallingPid();
238 int64_t token = ((int64_t)uid<<32) | pid;
239
240 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800241 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100242 }
243 mNotificationClients.valueFor(token)->setAudioVolumeGroupCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800244 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100245}
246
Eric Laurentb52c1522014-05-20 11:27:36 -0700247// removeNotificationClient() is called when the client process dies.
luochaojiang908c7d72018-06-21 14:58:04 +0800248void AudioPolicyService::removeNotificationClient(uid_t uid, pid_t pid)
Eric Laurentb52c1522014-05-20 11:27:36 -0700249{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000250 bool hasSameUid = false;
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800251 {
252 Mutex::Autolock _l(mNotificationClientsLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800253 int64_t token = ((int64_t)uid<<32) | pid;
254 mNotificationClients.removeItem(token);
luochaojiang908c7d72018-06-21 14:58:04 +0800255 for (size_t i = 0; i < mNotificationClients.size(); i++) {
256 if (mNotificationClients.valueAt(i)->uid() == uid) {
257 hasSameUid = true;
258 break;
259 }
260 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000261 }
262 {
263 Mutex::Autolock _l(mLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800264 if (mAudioPolicyManager && !hasSameUid) {
Eric Laurent10b71232018-04-13 18:14:44 -0700265 // called from binder death notification: no need to clear caller identity
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700266 mAudioPolicyManager->releaseResourcesForUid(uid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700267 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800268 }
Eric Laurentb52c1522014-05-20 11:27:36 -0700269}
270
271void AudioPolicyService::onAudioPortListUpdate()
272{
273 mOutputCommandThread->updateAudioPortListCommand();
274}
275
276void AudioPolicyService::doOnAudioPortListUpdate()
277{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800278 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700279 for (size_t i = 0; i < mNotificationClients.size(); i++) {
280 mNotificationClients.valueAt(i)->onAudioPortListUpdate();
281 }
282}
283
284void AudioPolicyService::onAudioPatchListUpdate()
285{
286 mOutputCommandThread->updateAudioPatchListCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700287}
288
Eric Laurentb52c1522014-05-20 11:27:36 -0700289void AudioPolicyService::doOnAudioPatchListUpdate()
290{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800291 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700292 for (size_t i = 0; i < mNotificationClients.size(); i++) {
293 mNotificationClients.valueAt(i)->onAudioPatchListUpdate();
294 }
295}
296
François Gaffiecfe17322018-11-07 13:41:29 +0100297void AudioPolicyService::onAudioVolumeGroupChanged(volume_group_t group, int flags)
298{
299 mOutputCommandThread->changeAudioVolumeGroupCommand(group, flags);
300}
301
302void AudioPolicyService::doOnAudioVolumeGroupChanged(volume_group_t group, int flags)
303{
304 Mutex::Autolock _l(mNotificationClientsLock);
305 for (size_t i = 0; i < mNotificationClients.size(); i++) {
306 mNotificationClients.valueAt(i)->onAudioVolumeGroupChanged(group, flags);
307 }
308}
309
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700310void AudioPolicyService::onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700311{
312 ALOGV("AudioPolicyService::onDynamicPolicyMixStateUpdate(%s, %d)",
313 regId.string(), state);
314 mOutputCommandThread->dynamicPolicyMixStateUpdateCommand(regId, state);
315}
316
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700317void AudioPolicyService::doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700318{
319 Mutex::Autolock _l(mNotificationClientsLock);
320 for (size_t i = 0; i < mNotificationClients.size(); i++) {
321 mNotificationClients.valueAt(i)->onDynamicPolicyMixStateUpdate(regId, state);
322 }
323}
324
Eric Laurenta9f86652018-11-28 17:23:11 -0800325void AudioPolicyService::onRecordingConfigurationUpdate(
326 int event,
327 const record_client_info_t *clientInfo,
328 const audio_config_base_t *clientConfig,
329 std::vector<effect_descriptor_t> clientEffects,
330 const audio_config_base_t *deviceConfig,
331 std::vector<effect_descriptor_t> effects,
332 audio_patch_handle_t patchHandle,
333 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800334{
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800335 mOutputCommandThread->recordingConfigurationUpdateCommand(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800336 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800337}
338
Eric Laurenta9f86652018-11-28 17:23:11 -0800339void AudioPolicyService::doOnRecordingConfigurationUpdate(
340 int event,
341 const record_client_info_t *clientInfo,
342 const audio_config_base_t *clientConfig,
343 std::vector<effect_descriptor_t> clientEffects,
344 const audio_config_base_t *deviceConfig,
345 std::vector<effect_descriptor_t> effects,
346 audio_patch_handle_t patchHandle,
347 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800348{
349 Mutex::Autolock _l(mNotificationClientsLock);
350 for (size_t i = 0; i < mNotificationClients.size(); i++) {
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800351 mNotificationClients.valueAt(i)->onRecordingConfigurationUpdate(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800352 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800353 }
354}
355
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700356void AudioPolicyService::onRoutingUpdated()
357{
358 mOutputCommandThread->routingChangedCommand();
359}
360
361void AudioPolicyService::doOnRoutingUpdated()
362{
363 Mutex::Autolock _l(mNotificationClientsLock);
364 for (size_t i = 0; i < mNotificationClients.size(); i++) {
365 mNotificationClients.valueAt(i)->onRoutingUpdated();
366 }
367}
368
Eric Laurent81dd0f52021-07-05 11:54:40 +0200369void AudioPolicyService::onCheckSpatializer()
370{
371 Mutex::Autolock _l(mLock);
Eric Laurent39095982021-08-24 18:29:27 +0200372 onCheckSpatializer_l();
373}
374
375void AudioPolicyService::onCheckSpatializer_l()
376{
377 if (mSpatializer != nullptr) {
378 mOutputCommandThread->checkSpatializerCommand();
379 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200380}
381
382void AudioPolicyService::doOnCheckSpatializer()
383{
Eric Laurent39095982021-08-24 18:29:27 +0200384 Mutex::Autolock _l(mLock);
Eric Laurent81dd0f52021-07-05 11:54:40 +0200385
Eric Laurent39095982021-08-24 18:29:27 +0200386 if (mSpatializer != nullptr) {
Eric Laurent52b0bd52021-09-27 15:25:40 +0200387 // Note: mSpatializer != nullptr => mAudioPolicyManager != nullptr
Eric Laurent39095982021-08-24 18:29:27 +0200388 if (mSpatializer->getLevel() != media::SpatializationLevel::NONE) {
389 audio_io_handle_t currentOutput = mSpatializer->getOutput();
390 audio_io_handle_t newOutput;
391 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
392 audio_config_base_t config = mSpatializer->getAudioInConfig();
393 status_t status =
394 mAudioPolicyManager->getSpatializerOutput(&config, &attr, &newOutput);
Eric Laurentb4f42a92022-01-17 17:37:31 +0100395 ALOGV("%s currentOutput %d newOutput %d channel_mask %#x",
396 __func__, currentOutput, newOutput, config.channel_mask);
Eric Laurent39095982021-08-24 18:29:27 +0200397 if (status == NO_ERROR && currentOutput == newOutput) {
398 return;
399 }
400 mLock.unlock();
401 // It is OK to call detachOutput() is none is already attached.
402 mSpatializer->detachOutput();
403 if (status != NO_ERROR || newOutput == AUDIO_IO_HANDLE_NONE) {
Eric Laurent81dd0f52021-07-05 11:54:40 +0200404 mLock.lock();
Eric Laurent39095982021-08-24 18:29:27 +0200405 return;
406 }
407 status = mSpatializer->attachOutput(newOutput);
408 mLock.lock();
409 if (status != NO_ERROR) {
410 mAudioPolicyManager->releaseSpatializerOutput(newOutput);
411 }
412 } else if (mSpatializer->getLevel() == media::SpatializationLevel::NONE
413 && mSpatializer->getOutput() != AUDIO_IO_HANDLE_NONE) {
414 mLock.unlock();
415 audio_io_handle_t output = mSpatializer->detachOutput();
416 mLock.lock();
417 if (output != AUDIO_IO_HANDLE_NONE) {
418 mAudioPolicyManager->releaseSpatializerOutput(output);
Eric Laurent81dd0f52021-07-05 11:54:40 +0200419 }
420 }
421 }
422}
423
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800424status_t AudioPolicyService::clientCreateAudioPatch(const struct audio_patch *patch,
425 audio_patch_handle_t *handle,
426 int delayMs)
427{
428 return mAudioCommandThread->createAudioPatchCommand(patch, handle, delayMs);
429}
430
431status_t AudioPolicyService::clientReleaseAudioPatch(audio_patch_handle_t handle,
432 int delayMs)
433{
434 return mAudioCommandThread->releaseAudioPatchCommand(handle, delayMs);
435}
436
Eric Laurente1715a42014-05-20 11:30:42 -0700437status_t AudioPolicyService::clientSetAudioPortConfig(const struct audio_port_config *config,
438 int delayMs)
439{
440 return mAudioCommandThread->setAudioPortConfigCommand(config, delayMs);
441}
442
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800443AudioPolicyService::NotificationClient::NotificationClient(
444 const sp<AudioPolicyService>& service,
445 const sp<media::IAudioPolicyServiceClient>& client,
446 uid_t uid,
447 pid_t pid)
luochaojiang908c7d72018-06-21 14:58:04 +0800448 : mService(service), mUid(uid), mPid(pid), mAudioPolicyServiceClient(client),
François Gaffiecfe17322018-11-07 13:41:29 +0100449 mAudioPortCallbacksEnabled(false), mAudioVolumeGroupCallbacksEnabled(false)
Eric Laurentb52c1522014-05-20 11:27:36 -0700450{
451}
452
453AudioPolicyService::NotificationClient::~NotificationClient()
454{
455}
456
457void AudioPolicyService::NotificationClient::binderDied(const wp<IBinder>& who __unused)
458{
459 sp<NotificationClient> keep(this);
460 sp<AudioPolicyService> service = mService.promote();
461 if (service != 0) {
luochaojiang908c7d72018-06-21 14:58:04 +0800462 service->removeNotificationClient(mUid, mPid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700463 }
464}
465
466void AudioPolicyService::NotificationClient::onAudioPortListUpdate()
467{
Eric Laurente8726fe2015-06-26 09:39:24 -0700468 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700469 mAudioPolicyServiceClient->onAudioPortListUpdate();
470 }
471}
472
473void AudioPolicyService::NotificationClient::onAudioPatchListUpdate()
474{
Eric Laurente8726fe2015-06-26 09:39:24 -0700475 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700476 mAudioPolicyServiceClient->onAudioPatchListUpdate();
477 }
478}
Eric Laurent57dae992011-07-24 13:36:09 -0700479
Pattydd807582021-11-04 21:01:03 +0800480void AudioPolicyService::NotificationClient::onAudioVolumeGroupChanged(volume_group_t group,
François Gaffiecfe17322018-11-07 13:41:29 +0100481 int flags)
482{
483 if (mAudioPolicyServiceClient != 0 && mAudioVolumeGroupCallbacksEnabled) {
484 mAudioPolicyServiceClient->onAudioVolumeGroupChanged(group, flags);
485 }
486}
487
488
Jean-Michel Trivide801052015-04-14 19:10:14 -0700489void AudioPolicyService::NotificationClient::onDynamicPolicyMixStateUpdate(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700490 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700491{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700492 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800493 mAudioPolicyServiceClient->onDynamicPolicyMixStateUpdate(
494 legacy2aidl_String8_string(regId).value(), state);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800495 }
496}
497
498void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate(
Eric Laurenta9f86652018-11-28 17:23:11 -0800499 int event,
500 const record_client_info_t *clientInfo,
501 const audio_config_base_t *clientConfig,
502 std::vector<effect_descriptor_t> clientEffects,
503 const audio_config_base_t *deviceConfig,
504 std::vector<effect_descriptor_t> effects,
505 audio_patch_handle_t patchHandle,
506 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800507{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700508 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800509 status_t status = [&]() -> status_t {
510 int32_t eventAidl = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(event));
511 media::RecordClientInfo clientInfoAidl = VALUE_OR_RETURN_STATUS(
512 legacy2aidl_record_client_info_t_RecordClientInfo(*clientInfo));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700513 AudioConfigBase clientConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700514 legacy2aidl_audio_config_base_t_AudioConfigBase(
515 *clientConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800516 std::vector<media::EffectDescriptor> clientEffectsAidl = VALUE_OR_RETURN_STATUS(
517 convertContainer<std::vector<media::EffectDescriptor>>(
518 clientEffects,
519 legacy2aidl_effect_descriptor_t_EffectDescriptor));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700520 AudioConfigBase deviceConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700521 legacy2aidl_audio_config_base_t_AudioConfigBase(
522 *deviceConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800523 std::vector<media::EffectDescriptor> effectsAidl = VALUE_OR_RETURN_STATUS(
524 convertContainer<std::vector<media::EffectDescriptor>>(
525 effects,
526 legacy2aidl_effect_descriptor_t_EffectDescriptor));
527 int32_t patchHandleAidl = VALUE_OR_RETURN_STATUS(
528 legacy2aidl_audio_patch_handle_t_int32_t(patchHandle));
Mikhail Naganovddceecc2021-09-03 13:58:56 -0700529 media::audio::common::AudioSource sourceAidl = VALUE_OR_RETURN_STATUS(
530 legacy2aidl_audio_source_t_AudioSource(source));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800531 return aidl_utils::statusTFromBinderStatus(
532 mAudioPolicyServiceClient->onRecordingConfigurationUpdate(eventAidl,
533 clientInfoAidl,
534 clientConfigAidl,
535 clientEffectsAidl,
536 deviceConfigAidl,
537 effectsAidl,
538 patchHandleAidl,
539 sourceAidl));
540 }();
541 ALOGW_IF(status != OK, "onRecordingConfigurationUpdate() failed: %d", status);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700542 }
543}
544
Eric Laurente8726fe2015-06-26 09:39:24 -0700545void AudioPolicyService::NotificationClient::setAudioPortCallbacksEnabled(bool enabled)
546{
547 mAudioPortCallbacksEnabled = enabled;
548}
549
François Gaffiecfe17322018-11-07 13:41:29 +0100550void AudioPolicyService::NotificationClient::setAudioVolumeGroupCallbacksEnabled(bool enabled)
551{
552 mAudioVolumeGroupCallbacksEnabled = enabled;
553}
Eric Laurente8726fe2015-06-26 09:39:24 -0700554
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700555void AudioPolicyService::NotificationClient::onRoutingUpdated()
556{
557 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
558 mAudioPolicyServiceClient->onRoutingUpdated();
559 }
560}
561
Mathias Agopian65ab4712010-07-14 17:59:35 -0700562void AudioPolicyService::binderDied(const wp<IBinder>& who) {
Glenn Kasten411e4472012-11-02 10:00:06 -0700563 ALOGW("binderDied() %p, calling pid %d", who.unsafe_get(),
Eric Laurentde070132010-07-13 04:45:46 -0700564 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700565}
566
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000567static bool dumpTryLock(Mutex& mutex) ACQUIRE(mutex) NO_THREAD_SAFETY_ANALYSIS
Mathias Agopian65ab4712010-07-14 17:59:35 -0700568{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000569 return mutex.timedLock(kDumpLockTimeoutNs) == NO_ERROR;
570}
571
572static void dumpReleaseLock(Mutex& mutex, bool locked) RELEASE(mutex) NO_THREAD_SAFETY_ANALYSIS
573{
574 if (locked) mutex.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700575}
576
577status_t AudioPolicyService::dumpInternals(int fd)
578{
579 const size_t SIZE = 256;
580 char buffer[SIZE];
581 String8 result;
582
Eric Laurentdce54a12014-03-10 12:19:46 -0700583 snprintf(buffer, SIZE, "AudioPolicyManager: %p\n", mAudioPolicyManager);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700584 result.append(buffer);
585 snprintf(buffer, SIZE, "Command Thread: %p\n", mAudioCommandThread.get());
586 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700587
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000588 snprintf(buffer, SIZE, "Supported System Usages:\n ");
Hayden Gomes524159d2019-12-23 14:41:47 -0800589 result.append(buffer);
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000590 std::stringstream msg;
591 size_t i = 0;
592 for (auto usage : mSupportedSystemUsages) {
593 if (i++ != 0) msg << ", ";
594 if (const char* strUsage = audio_usage_to_string(usage); strUsage) {
595 msg << strUsage;
596 } else {
597 msg << usage << " (unknown)";
598 }
Hayden Gomes524159d2019-12-23 14:41:47 -0800599 }
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000600 if (i == 0) {
601 msg << "None";
602 }
603 msg << std::endl;
604 result.append(msg.str().c_str());
Hayden Gomes524159d2019-12-23 14:41:47 -0800605
Mathias Agopian65ab4712010-07-14 17:59:35 -0700606 write(fd, result.string(), result.size());
Oscar Azucena829d90d2022-01-28 17:17:56 -0800607
608 mUidPolicy->dumpInternals(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700609 return NO_ERROR;
610}
611
Eric Laurente8c8b432018-10-17 10:08:02 -0700612void AudioPolicyService::updateUidStates()
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800613{
Eric Laurente8c8b432018-10-17 10:08:02 -0700614 Mutex::Autolock _l(mLock);
615 updateUidStates_l();
616}
617
618void AudioPolicyService::updateUidStates_l()
619{
Eric Laurent4eb58f12018-12-07 16:41:02 -0800620// Go over all active clients and allow capture (does not force silence) in the
621// following cases:
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800622// The client is in the active assistant list
623// AND is TOP
624// AND an accessibility service is TOP
625// AND source is either VOICE_RECOGNITION OR HOTWORD
626// OR there is no active privacy sensitive capture or call
627// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
628// AND source is VOICE_RECOGNITION OR HOTWORD
629// The client is an assistant AND active assistant is not being used
Evan Severson1f700cd2021-02-10 13:10:37 -0800630// AND an accessibility service is on TOP or a RTT call is active
Eric Laurent589171c2019-07-25 18:04:29 -0700631// AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800632// OR there is no active privacy sensitive capture or call
Evan Severson1f700cd2021-02-10 13:10:37 -0800633// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800634// AND is TOP most recent assistant and uses VOICE_RECOGNITION or HOTWORD
635// OR there is no top recent assistant and source is HOTWORD
Evan Severson1f700cd2021-02-10 13:10:37 -0800636// OR The client is an accessibility service
637// AND Is on TOP
638// AND the source is VOICE_RECOGNITION or HOTWORD
639// OR The assistant is not on TOP
Eric Laurent589171c2019-07-25 18:04:29 -0700640// AND there is no active privacy sensitive capture or call
641// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Evan Severson1f700cd2021-02-10 13:10:37 -0800642// AND is on TOP
643// AND the source is VOICE_RECOGNITION or HOTWORD
644// OR the client source is virtual (remote submix, call audio TX or RX...)
645// OR the client source is HOTWORD
646// AND is on TOP
647// OR all active clients are using HOTWORD source
648// AND no call is active
649// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
650// OR the client is the current InputMethodService
651// AND a RTT call is active AND the source is VOICE_RECOGNITION
652// OR Any client
653// AND The assistant is not on TOP
654// AND is on TOP or latest started
655// AND there is no active privacy sensitive capture or call
656// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4eb58f12018-12-07 16:41:02 -0800657
Eric Laurent4e947da2019-10-17 15:24:06 -0700658
Eric Laurent4eb58f12018-12-07 16:41:02 -0800659 sp<AudioRecordClient> topActive;
660 sp<AudioRecordClient> latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800661 sp<AudioRecordClient> topSensitiveActive;
Eric Laurentb809a752020-06-29 09:53:13 -0700662 sp<AudioRecordClient> latestSensitiveActiveOrComm;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800663 sp<AudioRecordClient> latestActiveAssistant;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700664
Eric Laurenta46bedb2018-12-07 18:01:26 -0800665 nsecs_t topStartNs = 0;
666 nsecs_t latestStartNs = 0;
Eric Laurentc21d5692020-02-25 10:24:36 -0800667 nsecs_t topSensitiveStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800668 nsecs_t latestSensitiveStartNs = 0;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800669 nsecs_t latestAssistantStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800670 bool isA11yOnTop = mUidPolicy->isA11yOnTop();
671 bool isAssistantOnTop = false;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800672 bool useActiveAssistantList = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800673 bool isSensitiveActive = false;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700674 bool isInCall = mPhoneState == AUDIO_MODE_IN_CALL;
Eric Laurentc21d5692020-02-25 10:24:36 -0800675 bool isInCommunication = mPhoneState == AUDIO_MODE_IN_COMMUNICATION;
676 bool rttCallActive = (isInCall || isInCommunication)
Eric Laurent6ede98f2019-06-11 14:50:30 -0700677 && mUidPolicy->isRttEnabled();
Eric Laurent4e947da2019-10-17 15:24:06 -0700678 bool onlyHotwordActive = true;
Eric Laurentb809a752020-06-29 09:53:13 -0700679 bool isPhoneStateOwnerActive = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800680
Michael Groovercfd28302018-12-11 19:16:46 -0800681 // if Sensor Privacy is enabled then all recordings should be silenced.
682 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
683 silenceAllRecordings_l();
684 return;
685 }
686
Eric Laurente8c8b432018-10-17 10:08:02 -0700687 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
688 sp<AudioRecordClient> current = mAudioRecordClients[i];
Svet Ganov33761132021-05-13 22:51:08 +0000689 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
690 current->attributionSource.uid));
Evan Severson1f700cd2021-02-10 13:10:37 -0800691 if (!current->active) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700692 continue;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800693 }
Eric Laurent1ff16a72019-03-14 18:35:04 -0700694
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700695 app_state_t appState = apmStatFromAmState(mUidPolicy->getUidState(currentUid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700696 // clients which app is in IDLE state are not eligible for top active or
697 // latest active
698 if (appState == APP_STATE_IDLE) {
699 continue;
700 }
701
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700702 bool isAccessibility = mUidPolicy->isA11yUid(currentUid);
Eric Laurent14a88632020-07-16 12:28:30 -0700703 // Clients capturing for Accessibility services or virtual sources are not considered
Eric Laurentc21d5692020-02-25 10:24:36 -0800704 // for top or latest active to avoid masking regular clients started before
Eric Laurent14a88632020-07-16 12:28:30 -0700705 if (!isAccessibility && !isVirtualSource(current->attributes.source)) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700706 bool isAssistant = mUidPolicy->isAssistantUid(currentUid);
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800707 bool isActiveAssistant = mUidPolicy->isActiveAssistantUid(currentUid);
Eric Laurentc21d5692020-02-25 10:24:36 -0800708 bool isPrivacySensitive =
709 (current->attributes.flags & AUDIO_FLAG_CAPTURE_PRIVATE) != 0;
Eric Laurentb809a752020-06-29 09:53:13 -0700710
Eric Laurentc21d5692020-02-25 10:24:36 -0800711 if (appState == APP_STATE_TOP) {
712 if (isPrivacySensitive) {
713 if (current->startTimeNs > topSensitiveStartNs) {
714 topSensitiveActive = current;
715 topSensitiveStartNs = current->startTimeNs;
716 }
717 } else {
718 if (current->startTimeNs > topStartNs) {
719 topActive = current;
720 topStartNs = current->startTimeNs;
721 }
722 }
723 if (isAssistant) {
724 isAssistantOnTop = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800725 if (isActiveAssistant) {
726 useActiveAssistantList = true;
727 } else if (!useActiveAssistantList) {
728 if (current->startTimeNs > latestAssistantStartNs) {
729 latestActiveAssistant = current;
730 latestAssistantStartNs = current->startTimeNs;
731 }
732 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800733 }
Eric Laurenta46bedb2018-12-07 18:01:26 -0800734 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800735 // Clients capturing for HOTWORD are not considered
736 // for latest active to avoid masking regular clients started before
737 if (!(current->attributes.source == AUDIO_SOURCE_HOTWORD
738 || ((isA11yOnTop || rttCallActive) && isAssistant))) {
739 if (isPrivacySensitive) {
Eric Laurentb809a752020-06-29 09:53:13 -0700740 // if audio mode is IN_COMMUNICATION, make sure the audio mode owner
741 // is marked latest sensitive active even if another app qualifies.
742 if (current->startTimeNs > latestSensitiveStartNs
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700743 || (isInCommunication && currentUid == mPhoneStateOwnerUid)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700744 if (!isInCommunication || latestSensitiveActiveOrComm == nullptr
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700745 || VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000746 latestSensitiveActiveOrComm->attributionSource.uid))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700747 != mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700748 latestSensitiveActiveOrComm = current;
749 latestSensitiveStartNs = current->startTimeNs;
750 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800751 }
752 isSensitiveActive = true;
753 } else {
754 if (current->startTimeNs > latestStartNs) {
755 latestActive = current;
756 latestStartNs = current->startTimeNs;
757 }
758 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800759 }
760 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700761 if (current->attributes.source != AUDIO_SOURCE_HOTWORD) {
762 onlyHotwordActive = false;
763 }
Eric Laurentb0eff0f2021-11-09 16:05:49 +0100764 if (currentUid == mPhoneStateOwnerUid &&
765 !isVirtualSource(current->attributes.source)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700766 isPhoneStateOwnerActive = true;
767 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800768 }
769
Eric Laurent1ff16a72019-03-14 18:35:04 -0700770 // if no active client with UI on Top, consider latest active as top
771 if (topActive == nullptr) {
772 topActive = latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800773 topStartNs = latestStartNs;
774 }
775 if (topSensitiveActive == nullptr) {
Eric Laurentb809a752020-06-29 09:53:13 -0700776 topSensitiveActive = latestSensitiveActiveOrComm;
Eric Laurentc21d5692020-02-25 10:24:36 -0800777 topSensitiveStartNs = latestSensitiveStartNs;
Eric Laurentb809a752020-06-29 09:53:13 -0700778 } else if (latestSensitiveActiveOrComm != nullptr) {
779 // if audio mode is IN_COMMUNICATION, favor audio mode owner over an app with
780 // foreground UI in case both are capturing with privacy sensitive flag.
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700781 uid_t latestActiveUid = VALUE_OR_FATAL(
Svet Ganov33761132021-05-13 22:51:08 +0000782 aidl2legacy_int32_t_uid_t(latestSensitiveActiveOrComm->attributionSource.uid));
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700783 if (isInCommunication && latestActiveUid == mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700784 topSensitiveActive = latestSensitiveActiveOrComm;
785 topSensitiveStartNs = latestSensitiveStartNs;
786 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800787 }
788
789 // If both privacy sensitive and regular capture are active:
790 // if the regular capture is privileged
791 // allow concurrency
792 // else
793 // favor the privacy sensitive case
794 if (topActive != nullptr && topSensitiveActive != nullptr
Ricardo Correa57a37692020-03-23 17:27:25 -0700795 && !topActive->canCaptureOutput) {
Eric Laurentc21d5692020-02-25 10:24:36 -0800796 topActive = nullptr;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800797 }
798
799 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
800 sp<AudioRecordClient> current = mAudioRecordClients[i];
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700801 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000802 current->attributionSource.uid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700803 if (!current->active) {
804 continue;
805 }
806
Eric Laurent4eb58f12018-12-07 16:41:02 -0800807 audio_source_t source = current->attributes.source;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700808 bool isTopOrLatestActive = topActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +0000809 current->attributionSource.uid == topActive->attributionSource.uid;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700810 bool isTopOrLatestSensitive = topSensitiveActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +0000811 current->attributionSource.uid == topSensitiveActive->attributionSource.uid;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800812 bool isTopOrLatestAssistant = latestActiveAssistant == nullptr ? false :
813 current->attributionSource.uid == latestActiveAssistant->attributionSource.uid;
Eric Laurentc21d5692020-02-25 10:24:36 -0800814
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000815 auto canCaptureIfInCallOrCommunication = [&](const auto &recordClient) REQUIRES(mLock) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700816 uid_t recordUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000817 recordClient->attributionSource.uid));
Ricardo Correa57a37692020-03-23 17:27:25 -0700818 bool canCaptureCall = recordClient->canCaptureOutput;
Eric Laurentb809a752020-06-29 09:53:13 -0700819 bool canCaptureCommunication = recordClient->canCaptureOutput
820 || !isPhoneStateOwnerActive
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700821 || recordUid == mPhoneStateOwnerUid;
Eric Laurentb809a752020-06-29 09:53:13 -0700822 return !(isInCall && !canCaptureCall)
823 && !(isInCommunication && !canCaptureCommunication);
Eric Laurentc21d5692020-02-25 10:24:36 -0800824 };
Eric Laurent1ff16a72019-03-14 18:35:04 -0700825
826 // By default allow capture if:
827 // The assistant is not on TOP
Eric Laurenta171e352019-05-07 13:04:45 -0700828 // AND is on TOP or latest started
Eric Laurent1ff16a72019-03-14 18:35:04 -0700829 // AND there is no active privacy sensitive capture or call
830 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
831 bool allowCapture = !isAssistantOnTop
Eric Laurentc21d5692020-02-25 10:24:36 -0800832 && (isTopOrLatestActive || isTopOrLatestSensitive)
833 && !(isSensitiveActive
Ricardo Correa57a37692020-03-23 17:27:25 -0700834 && !(isTopOrLatestSensitive || current->canCaptureOutput))
Eric Laurentc21d5692020-02-25 10:24:36 -0800835 && canCaptureIfInCallOrCommunication(current);
Eric Laurent2dc962b2019-03-01 08:25:25 -0800836
Eric Laurented726cc2021-07-01 14:26:41 +0200837 if (!current->hasOp()) {
838 // Never allow capture if app op is denied
839 allowCapture = false;
840 } else if (isVirtualSource(source)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700841 // Allow capture for virtual (remote submix, call audio TX or RX...) sources
842 allowCapture = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800843 } else if (!useActiveAssistantList && mUidPolicy->isAssistantUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700844 // For assistant allow capture if:
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800845 // Active assistant list is not being used
846 // AND accessibility service is on TOP or a RTT call is active
Eric Laurent1ff16a72019-03-14 18:35:04 -0700847 // AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800848 // OR there is no active privacy sensitive capture or call
849 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
850 // AND is latest TOP assistant AND
851 // uses VOICE_RECOGNITION OR uses HOTWORD
852 // OR there is no TOP assistant and uses HOTWORD
Eric Laurent6ede98f2019-06-11 14:50:30 -0700853 if (isA11yOnTop || rttCallActive) {
Eric Laurent4eb58f12018-12-07 16:41:02 -0800854 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700855 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800856 }
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800857 } else if (!(isSensitiveActive && !current->canCaptureOutput)
858 && canCaptureIfInCallOrCommunication(current)) {
859 if (isTopOrLatestAssistant
860 && (source == AUDIO_SOURCE_VOICE_RECOGNITION
861 || source == AUDIO_SOURCE_HOTWORD)) {
862 allowCapture = true;
863 } else if (!isAssistantOnTop && (source == AUDIO_SOURCE_HOTWORD)) {
864 allowCapture = true;
865 }
866 }
867 } else if (useActiveAssistantList && mUidPolicy->isActiveAssistantUid(currentUid)) {
868 // For assistant on active list and on top allow capture if:
869 // An accessibility service is on TOP
870 // AND the source is VOICE_RECOGNITION or HOTWORD
871 // OR there is no active privacy sensitive capture or call
872 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
873 // AND uses VOICE_RECOGNITION OR uses HOTWORD
874 if (isA11yOnTop) {
875 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
876 allowCapture = true;
877 }
878 } else if (!(isSensitiveActive && !current->canCaptureOutput)
Eric Laurentc21d5692020-02-25 10:24:36 -0800879 && canCaptureIfInCallOrCommunication(current)) {
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800880 if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) || (source == AUDIO_SOURCE_HOTWORD))
881 {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700882 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800883 }
884 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700885 } else if (mUidPolicy->isA11yUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700886 // For accessibility service allow capture if:
Eric Laurent47670c92019-08-28 16:59:05 -0700887 // The assistant is not on TOP
888 // AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -0700889 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent47670c92019-08-28 16:59:05 -0700890 // OR
891 // Is on TOP AND the source is VOICE_RECOGNITION or HOTWORD
892 if (!isAssistantOnTop
Ricardo Correa57a37692020-03-23 17:27:25 -0700893 && !(isSensitiveActive && !current->canCaptureOutput)
Eric Laurentc21d5692020-02-25 10:24:36 -0800894 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent47670c92019-08-28 16:59:05 -0700895 allowCapture = true;
896 }
Eric Laurent589171c2019-07-25 18:04:29 -0700897 if (isA11yOnTop) {
898 if (source == AUDIO_SOURCE_VOICE_RECOGNITION || source == AUDIO_SOURCE_HOTWORD) {
899 allowCapture = true;
900 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800901 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700902 } else if (source == AUDIO_SOURCE_HOTWORD) {
903 // For HOTWORD source allow capture when not on TOP if:
904 // All active clients are using HOTWORD source
905 // AND no call is active
906 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurentc21d5692020-02-25 10:24:36 -0800907 if (onlyHotwordActive
908 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent4e947da2019-10-17 15:24:06 -0700909 allowCapture = true;
910 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700911 } else if (mUidPolicy->isCurrentImeUid(currentUid)) {
Kohsuke Yatoha623a132020-03-24 20:10:26 -0700912 // For current InputMethodService allow capture if:
913 // A RTT call is active AND the source is VOICE_RECOGNITION
914 if (rttCallActive && source == AUDIO_SOURCE_VOICE_RECOGNITION) {
915 allowCapture = true;
916 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800917 }
Eric Laurent8c7ef892021-06-10 13:32:16 +0200918 setAppState_l(current,
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700919 allowCapture ? apmStatFromAmState(mUidPolicy->getUidState(currentUid)) :
Eric Laurent1ff16a72019-03-14 18:35:04 -0700920 APP_STATE_IDLE);
Eric Laurente8c8b432018-10-17 10:08:02 -0700921 }
922}
923
Michael Groovercfd28302018-12-11 19:16:46 -0800924void AudioPolicyService::silenceAllRecordings_l() {
925 for (size_t i = 0; i < mAudioRecordClients.size(); i++) {
926 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -0700927 if (!isVirtualSource(current->attributes.source)) {
Eric Laurent8c7ef892021-06-10 13:32:16 +0200928 setAppState_l(current, APP_STATE_IDLE);
Eric Laurent1ff16a72019-03-14 18:35:04 -0700929 }
Michael Groovercfd28302018-12-11 19:16:46 -0800930 }
931}
932
Eric Laurente8c8b432018-10-17 10:08:02 -0700933/* static */
934app_state_t AudioPolicyService::apmStatFromAmState(int amState) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700935
936 if (amState == ActivityManager::PROCESS_STATE_UNKNOWN) {
Eric Laurente8c8b432018-10-17 10:08:02 -0700937 return APP_STATE_IDLE;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700938 } else if (amState <= ActivityManager::PROCESS_STATE_TOP) {
939 // include persistent services
940 return APP_STATE_TOP;
Eric Laurente8c8b432018-10-17 10:08:02 -0700941 }
942 return APP_STATE_FOREGROUND;
943}
944
Eric Laurent4eb58f12018-12-07 16:41:02 -0800945/* static */
Eric Laurent2dc962b2019-03-01 08:25:25 -0800946bool AudioPolicyService::isVirtualSource(audio_source_t source)
Eric Laurent4eb58f12018-12-07 16:41:02 -0800947{
948 switch (source) {
949 case AUDIO_SOURCE_VOICE_UPLINK:
950 case AUDIO_SOURCE_VOICE_DOWNLINK:
951 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent2dc962b2019-03-01 08:25:25 -0800952 case AUDIO_SOURCE_REMOTE_SUBMIX:
953 case AUDIO_SOURCE_FM_TUNER:
Eric Laurent68eb2122020-04-30 17:40:57 -0700954 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent4eb58f12018-12-07 16:41:02 -0800955 return true;
956 default:
957 break;
958 }
959 return false;
960}
961
Eric Laurented726cc2021-07-01 14:26:41 +0200962/* static */
963bool AudioPolicyService::isAppOpSource(audio_source_t source)
964{
965 switch (source) {
966 case AUDIO_SOURCE_FM_TUNER:
967 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent637bd202021-09-22 11:17:11 +0200968 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurented726cc2021-07-01 14:26:41 +0200969 return false;
970 default:
971 break;
972 }
973 return true;
974}
975
Eric Laurent8c7ef892021-06-10 13:32:16 +0200976void AudioPolicyService::setAppState_l(sp<AudioRecordClient> client, app_state_t state)
Eric Laurente8c8b432018-10-17 10:08:02 -0700977{
978 AutoCallerClear acc;
979
980 if (mAudioPolicyManager) {
Eric Laurent8c7ef892021-06-10 13:32:16 +0200981 mAudioPolicyManager->setAppState(client->portId, state);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700982 }
983 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
984 if (af) {
Eric Laurentf32108e2018-10-04 17:22:04 -0700985 bool silenced = state == APP_STATE_IDLE;
Eric Laurent8c7ef892021-06-10 13:32:16 +0200986 if (client->silenced != silenced) {
987 if (client->active) {
988 if (silenced) {
989 finishRecording(client->attributionSource, client->attributes.source);
990 } else {
991 std::stringstream msg;
992 msg << "Audio recording un-silenced on session " << client->session;
993 if (!startRecording(client->attributionSource, String16(msg.str().c_str()),
994 client->attributes.source)) {
995 silenced = true;
996 }
997 }
998 }
999 af->setRecordSilenced(client->portId, silenced);
1000 client->silenced = silenced;
1001 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001002 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001003}
1004
Glenn Kasten0f11b512014-01-31 16:18:54 -08001005status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001006{
Glenn Kasten44deb052012-02-05 18:09:08 -08001007 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001008 dumpPermissionDenial(fd);
1009 } else {
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001010 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001011 if (!locked) {
1012 String8 result(kDeadlockedString);
1013 write(fd, result.string(), result.size());
1014 }
1015
1016 dumpInternals(fd);
Glenn Kasten9d1f02d2012-02-08 17:47:58 -08001017 if (mAudioCommandThread != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001018 mAudioCommandThread->dump(fd);
1019 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001020
Eric Laurentdce54a12014-03-10 12:19:46 -07001021 if (mAudioPolicyManager) {
1022 mAudioPolicyManager->dump(fd);
1023 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001024
Kevin Rocard8be94972019-02-22 13:26:25 -08001025 mPackageManager.dump(fd);
1026
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001027 dumpReleaseLock(mLock, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001028 }
1029 return NO_ERROR;
1030}
1031
1032status_t AudioPolicyService::dumpPermissionDenial(int fd)
1033{
1034 const size_t SIZE = 256;
1035 char buffer[SIZE];
1036 String8 result;
1037 snprintf(buffer, SIZE, "Permission Denial: "
1038 "can't dump AudioPolicyService from pid=%d, uid=%d\n",
1039 IPCThreadState::self()->getCallingPid(),
1040 IPCThreadState::self()->getCallingUid());
1041 result.append(buffer);
1042 write(fd, result.string(), result.size());
1043 return NO_ERROR;
1044}
1045
1046status_t AudioPolicyService::onTransact(
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001047 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001048 // make sure transactions reserved to AudioFlinger do not come from other processes
1049 switch (code) {
1050 case TRANSACTION_startOutput:
1051 case TRANSACTION_stopOutput:
1052 case TRANSACTION_releaseOutput:
1053 case TRANSACTION_getInputForAttr:
1054 case TRANSACTION_startInput:
1055 case TRANSACTION_stopInput:
1056 case TRANSACTION_releaseInput:
1057 case TRANSACTION_getOutputForEffect:
1058 case TRANSACTION_registerEffect:
1059 case TRANSACTION_unregisterEffect:
1060 case TRANSACTION_setEffectEnabled:
1061 case TRANSACTION_getStrategyForStream:
1062 case TRANSACTION_getOutputForAttr:
1063 case TRANSACTION_moveEffectsToIo:
1064 ALOGW("%s: transaction %d received from PID %d",
1065 __func__, code, IPCThreadState::self()->getCallingPid());
1066 return INVALID_OPERATION;
1067 default:
1068 break;
1069 }
1070
1071 // make sure the following transactions come from system components
1072 switch (code) {
1073 case TRANSACTION_setDeviceConnectionState:
1074 case TRANSACTION_handleDeviceConfigChange:
1075 case TRANSACTION_setPhoneState:
1076//FIXME: Allow setForceUse calls from system apps until a better use case routing API is available
1077// case TRANSACTION_setForceUse:
1078 case TRANSACTION_initStreamVolume:
1079 case TRANSACTION_setStreamVolumeIndex:
1080 case TRANSACTION_setVolumeIndexForAttributes:
1081 case TRANSACTION_getStreamVolumeIndex:
1082 case TRANSACTION_getVolumeIndexForAttributes:
1083 case TRANSACTION_getMinVolumeIndexForAttributes:
1084 case TRANSACTION_getMaxVolumeIndexForAttributes:
1085 case TRANSACTION_isStreamActive:
1086 case TRANSACTION_isStreamActiveRemotely:
1087 case TRANSACTION_isSourceActive:
1088 case TRANSACTION_getDevicesForStream:
1089 case TRANSACTION_registerPolicyMixes:
1090 case TRANSACTION_setMasterMono:
1091 case TRANSACTION_getSurroundFormats:
Kriti Dang6537def2021-03-02 13:46:59 +01001092 case TRANSACTION_getReportedSurroundFormats:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001093 case TRANSACTION_setSurroundFormatEnabled:
Oscar Azucena829d90d2022-01-28 17:17:56 -08001094 case TRANSACTION_setAssistantServicesUids:
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001095 case TRANSACTION_setActiveAssistantServicesUids:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001096 case TRANSACTION_setA11yServicesUids:
1097 case TRANSACTION_setUidDeviceAffinities:
1098 case TRANSACTION_removeUidDeviceAffinities:
1099 case TRANSACTION_setUserIdDeviceAffinities:
1100 case TRANSACTION_removeUserIdDeviceAffinities:
Pattydd807582021-11-04 21:01:03 +08001101 case TRANSACTION_getHwOffloadFormatsSupportedForBluetoothMedia:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001102 case TRANSACTION_listAudioVolumeGroups:
1103 case TRANSACTION_getVolumeGroupFromAudioAttributes:
1104 case TRANSACTION_acquireSoundTriggerSession:
1105 case TRANSACTION_releaseSoundTriggerSession:
1106 case TRANSACTION_setRttEnabled:
1107 case TRANSACTION_isCallScreenModeSupported:
1108 case TRANSACTION_setDevicesRoleForStrategy:
1109 case TRANSACTION_setSupportedSystemUsages:
1110 case TRANSACTION_removeDevicesRoleForStrategy:
1111 case TRANSACTION_getDevicesForRoleAndStrategy:
1112 case TRANSACTION_getDevicesForAttributes:
1113 case TRANSACTION_setAllowedCapturePolicy:
1114 case TRANSACTION_onNewAudioModulesAvailable:
1115 case TRANSACTION_setCurrentImeUid:
1116 case TRANSACTION_registerSoundTriggerCaptureStateListener:
1117 case TRANSACTION_setDevicesRoleForCapturePreset:
1118 case TRANSACTION_addDevicesRoleForCapturePreset:
1119 case TRANSACTION_removeDevicesRoleForCapturePreset:
1120 case TRANSACTION_clearDevicesRoleForCapturePreset:
Eric Laurent81dd0f52021-07-05 11:54:40 +02001121 case TRANSACTION_getDevicesForRoleAndCapturePreset:
1122 case TRANSACTION_getSpatializer: {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001123 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
1124 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
1125 __func__, code, IPCThreadState::self()->getCallingPid(),
1126 IPCThreadState::self()->getCallingUid());
1127 return INVALID_OPERATION;
1128 }
1129 } break;
1130 default:
1131 break;
1132 }
1133
1134 std::string tag("IAudioPolicyService command " + std::to_string(code));
1135 TimeCheck check(tag.c_str());
1136
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001137 switch (code) {
1138 case SHELL_COMMAND_TRANSACTION: {
1139 int in = data.readFileDescriptor();
1140 int out = data.readFileDescriptor();
1141 int err = data.readFileDescriptor();
1142 int argc = data.readInt32();
1143 Vector<String16> args;
1144 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
1145 args.add(data.readString16());
1146 }
1147 sp<IBinder> unusedCallback;
1148 sp<IResultReceiver> resultReceiver;
1149 status_t status;
1150 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
1151 return status;
1152 }
1153 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
1154 return status;
1155 }
1156 status = shellCommand(in, out, err, args);
1157 if (resultReceiver != nullptr) {
1158 resultReceiver->send(status);
1159 }
1160 return NO_ERROR;
1161 }
1162 }
1163
Mathias Agopian65ab4712010-07-14 17:59:35 -07001164 return BnAudioPolicyService::onTransact(code, data, reply, flags);
1165}
1166
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001167// ------------------- Shell command implementation -------------------
1168
1169// NOTE: This is a remote API - make sure all args are validated
1170status_t AudioPolicyService::shellCommand(int in, int out, int err, Vector<String16>& args) {
1171 if (!checkCallingPermission(sManageAudioPolicyPermission, nullptr, nullptr)) {
1172 return PERMISSION_DENIED;
1173 }
1174 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
1175 return BAD_VALUE;
1176 }
jovanakbe066e12019-09-02 11:54:39 -07001177 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001178 return handleSetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001179 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001180 return handleResetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001181 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001182 return handleGetUidState(args, out, err);
Eric Laurent269acb42021-04-23 16:53:22 +02001183 } else if (args.size() >= 1 && args[0] == String16("purge_permission-cache")) {
1184 purgePermissionCache();
1185 return NO_ERROR;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001186 } else if (args.size() == 1 && args[0] == String16("help")) {
1187 printHelp(out);
1188 return NO_ERROR;
1189 }
1190 printHelp(err);
1191 return BAD_VALUE;
1192}
1193
jovanakbe066e12019-09-02 11:54:39 -07001194static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1195 if (userId < 0) {
1196 ALOGE("Invalid user: %d", userId);
1197 dprintf(err, "Invalid user: %d\n", userId);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001198 return BAD_VALUE;
1199 }
jovanakbe066e12019-09-02 11:54:39 -07001200
1201 PermissionController pc;
1202 uid = pc.getPackageUid(packageName, 0);
1203 if (uid <= 0) {
1204 ALOGE("Unknown package: '%s'", String8(packageName).string());
1205 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1206 return BAD_VALUE;
1207 }
1208
1209 uid = multiuser_get_uid(userId, uid);
1210 return NO_ERROR;
1211}
1212
1213status_t AudioPolicyService::handleSetUidState(Vector<String16>& args, int err) {
1214 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
1215 if (!(args.size() == 3 || args.size() == 5)) {
1216 printHelp(err);
1217 return BAD_VALUE;
1218 }
1219
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001220 bool active = false;
1221 if (args[2] == String16("active")) {
1222 active = true;
1223 } else if ((args[2] != String16("idle"))) {
1224 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
1225 return BAD_VALUE;
1226 }
jovanakbe066e12019-09-02 11:54:39 -07001227
1228 int userId = 0;
1229 if (args.size() >= 5 && args[3] == String16("--user")) {
1230 userId = atoi(String8(args[4]));
1231 }
1232
1233 uid_t uid;
1234 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1235 return BAD_VALUE;
1236 }
1237
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001238 sp<UidPolicy> uidPolicy;
1239 {
1240 Mutex::Autolock _l(mLock);
1241 uidPolicy = mUidPolicy;
1242 }
1243 if (uidPolicy) {
1244 uidPolicy->addOverrideUid(uid, active);
1245 return NO_ERROR;
1246 }
1247 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001248}
1249
1250status_t AudioPolicyService::handleResetUidState(Vector<String16>& args, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001251 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1252 if (!(args.size() == 2 || args.size() == 4)) {
1253 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001254 return BAD_VALUE;
1255 }
jovanakbe066e12019-09-02 11:54:39 -07001256
1257 int userId = 0;
1258 if (args.size() >= 4 && args[2] == String16("--user")) {
1259 userId = atoi(String8(args[3]));
1260 }
1261
1262 uid_t uid;
1263 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1264 return BAD_VALUE;
1265 }
1266
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001267 sp<UidPolicy> uidPolicy;
1268 {
1269 Mutex::Autolock _l(mLock);
1270 uidPolicy = mUidPolicy;
1271 }
1272 if (uidPolicy) {
1273 uidPolicy->removeOverrideUid(uid);
1274 return NO_ERROR;
1275 }
1276 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001277}
1278
1279status_t AudioPolicyService::handleGetUidState(Vector<String16>& args, int out, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001280 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1281 if (!(args.size() == 2 || args.size() == 4)) {
1282 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001283 return BAD_VALUE;
1284 }
jovanakbe066e12019-09-02 11:54:39 -07001285
1286 int userId = 0;
1287 if (args.size() >= 4 && args[2] == String16("--user")) {
1288 userId = atoi(String8(args[3]));
1289 }
1290
1291 uid_t uid;
1292 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1293 return BAD_VALUE;
1294 }
1295
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001296 sp<UidPolicy> uidPolicy;
1297 {
1298 Mutex::Autolock _l(mLock);
1299 uidPolicy = mUidPolicy;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001300 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001301 if (uidPolicy) {
1302 return dprintf(out, uidPolicy->isUidActive(uid) ? "active\n" : "idle\n");
1303 }
1304 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001305}
1306
1307status_t AudioPolicyService::printHelp(int out) {
1308 return dprintf(out, "Audio policy service commands:\n"
jovanakbe066e12019-09-02 11:54:39 -07001309 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
1310 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
1311 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001312 " help print this message\n");
1313}
1314
1315// ----------- AudioPolicyService::UidPolicy implementation ----------
1316
1317void AudioPolicyService::UidPolicy::registerSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001318 status_t res = mAm.linkToDeath(this);
1319 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001320 | ActivityManager::UID_OBSERVER_IDLE
Eric Laurente8c8b432018-10-17 10:08:02 -07001321 | ActivityManager::UID_OBSERVER_ACTIVE
1322 | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001323 ActivityManager::PROCESS_STATE_UNKNOWN,
1324 String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001325 if (!res) {
1326 Mutex::Autolock _l(mLock);
1327 mObserverRegistered = true;
1328 } else {
1329 ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001330
Steven Moreland2f348142019-07-02 15:59:07 -07001331 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001332 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001333}
1334
1335void AudioPolicyService::UidPolicy::unregisterSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001336 mAm.unlinkToDeath(this);
1337 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001338 Mutex::Autolock _l(mLock);
1339 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001340}
1341
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001342void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
1343 Mutex::Autolock _l(mLock);
1344 mCachedUids.clear();
1345 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001346}
1347
Eric Laurente8c8b432018-10-17 10:08:02 -07001348void AudioPolicyService::UidPolicy::checkRegistered() {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001349 bool needToReregister = false;
1350 {
1351 Mutex::Autolock _l(mLock);
1352 needToReregister = !mObserverRegistered;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001353 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001354 if (needToReregister) {
1355 // Looks like ActivityManager has died previously, attempt to re-register.
1356 registerSelf();
1357 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001358}
1359
1360bool AudioPolicyService::UidPolicy::isUidActive(uid_t uid) {
1361 if (isServiceUid(uid)) return true;
1362 checkRegistered();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001363 {
1364 Mutex::Autolock _l(mLock);
1365 auto overrideIter = mOverrideUids.find(uid);
1366 if (overrideIter != mOverrideUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001367 return overrideIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001368 }
1369 // In an absense of the ActivityManager, assume everything to be active.
1370 if (!mObserverRegistered) return true;
1371 auto cacheIter = mCachedUids.find(uid);
Mikhail Naganoveba668a2018-04-05 08:13:15 -07001372 if (cacheIter != mCachedUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001373 return cacheIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001374 }
1375 }
1376 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001377 bool active = am.isUidActive(uid, String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001378 {
1379 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001380 mCachedUids.insert(std::pair<uid_t,
1381 std::pair<bool, int>>(uid, std::pair<bool, int>(active,
1382 ActivityManager::PROCESS_STATE_UNKNOWN)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001383 }
1384 return active;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001385}
1386
Eric Laurente8c8b432018-10-17 10:08:02 -07001387int AudioPolicyService::UidPolicy::getUidState(uid_t uid) {
1388 if (isServiceUid(uid)) {
1389 return ActivityManager::PROCESS_STATE_TOP;
1390 }
1391 checkRegistered();
1392 {
1393 Mutex::Autolock _l(mLock);
1394 auto overrideIter = mOverrideUids.find(uid);
1395 if (overrideIter != mOverrideUids.end()) {
1396 if (overrideIter->second.first) {
1397 if (overrideIter->second.second != ActivityManager::PROCESS_STATE_UNKNOWN) {
1398 return overrideIter->second.second;
1399 } else {
1400 auto cacheIter = mCachedUids.find(uid);
1401 if (cacheIter != mCachedUids.end()) {
1402 return cacheIter->second.second;
1403 }
1404 }
1405 }
1406 return ActivityManager::PROCESS_STATE_UNKNOWN;
1407 }
1408 // In an absense of the ActivityManager, assume everything to be active.
1409 if (!mObserverRegistered) {
1410 return ActivityManager::PROCESS_STATE_TOP;
1411 }
1412 auto cacheIter = mCachedUids.find(uid);
1413 if (cacheIter != mCachedUids.end()) {
1414 if (cacheIter->second.first) {
1415 return cacheIter->second.second;
1416 } else {
1417 return ActivityManager::PROCESS_STATE_UNKNOWN;
1418 }
1419 }
1420 }
1421 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001422 bool active = am.isUidActive(uid, String16("audioserver"));
Eric Laurente8c8b432018-10-17 10:08:02 -07001423 int state = ActivityManager::PROCESS_STATE_UNKNOWN;
1424 if (active) {
1425 state = am.getUidProcessState(uid, String16("audioserver"));
1426 }
1427 {
1428 Mutex::Autolock _l(mLock);
1429 mCachedUids.insert(std::pair<uid_t,
1430 std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
1431 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001432
Eric Laurente8c8b432018-10-17 10:08:02 -07001433 return state;
1434}
1435
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001436void AudioPolicyService::UidPolicy::onUidActive(uid_t uid) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001437 updateUid(&mCachedUids, uid, true, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001438}
1439
1440void AudioPolicyService::UidPolicy::onUidGone(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001441 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, false);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001442}
1443
1444void AudioPolicyService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001445 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001446}
1447
Eric Laurente8c8b432018-10-17 10:08:02 -07001448void AudioPolicyService::UidPolicy::onUidStateChanged(uid_t uid,
1449 int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07001450 int64_t procStateSeq __unused,
1451 int32_t capability __unused) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001452 if (procState != ActivityManager::PROCESS_STATE_UNKNOWN) {
1453 updateUid(&mCachedUids, uid, true, procState, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001454 }
1455}
1456
1457void AudioPolicyService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001458 updateUid(&mOverrideUids, uid, active, ActivityManager::PROCESS_STATE_UNKNOWN, insert);
1459}
1460
1461void AudioPolicyService::UidPolicy::notifyService() {
1462 sp<AudioPolicyService> service = mService.promote();
1463 if (service != nullptr) {
1464 service->updateUidStates();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001465 }
1466}
1467
Eric Laurente8c8b432018-10-17 10:08:02 -07001468void AudioPolicyService::UidPolicy::updateUid(std::unordered_map<uid_t,
1469 std::pair<bool, int>> *uids,
1470 uid_t uid,
1471 bool active,
1472 int state,
1473 bool insert) {
1474 if (isServiceUid(uid)) {
1475 return;
1476 }
1477 bool wasActive = isUidActive(uid);
1478 int previousState = getUidState(uid);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001479 {
1480 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001481 updateUidLocked(uids, uid, active, state, insert);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001482 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001483 if (wasActive != isUidActive(uid) || state != previousState) {
1484 notifyService();
1485 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001486}
1487
Eric Laurente8c8b432018-10-17 10:08:02 -07001488void AudioPolicyService::UidPolicy::updateUidLocked(std::unordered_map<uid_t,
1489 std::pair<bool, int>> *uids,
1490 uid_t uid,
1491 bool active,
1492 int state,
1493 bool insert) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001494 auto it = uids->find(uid);
1495 if (it != uids->end()) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001496 if (insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001497 if (state == ActivityManager::PROCESS_STATE_UNKNOWN) {
1498 it->second.first = active;
1499 }
1500 if (it->second.first) {
1501 it->second.second = state;
1502 } else {
1503 it->second.second = ActivityManager::PROCESS_STATE_UNKNOWN;
1504 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001505 } else {
1506 uids->erase(it);
1507 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001508 } else if (insert && (state == ActivityManager::PROCESS_STATE_UNKNOWN)) {
1509 uids->insert(std::pair<uid_t, std::pair<bool, int>>(uid,
1510 std::pair<bool, int>(active, state)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001511 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001512}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001513
Eric Laurent4eb58f12018-12-07 16:41:02 -08001514bool AudioPolicyService::UidPolicy::isA11yOnTop() {
1515 for (const auto &uid : mCachedUids) {
Eric Laurent47670c92019-08-28 16:59:05 -07001516 if (!isA11yUid(uid.first)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001517 continue;
1518 }
Amith Yamasanibcbb3002019-01-23 13:53:33 -08001519 if (uid.second.second >= ActivityManager::PROCESS_STATE_TOP
1520 && uid.second.second <= ActivityManager::PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001521 return true;
1522 }
1523 }
1524 return false;
1525}
1526
Eric Laurentb78763e2018-10-17 10:08:02 -07001527bool AudioPolicyService::UidPolicy::isA11yUid(uid_t uid)
1528{
1529 std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid);
1530 return it != mA11yUids.end();
1531}
1532
Oscar Azucena829d90d2022-01-28 17:17:56 -08001533void AudioPolicyService::UidPolicy::setAssistantUids(const std::vector<uid_t>& uids) {
1534 mAssistantUids.clear();
1535 mAssistantUids = uids;
1536}
1537
1538bool AudioPolicyService::UidPolicy::isAssistantUid(uid_t uid)
1539{
1540 std::vector<uid_t>::iterator it = find(mAssistantUids.begin(), mAssistantUids.end(), uid);
1541 return it != mAssistantUids.end();
1542}
1543
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001544void AudioPolicyService::UidPolicy::setActiveAssistantUids(const std::vector<uid_t>& activeUids) {
1545 mActiveAssistantUids = activeUids;
1546}
1547
1548bool AudioPolicyService::UidPolicy::isActiveAssistantUid(uid_t uid)
1549{
1550 std::vector<uid_t>::iterator it = find(mActiveAssistantUids.begin(),
1551 mActiveAssistantUids.end(), uid);
1552 return it != mActiveAssistantUids.end();
1553}
1554
Oscar Azucena829d90d2022-01-28 17:17:56 -08001555void AudioPolicyService::UidPolicy::dumpInternals(int fd) {
1556 const size_t SIZE = 256;
1557 char buffer[SIZE];
1558 String8 result;
1559 auto appendUidsToResult = [&](const char* title, const std::vector<uid_t> &uids) {
1560 snprintf(buffer, SIZE, "\t%s: \n", title);
1561 result.append(buffer);
1562 int counter = 0;
1563 if (uids.empty()) {
1564 snprintf(buffer, SIZE, "\t\tNo UIDs present.\n");
1565 result.append(buffer);
1566 return;
1567 }
1568 for (const auto &uid : uids) {
1569 snprintf(buffer, SIZE, "\t\tUID[%d]=%d\n", counter++, uid);
1570 result.append(buffer);
1571 }
1572 };
1573
1574 snprintf(buffer, SIZE, "UID Policy:\n");
1575 result.append(buffer);
1576 snprintf(buffer, SIZE, "\tmObserverRegistered=%s\n",(mObserverRegistered ? "True":"False"));
1577 result.append(buffer);
1578
1579 appendUidsToResult("Assistants UIDs", mAssistantUids);
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001580 appendUidsToResult("Active Assistants UIDs", mActiveAssistantUids);
Oscar Azucena829d90d2022-01-28 17:17:56 -08001581
1582 appendUidsToResult("Accessibility UIDs", mA11yUids);
1583
1584 snprintf(buffer, SIZE, "\tInput Method Service UID=%d\n", mCurrentImeUid);
1585 result.append(buffer);
1586
1587 snprintf(buffer, SIZE, "\tIs RTT Enabled: %s\n", (mRttEnabled ? "True":"False"));
1588 result.append(buffer);
1589
1590 write(fd, result.string(), result.size());
1591}
1592
Michael Groovercfd28302018-12-11 19:16:46 -08001593// ----------- AudioPolicyService::SensorPrivacyService implementation ----------
1594void AudioPolicyService::SensorPrivacyPolicy::registerSelf() {
1595 SensorPrivacyManager spm;
1596 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1597 spm.addSensorPrivacyListener(this);
1598}
1599
1600void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
1601 SensorPrivacyManager spm;
1602 spm.removeSensorPrivacyListener(this);
1603}
1604
1605bool AudioPolicyService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1606 return mSensorPrivacyEnabled;
1607}
1608
Evan Seversond8dc6832022-01-27 10:47:03 -08001609binder::Status AudioPolicyService::SensorPrivacyPolicy::onSensorPrivacyChanged(
1610 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Groovercfd28302018-12-11 19:16:46 -08001611 mSensorPrivacyEnabled = enabled;
1612 sp<AudioPolicyService> service = mService.promote();
1613 if (service != nullptr) {
1614 service->updateUidStates();
1615 }
1616 return binder::Status::ok();
1617}
1618
Eric Laurented726cc2021-07-01 14:26:41 +02001619// ----------- AudioPolicyService::OpRecordAudioMonitor implementation ----------
1620
1621// static
1622sp<AudioPolicyService::OpRecordAudioMonitor>
1623AudioPolicyService::OpRecordAudioMonitor::createIfNeeded(
1624 const AttributionSourceState& attributionSource, const audio_attributes_t& attr,
1625 wp<AudioCommandThread> commandThread)
1626{
Eric Laurent987ce102021-07-05 12:11:51 +02001627 if (isAudioServerOrRootUid(attributionSource.uid)) {
1628 ALOGV("not silencing record for audio or root source %s",
Eric Laurented726cc2021-07-01 14:26:41 +02001629 attributionSource.toString().c_str());
1630 return nullptr;
1631 }
1632
1633 if (!AudioPolicyService::isAppOpSource(attr.source)) {
1634 ALOGD("not monitoring app op for uid %d and source %d",
1635 attributionSource.uid, attr.source);
1636 return nullptr;
1637 }
1638
1639 if (!attributionSource.packageName.has_value()
1640 || attributionSource.packageName.value().size() == 0) {
1641 return nullptr;
1642 }
1643 return new OpRecordAudioMonitor(attributionSource, getOpForSource(attr.source), commandThread);
1644}
1645
1646AudioPolicyService::OpRecordAudioMonitor::OpRecordAudioMonitor(
1647 const AttributionSourceState& attributionSource, int32_t appOp,
1648 wp<AudioCommandThread> commandThread) :
1649 mHasOp(true), mAttributionSource(attributionSource), mAppOp(appOp),
1650 mCommandThread(commandThread)
1651{
1652}
1653
1654AudioPolicyService::OpRecordAudioMonitor::~OpRecordAudioMonitor()
1655{
1656 if (mOpCallback != 0) {
1657 mAppOpsManager.stopWatchingMode(mOpCallback);
1658 }
1659 mOpCallback.clear();
1660}
1661
1662void AudioPolicyService::OpRecordAudioMonitor::onFirstRef()
1663{
1664 checkOp();
1665 mOpCallback = new RecordAudioOpCallback(this);
1666 ALOGV("start watching op %d for %s", mAppOp, mAttributionSource.toString().c_str());
1667 // TODO: We need to always watch AppOpsManager::OP_RECORD_AUDIO too
1668 // since it controls the mic permission for legacy apps.
1669 mAppOpsManager.startWatchingMode(mAppOp, VALUE_OR_FATAL(aidl2legacy_string_view_String16(
1670 mAttributionSource.packageName.value_or(""))),
1671 mOpCallback);
1672}
1673
1674bool AudioPolicyService::OpRecordAudioMonitor::hasOp() const {
1675 return mHasOp.load();
1676}
1677
1678// Called by RecordAudioOpCallback when the app op corresponding to this OpRecordAudioMonitor
1679// is updated in AppOp callback and in onFirstRef()
1680// Note this method is never called (and never to be) for audio server / root track
1681// due to the UID in createIfNeeded(). As a result for those record track, it's:
1682// - not called from constructor,
1683// - not called from RecordAudioOpCallback because the callback is not installed in this case
1684void AudioPolicyService::OpRecordAudioMonitor::checkOp(bool updateUidStates)
1685{
1686 // TODO: We need to always check AppOpsManager::OP_RECORD_AUDIO too
1687 // since it controls the mic permission for legacy apps.
1688 const int32_t mode = mAppOpsManager.checkOp(mAppOp,
1689 mAttributionSource.uid, VALUE_OR_FATAL(aidl2legacy_string_view_String16(
1690 mAttributionSource.packageName.value_or(""))));
1691 const bool hasIt = (mode == AppOpsManager::MODE_ALLOWED);
1692 // verbose logging only log when appOp changed
1693 ALOGI_IF(hasIt != mHasOp.load(),
1694 "App op %d missing, %ssilencing record %s",
1695 mAppOp, hasIt ? "un" : "", mAttributionSource.toString().c_str());
1696 mHasOp.store(hasIt);
1697
1698 if (updateUidStates) {
1699 sp<AudioCommandThread> commandThread = mCommandThread.promote();
1700 if (commandThread != nullptr) {
1701 commandThread->updateUidStatesCommand();
1702 }
1703 }
1704}
1705
1706AudioPolicyService::OpRecordAudioMonitor::RecordAudioOpCallback::RecordAudioOpCallback(
1707 const wp<OpRecordAudioMonitor>& monitor) : mMonitor(monitor)
1708{ }
1709
1710void AudioPolicyService::OpRecordAudioMonitor::RecordAudioOpCallback::opChanged(int32_t op,
1711 const String16& packageName __unused) {
1712 sp<OpRecordAudioMonitor> monitor = mMonitor.promote();
1713 if (monitor != NULL) {
1714 if (op != monitor->getOp()) {
1715 return;
1716 }
1717 monitor->checkOp(true);
1718 }
1719}
1720
1721
Mathias Agopian65ab4712010-07-14 17:59:35 -07001722// ----------- AudioPolicyService::AudioCommandThread implementation ----------
1723
Eric Laurentbfb1b832013-01-07 09:53:42 -08001724AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
1725 const wp<AudioPolicyService>& service)
1726 : Thread(false), mName(name), mService(service)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001727{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001728}
1729
1730
1731AudioPolicyService::AudioCommandThread::~AudioCommandThread()
1732{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001733 if (!mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001734 release_wake_lock(mName.string());
1735 }
1736 mAudioCommands.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001737}
1738
1739void AudioPolicyService::AudioCommandThread::onFirstRef()
1740{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001741 run(mName.string(), ANDROID_PRIORITY_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001742}
1743
1744bool AudioPolicyService::AudioCommandThread::threadLoop()
1745{
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001746 nsecs_t waitTime = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001747
1748 mLock.lock();
1749 while (!exitPending())
1750 {
Eric Laurent59a89232014-06-08 14:14:17 -07001751 sp<AudioPolicyService> svc;
1752 while (!mAudioCommands.isEmpty() && !exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001753 nsecs_t curTime = systemTime();
1754 // commands are sorted by increasing time stamp: execute them from index 0 and up
1755 if (mAudioCommands[0]->mTime <= curTime) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001756 sp<AudioCommand> command = mAudioCommands[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001757 mAudioCommands.removeAt(0);
Eric Laurent0ede8922014-05-09 18:04:42 -07001758 mLastCommand = command;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001759
1760 switch (command->mCommand) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001761 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001762 VolumeData *data = (VolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001763 ALOGV("AudioCommandThread() processing set volume stream %d, \
Eric Laurentde070132010-07-13 04:45:46 -07001764 volume %f, output %d", data->mStream, data->mVolume, data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001765 mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07001766 command->mStatus = AudioSystem::setStreamVolume(data->mStream,
1767 data->mVolume,
1768 data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001769 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001770 }break;
1771 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001772 ParametersData *data = (ParametersData *)command->mParam.get();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001773 ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
1774 data->mKeyValuePairs.string(), data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001775 mLock.unlock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001776 command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
Andy Hungfe726a62018-09-27 15:17:25 -07001777 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001778 }break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001779 case SET_VOICE_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001780 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001781 ALOGV("AudioCommandThread() processing set voice volume volume %f",
Eric Laurentde070132010-07-13 04:45:46 -07001782 data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001783 mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001784 command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001785 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001786 }break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001787 case STOP_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001788 StopOutputData *data = (StopOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001789 ALOGV("AudioCommandThread() processing stop output portId %d",
1790 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001791 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001792 if (svc == 0) {
1793 break;
1794 }
1795 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001796 svc->doStopOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001797 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001798 }break;
1799 case RELEASE_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001800 ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001801 ALOGV("AudioCommandThread() processing release output portId %d",
1802 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001803 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001804 if (svc == 0) {
1805 break;
1806 }
1807 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001808 svc->doReleaseOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001809 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001810 }break;
Eric Laurent951f4552014-05-20 10:48:17 -07001811 case CREATE_AUDIO_PATCH: {
1812 CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
1813 ALOGV("AudioCommandThread() processing create audio patch");
1814 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1815 if (af == 0) {
1816 command->mStatus = PERMISSION_DENIED;
1817 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001818 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001819 command->mStatus = af->createAudioPatch(&data->mPatch, &data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001820 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001821 }
1822 } break;
1823 case RELEASE_AUDIO_PATCH: {
1824 ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
1825 ALOGV("AudioCommandThread() processing release audio patch");
1826 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1827 if (af == 0) {
1828 command->mStatus = PERMISSION_DENIED;
1829 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001830 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001831 command->mStatus = af->releaseAudioPatch(data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001832 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001833 }
1834 } break;
Eric Laurentb52c1522014-05-20 11:27:36 -07001835 case UPDATE_AUDIOPORT_LIST: {
1836 ALOGV("AudioCommandThread() processing update audio port list");
Eric Laurent59a89232014-06-08 14:14:17 -07001837 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001838 if (svc == 0) {
1839 break;
1840 }
1841 mLock.unlock();
1842 svc->doOnAudioPortListUpdate();
1843 mLock.lock();
1844 }break;
1845 case UPDATE_AUDIOPATCH_LIST: {
1846 ALOGV("AudioCommandThread() processing update audio patch list");
Eric Laurent59a89232014-06-08 14:14:17 -07001847 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001848 if (svc == 0) {
1849 break;
1850 }
1851 mLock.unlock();
1852 svc->doOnAudioPatchListUpdate();
1853 mLock.lock();
1854 }break;
François Gaffiecfe17322018-11-07 13:41:29 +01001855 case CHANGED_AUDIOVOLUMEGROUP: {
1856 AudioVolumeGroupData *data =
1857 static_cast<AudioVolumeGroupData *>(command->mParam.get());
1858 ALOGV("AudioCommandThread() processing update audio volume group");
1859 svc = mService.promote();
1860 if (svc == 0) {
1861 break;
1862 }
1863 mLock.unlock();
1864 svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
1865 mLock.lock();
1866 }break;
Eric Laurente1715a42014-05-20 11:30:42 -07001867 case SET_AUDIOPORT_CONFIG: {
1868 SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
1869 ALOGV("AudioCommandThread() processing set port config");
1870 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1871 if (af == 0) {
1872 command->mStatus = PERMISSION_DENIED;
1873 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001874 mLock.unlock();
Eric Laurente1715a42014-05-20 11:30:42 -07001875 command->mStatus = af->setAudioPortConfig(&data->mConfig);
Andy Hungfe726a62018-09-27 15:17:25 -07001876 mLock.lock();
Eric Laurente1715a42014-05-20 11:30:42 -07001877 }
1878 } break;
Jean-Michel Trivide801052015-04-14 19:10:14 -07001879 case DYN_POLICY_MIX_STATE_UPDATE: {
1880 DynPolicyMixStateUpdateData *data =
1881 (DynPolicyMixStateUpdateData *)command->mParam.get();
Jean-Michel Trivide801052015-04-14 19:10:14 -07001882 ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
1883 data->mRegId.string(), data->mState);
1884 svc = mService.promote();
1885 if (svc == 0) {
1886 break;
1887 }
1888 mLock.unlock();
1889 svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
1890 mLock.lock();
1891 } break;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001892 case RECORDING_CONFIGURATION_UPDATE: {
1893 RecordingConfigurationUpdateData *data =
1894 (RecordingConfigurationUpdateData *)command->mParam.get();
1895 ALOGV("AudioCommandThread() processing recording configuration update");
1896 svc = mService.promote();
1897 if (svc == 0) {
1898 break;
1899 }
1900 mLock.unlock();
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001901 svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -08001902 &data->mClientConfig, data->mClientEffects,
1903 &data->mDeviceConfig, data->mEffects,
1904 data->mPatchHandle, data->mSource);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001905 mLock.lock();
1906 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001907 case SET_EFFECT_SUSPENDED: {
1908 SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
1909 ALOGV("AudioCommandThread() processing set effect suspended");
1910 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1911 if (af != 0) {
1912 mLock.unlock();
1913 af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
1914 mLock.lock();
1915 }
1916 } break;
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001917 case AUDIO_MODULES_UPDATE: {
1918 ALOGV("AudioCommandThread() processing audio modules update");
1919 svc = mService.promote();
1920 if (svc == 0) {
1921 break;
1922 }
1923 mLock.unlock();
1924 svc->doOnNewAudioModulesAvailable();
1925 mLock.lock();
1926 } break;
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07001927 case ROUTING_UPDATED: {
1928 ALOGV("AudioCommandThread() processing routing update");
1929 svc = mService.promote();
1930 if (svc == 0) {
1931 break;
1932 }
1933 mLock.unlock();
1934 svc->doOnRoutingUpdated();
1935 mLock.lock();
1936 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001937
Eric Laurented726cc2021-07-01 14:26:41 +02001938 case UPDATE_UID_STATES: {
1939 ALOGV("AudioCommandThread() processing updateUID states");
1940 svc = mService.promote();
1941 if (svc == 0) {
1942 break;
1943 }
1944 mLock.unlock();
1945 svc->updateUidStates();
1946 mLock.lock();
1947 } break;
1948
Eric Laurent81dd0f52021-07-05 11:54:40 +02001949 case CHECK_SPATIALIZER: {
1950 ALOGV("AudioCommandThread() processing updateUID states");
1951 svc = mService.promote();
1952 if (svc == 0) {
1953 break;
1954 }
1955 mLock.unlock();
1956 svc->doOnCheckSpatializer();
1957 mLock.lock();
1958 } break;
1959
Mathias Agopian65ab4712010-07-14 17:59:35 -07001960 default:
Steve Block5ff1dd52012-01-05 23:22:43 +00001961 ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001962 }
Eric Laurent0ede8922014-05-09 18:04:42 -07001963 {
1964 Mutex::Autolock _l(command->mLock);
1965 if (command->mWaitStatus) {
1966 command->mWaitStatus = false;
1967 command->mCond.signal();
1968 }
1969 }
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001970 waitTime = -1;
Zach Janga754b4f2015-10-27 01:29:34 +00001971 // release mLock before releasing strong reference on the service as
1972 // AudioPolicyService destructor calls AudioCommandThread::exit() which
1973 // acquires mLock.
1974 mLock.unlock();
1975 svc.clear();
1976 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001977 } else {
1978 waitTime = mAudioCommands[0]->mTime - curTime;
1979 break;
1980 }
1981 }
Zach Janga754b4f2015-10-27 01:29:34 +00001982
1983 // release delayed commands wake lock if the queue is empty
1984 if (mAudioCommands.isEmpty()) {
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07001985 release_wake_lock(mName.string());
Zach Janga754b4f2015-10-27 01:29:34 +00001986 }
1987
1988 // At this stage we have either an empty command queue or the first command in the queue
1989 // has a finite delay. So unless we are exiting it is safe to wait.
1990 if (!exitPending()) {
Eric Laurent59a89232014-06-08 14:14:17 -07001991 ALOGV("AudioCommandThread() going to sleep");
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001992 if (waitTime == -1) {
1993 mWaitWorkCV.wait(mLock);
1994 } else {
1995 mWaitWorkCV.waitRelative(mLock, waitTime);
1996 }
Eric Laurent59a89232014-06-08 14:14:17 -07001997 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001998 }
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07001999 // release delayed commands wake lock before quitting
2000 if (!mAudioCommands.isEmpty()) {
2001 release_wake_lock(mName.string());
2002 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002003 mLock.unlock();
2004 return false;
2005}
2006
2007status_t AudioPolicyService::AudioCommandThread::dump(int fd)
2008{
2009 const size_t SIZE = 256;
2010 char buffer[SIZE];
2011 String8 result;
2012
2013 snprintf(buffer, SIZE, "AudioCommandThread %p Dump\n", this);
2014 result.append(buffer);
2015 write(fd, result.string(), result.size());
2016
Mikhail Naganov12b716c2020-04-30 22:37:43 +00002017 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002018 if (!locked) {
2019 String8 result2(kCmdDeadlockedString);
2020 write(fd, result2.string(), result2.size());
2021 }
2022
2023 snprintf(buffer, SIZE, "- Commands:\n");
2024 result = String8(buffer);
2025 result.append(" Command Time Wait pParam\n");
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002026 for (size_t i = 0; i < mAudioCommands.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002027 mAudioCommands[i]->dump(buffer, SIZE);
2028 result.append(buffer);
2029 }
2030 result.append(" Last Command\n");
Eric Laurent0ede8922014-05-09 18:04:42 -07002031 if (mLastCommand != 0) {
2032 mLastCommand->dump(buffer, SIZE);
2033 result.append(buffer);
2034 } else {
2035 result.append(" none\n");
2036 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002037
2038 write(fd, result.string(), result.size());
2039
Mikhail Naganov12b716c2020-04-30 22:37:43 +00002040 dumpReleaseLock(mLock, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002041
2042 return NO_ERROR;
2043}
2044
Glenn Kastenfff6d712012-01-12 16:38:12 -08002045status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
Eric Laurentde070132010-07-13 04:45:46 -07002046 float volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002047 audio_io_handle_t output,
Eric Laurentde070132010-07-13 04:45:46 -07002048 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002049{
Eric Laurent0ede8922014-05-09 18:04:42 -07002050 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002051 command->mCommand = SET_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002052 sp<VolumeData> data = new VolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002053 data->mStream = stream;
2054 data->mVolume = volume;
2055 data->mIO = output;
2056 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002057 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002058 ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
Eric Laurentde070132010-07-13 04:45:46 -07002059 stream, volume, output);
Eric Laurent0ede8922014-05-09 18:04:42 -07002060 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002061}
2062
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002063status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
Dima Zavinfce7a472011-04-19 22:30:36 -07002064 const char *keyValuePairs,
Eric Laurentde070132010-07-13 04:45:46 -07002065 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002066{
Eric Laurent0ede8922014-05-09 18:04:42 -07002067 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002068 command->mCommand = SET_PARAMETERS;
Eric Laurent0ede8922014-05-09 18:04:42 -07002069 sp<ParametersData> data = new ParametersData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002070 data->mIO = ioHandle;
Dima Zavinfce7a472011-04-19 22:30:36 -07002071 data->mKeyValuePairs = String8(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002072 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002073 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002074 ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
Dima Zavinfce7a472011-04-19 22:30:36 -07002075 keyValuePairs, ioHandle, delayMs);
Eric Laurent0ede8922014-05-09 18:04:42 -07002076 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002077}
2078
2079status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
2080{
Eric Laurent0ede8922014-05-09 18:04:42 -07002081 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002082 command->mCommand = SET_VOICE_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002083 sp<VoiceVolumeData> data = new VoiceVolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002084 data->mVolume = volume;
2085 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002086 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002087 ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
Eric Laurent0ede8922014-05-09 18:04:42 -07002088 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002089}
2090
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002091void AudioPolicyService::AudioCommandThread::setEffectSuspendedCommand(int effectId,
2092 audio_session_t sessionId,
2093 bool suspended)
2094{
2095 sp<AudioCommand> command = new AudioCommand();
2096 command->mCommand = SET_EFFECT_SUSPENDED;
2097 sp<SetEffectSuspendedData> data = new SetEffectSuspendedData();
2098 data->mEffectId = effectId;
2099 data->mSessionId = sessionId;
2100 data->mSuspended = suspended;
2101 command->mParam = data;
2102 ALOGV("AudioCommandThread() adding set suspended effectId %d sessionId %d suspended %d",
2103 effectId, sessionId, suspended);
2104 sendCommand(command);
2105}
2106
2107
Eric Laurentd7fe0862018-07-14 16:48:01 -07002108void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002109{
Eric Laurent0ede8922014-05-09 18:04:42 -07002110 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002111 command->mCommand = STOP_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002112 sp<StopOutputData> data = new StopOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002113 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002114 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002115 ALOGV("AudioCommandThread() adding stop output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002116 sendCommand(command);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002117}
2118
Eric Laurentd7fe0862018-07-14 16:48:01 -07002119void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002120{
Eric Laurent0ede8922014-05-09 18:04:42 -07002121 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002122 command->mCommand = RELEASE_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002123 sp<ReleaseOutputData> data = new ReleaseOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002124 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002125 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002126 ALOGV("AudioCommandThread() adding release output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002127 sendCommand(command);
2128}
2129
Eric Laurent951f4552014-05-20 10:48:17 -07002130status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
2131 const struct audio_patch *patch,
2132 audio_patch_handle_t *handle,
2133 int delayMs)
2134{
2135 status_t status = NO_ERROR;
2136
2137 sp<AudioCommand> command = new AudioCommand();
2138 command->mCommand = CREATE_AUDIO_PATCH;
2139 CreateAudioPatchData *data = new CreateAudioPatchData();
2140 data->mPatch = *patch;
2141 data->mHandle = *handle;
2142 command->mParam = data;
2143 command->mWaitStatus = true;
2144 ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
2145 status = sendCommand(command, delayMs);
2146 if (status == NO_ERROR) {
2147 *handle = data->mHandle;
2148 }
2149 return status;
2150}
2151
2152status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
2153 int delayMs)
2154{
2155 sp<AudioCommand> command = new AudioCommand();
2156 command->mCommand = RELEASE_AUDIO_PATCH;
2157 ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
2158 data->mHandle = handle;
2159 command->mParam = data;
2160 command->mWaitStatus = true;
2161 ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
2162 return sendCommand(command, delayMs);
2163}
2164
Eric Laurentb52c1522014-05-20 11:27:36 -07002165void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
2166{
2167 sp<AudioCommand> command = new AudioCommand();
2168 command->mCommand = UPDATE_AUDIOPORT_LIST;
2169 ALOGV("AudioCommandThread() adding update audio port list");
2170 sendCommand(command);
2171}
2172
Eric Laurented726cc2021-07-01 14:26:41 +02002173void AudioPolicyService::AudioCommandThread::updateUidStatesCommand()
2174{
2175 sp<AudioCommand> command = new AudioCommand();
2176 command->mCommand = UPDATE_UID_STATES;
2177 ALOGV("AudioCommandThread() adding update UID states");
2178 sendCommand(command);
2179}
2180
Eric Laurentb52c1522014-05-20 11:27:36 -07002181void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
2182{
2183 sp<AudioCommand>command = new AudioCommand();
2184 command->mCommand = UPDATE_AUDIOPATCH_LIST;
2185 ALOGV("AudioCommandThread() adding update audio patch list");
2186 sendCommand(command);
2187}
2188
François Gaffiecfe17322018-11-07 13:41:29 +01002189void AudioPolicyService::AudioCommandThread::changeAudioVolumeGroupCommand(volume_group_t group,
2190 int flags)
2191{
2192 sp<AudioCommand>command = new AudioCommand();
2193 command->mCommand = CHANGED_AUDIOVOLUMEGROUP;
2194 AudioVolumeGroupData *data= new AudioVolumeGroupData();
2195 data->mGroup = group;
2196 data->mFlags = flags;
2197 command->mParam = data;
2198 ALOGV("AudioCommandThread() adding audio volume group changed");
2199 sendCommand(command);
2200}
2201
Eric Laurente1715a42014-05-20 11:30:42 -07002202status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
2203 const struct audio_port_config *config, int delayMs)
2204{
2205 sp<AudioCommand> command = new AudioCommand();
2206 command->mCommand = SET_AUDIOPORT_CONFIG;
2207 SetAudioPortConfigData *data = new SetAudioPortConfigData();
2208 data->mConfig = *config;
2209 command->mParam = data;
2210 command->mWaitStatus = true;
2211 ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
2212 return sendCommand(command, delayMs);
2213}
2214
Jean-Michel Trivide801052015-04-14 19:10:14 -07002215void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002216 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -07002217{
2218 sp<AudioCommand> command = new AudioCommand();
2219 command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
2220 DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
2221 data->mRegId = regId;
2222 data->mState = state;
2223 command->mParam = data;
2224 ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
2225 regId.string(), state);
2226 sendCommand(command);
2227}
2228
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002229void AudioPolicyService::AudioCommandThread::recordingConfigurationUpdateCommand(
Eric Laurenta9f86652018-11-28 17:23:11 -08002230 int event,
2231 const record_client_info_t *clientInfo,
2232 const audio_config_base_t *clientConfig,
2233 std::vector<effect_descriptor_t> clientEffects,
2234 const audio_config_base_t *deviceConfig,
2235 std::vector<effect_descriptor_t> effects,
2236 audio_patch_handle_t patchHandle,
2237 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002238{
2239 sp<AudioCommand>command = new AudioCommand();
2240 command->mCommand = RECORDING_CONFIGURATION_UPDATE;
2241 RecordingConfigurationUpdateData *data = new RecordingConfigurationUpdateData();
2242 data->mEvent = event;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002243 data->mClientInfo = *clientInfo;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002244 data->mClientConfig = *clientConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002245 data->mClientEffects = clientEffects;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002246 data->mDeviceConfig = *deviceConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002247 data->mEffects = effects;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002248 data->mPatchHandle = patchHandle;
Eric Laurenta9f86652018-11-28 17:23:11 -08002249 data->mSource = source;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002250 command->mParam = data;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002251 ALOGV("AudioCommandThread() adding recording configuration update event %d, source %d uid %u",
2252 event, clientInfo->source, clientInfo->uid);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002253 sendCommand(command);
2254}
2255
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002256void AudioPolicyService::AudioCommandThread::audioModulesUpdateCommand()
2257{
2258 sp<AudioCommand> command = new AudioCommand();
2259 command->mCommand = AUDIO_MODULES_UPDATE;
2260 sendCommand(command);
2261}
2262
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002263void AudioPolicyService::AudioCommandThread::routingChangedCommand()
2264{
2265 sp<AudioCommand>command = new AudioCommand();
2266 command->mCommand = ROUTING_UPDATED;
2267 ALOGV("AudioCommandThread() adding routing update");
2268 sendCommand(command);
2269}
2270
Eric Laurent81dd0f52021-07-05 11:54:40 +02002271void AudioPolicyService::AudioCommandThread::checkSpatializerCommand()
2272{
2273 sp<AudioCommand>command = new AudioCommand();
2274 command->mCommand = CHECK_SPATIALIZER;
2275 ALOGV("AudioCommandThread() adding check spatializer");
2276 sendCommand(command);
2277}
2278
Eric Laurent0ede8922014-05-09 18:04:42 -07002279status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
2280{
2281 {
2282 Mutex::Autolock _l(mLock);
2283 insertCommand_l(command, delayMs);
2284 mWaitWorkCV.signal();
2285 }
2286 Mutex::Autolock _l(command->mLock);
2287 while (command->mWaitStatus) {
2288 nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
2289 if (command->mCond.waitRelative(command->mLock, timeOutNs) != NO_ERROR) {
2290 command->mStatus = TIMED_OUT;
2291 command->mWaitStatus = false;
2292 }
2293 }
2294 return command->mStatus;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002295}
2296
Mathias Agopian65ab4712010-07-14 17:59:35 -07002297// insertCommand_l() must be called with mLock held
Eric Laurent0ede8922014-05-09 18:04:42 -07002298void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002299{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002300 ssize_t i; // not size_t because i will count down to -1
Eric Laurent0ede8922014-05-09 18:04:42 -07002301 Vector < sp<AudioCommand> > removedCommands;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002302 command->mTime = systemTime() + milliseconds(delayMs);
2303
2304 // acquire wake lock to make sure delayed commands are processed
Eric Laurentbfb1b832013-01-07 09:53:42 -08002305 if (mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002306 acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.string());
2307 }
2308
2309 // check same pending commands with later time stamps and eliminate them
Ivan Lozano5ff158f2017-10-30 09:06:24 -07002310 for (i = (ssize_t)mAudioCommands.size()-1; i >= 0; i--) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002311 sp<AudioCommand> command2 = mAudioCommands[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07002312 // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
2313 if (command2->mTime <= command->mTime) break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002314
2315 // create audio patch or release audio patch commands are equivalent
2316 // with regard to filtering
2317 if ((command->mCommand == CREATE_AUDIO_PATCH) ||
2318 (command->mCommand == RELEASE_AUDIO_PATCH)) {
2319 if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
2320 (command2->mCommand != RELEASE_AUDIO_PATCH)) {
2321 continue;
2322 }
2323 } else if (command2->mCommand != command->mCommand) continue;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002324
2325 switch (command->mCommand) {
2326 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002327 ParametersData *data = (ParametersData *)command->mParam.get();
2328 ParametersData *data2 = (ParametersData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002329 if (data->mIO != data2->mIO) break;
Steve Block3856b092011-10-20 11:56:00 +01002330 ALOGV("Comparing parameter command %s to new command %s",
Eric Laurentde070132010-07-13 04:45:46 -07002331 data2->mKeyValuePairs.string(), data->mKeyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002332 AudioParameter param = AudioParameter(data->mKeyValuePairs);
2333 AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
2334 for (size_t j = 0; j < param.size(); j++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002335 String8 key;
2336 String8 value;
2337 param.getAt(j, key, value);
2338 for (size_t k = 0; k < param2.size(); k++) {
2339 String8 key2;
2340 String8 value2;
2341 param2.getAt(k, key2, value2);
2342 if (key2 == key) {
2343 param2.remove(key2);
2344 ALOGV("Filtering out parameter %s", key2.string());
2345 break;
2346 }
2347 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002348 }
2349 // if all keys have been filtered out, remove the command.
2350 // otherwise, update the key value pairs
2351 if (param2.size() == 0) {
2352 removedCommands.add(command2);
2353 } else {
2354 data2->mKeyValuePairs = param2.toString();
2355 }
Eric Laurent21e54562013-09-23 12:08:05 -07002356 command->mTime = command2->mTime;
2357 // force delayMs to non 0 so that code below does not request to wait for
2358 // command status as the command is now delayed
2359 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002360 } break;
2361
2362 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002363 VolumeData *data = (VolumeData *)command->mParam.get();
2364 VolumeData *data2 = (VolumeData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002365 if (data->mIO != data2->mIO) break;
2366 if (data->mStream != data2->mStream) break;
Steve Block3856b092011-10-20 11:56:00 +01002367 ALOGV("Filtering out volume command on output %d for stream %d",
Eric Laurentde070132010-07-13 04:45:46 -07002368 data->mIO, data->mStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002369 removedCommands.add(command2);
Eric Laurent21e54562013-09-23 12:08:05 -07002370 command->mTime = command2->mTime;
2371 // force delayMs to non 0 so that code below does not request to wait for
2372 // command status as the command is now delayed
2373 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002374 } break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002375
Eric Laurentbaf35fe2016-07-27 15:36:53 -07002376 case SET_VOICE_VOLUME: {
2377 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
2378 VoiceVolumeData *data2 = (VoiceVolumeData *)command2->mParam.get();
2379 ALOGV("Filtering out voice volume command value %f replaced by %f",
2380 data2->mVolume, data->mVolume);
2381 removedCommands.add(command2);
2382 command->mTime = command2->mTime;
2383 // force delayMs to non 0 so that code below does not request to wait for
2384 // command status as the command is now delayed
2385 delayMs = 1;
2386 } break;
2387
Eric Laurente45b48a2014-09-04 16:40:57 -07002388 case CREATE_AUDIO_PATCH:
2389 case RELEASE_AUDIO_PATCH: {
2390 audio_patch_handle_t handle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002391 struct audio_patch patch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002392 if (command->mCommand == CREATE_AUDIO_PATCH) {
2393 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002394 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002395 } else {
2396 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
Mikhail Naganov7be71d22018-05-23 16:51:46 -07002397 memset(&patch, 0, sizeof(patch));
Eric Laurente45b48a2014-09-04 16:40:57 -07002398 }
2399 audio_patch_handle_t handle2;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002400 struct audio_patch patch2;
Eric Laurente45b48a2014-09-04 16:40:57 -07002401 if (command2->mCommand == CREATE_AUDIO_PATCH) {
2402 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002403 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002404 } else {
2405 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
Glenn Kastenf60b6b62015-07-06 10:53:26 -07002406 memset(&patch2, 0, sizeof(patch2));
Eric Laurente45b48a2014-09-04 16:40:57 -07002407 }
2408 if (handle != handle2) break;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002409 /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
2410 same output. */
2411 if( (command->mCommand == CREATE_AUDIO_PATCH) &&
2412 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
2413 bool isOutputDiff = false;
2414 if (patch.num_sources == patch2.num_sources) {
2415 for (unsigned count = 0; count < patch.num_sources; count++) {
2416 if (patch.sources[count].id != patch2.sources[count].id) {
2417 isOutputDiff = true;
2418 break;
2419 }
2420 }
2421 if (isOutputDiff)
2422 break;
2423 }
2424 }
Eric Laurente45b48a2014-09-04 16:40:57 -07002425 ALOGV("Filtering out %s audio patch command for handle %d",
2426 (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
2427 removedCommands.add(command2);
2428 command->mTime = command2->mTime;
2429 // force delayMs to non 0 so that code below does not request to wait for
2430 // command status as the command is now delayed
2431 delayMs = 1;
2432 } break;
2433
Jean-Michel Trivide801052015-04-14 19:10:14 -07002434 case DYN_POLICY_MIX_STATE_UPDATE: {
2435
2436 } break;
2437
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002438 case RECORDING_CONFIGURATION_UPDATE: {
2439
2440 } break;
2441
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002442 case ROUTING_UPDATED: {
2443
2444 } break;
2445
Mathias Agopian65ab4712010-07-14 17:59:35 -07002446 default:
2447 break;
2448 }
2449 }
2450
2451 // remove filtered commands
2452 for (size_t j = 0; j < removedCommands.size(); j++) {
2453 // removed commands always have time stamps greater than current command
2454 for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002455 if (mAudioCommands[k].get() == removedCommands[j].get()) {
Steve Block3856b092011-10-20 11:56:00 +01002456 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002457 mAudioCommands.removeAt(k);
2458 break;
2459 }
2460 }
2461 }
2462 removedCommands.clear();
2463
Eric Laurentaa79bef2015-01-15 14:33:51 -08002464 // Disable wait for status if delay is not 0.
2465 // Except for create audio patch command because the returned patch handle
2466 // is needed by audio policy manager
2467 if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
Eric Laurentcec4abb2012-07-03 12:23:02 -07002468 command->mWaitStatus = false;
2469 }
Eric Laurentcec4abb2012-07-03 12:23:02 -07002470
Mathias Agopian65ab4712010-07-14 17:59:35 -07002471 // insert command at the right place according to its time stamp
Eric Laurent1e693b52014-07-09 15:03:28 -07002472 ALOGV("inserting command: %d at index %zd, num commands %zu",
2473 command->mCommand, i+1, mAudioCommands.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002474 mAudioCommands.insertAt(command, i + 1);
2475}
2476
2477void AudioPolicyService::AudioCommandThread::exit()
2478{
Steve Block3856b092011-10-20 11:56:00 +01002479 ALOGV("AudioCommandThread::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002480 {
2481 AutoMutex _l(mLock);
2482 requestExit();
2483 mWaitWorkCV.signal();
2484 }
Zach Janga754b4f2015-10-27 01:29:34 +00002485 // Note that we can call it from the thread loop if all other references have been released
2486 // but it will safely return WOULD_BLOCK in this case
Mathias Agopian65ab4712010-07-14 17:59:35 -07002487 requestExitAndWait();
2488}
2489
2490void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
2491{
2492 snprintf(buffer, size, " %02d %06d.%03d %01u %p\n",
2493 mCommand,
2494 (int)ns2s(mTime),
2495 (int)ns2ms(mTime)%1000,
2496 mWaitStatus,
Eric Laurent0ede8922014-05-09 18:04:42 -07002497 mParam.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002498}
2499
Dima Zavinfce7a472011-04-19 22:30:36 -07002500/******* helpers for the service_ops callbacks defined below *********/
2501void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
2502 const char *keyValuePairs,
2503 int delayMs)
2504{
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002505 mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
Dima Zavinfce7a472011-04-19 22:30:36 -07002506 delayMs);
2507}
2508
2509int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
2510 float volume,
2511 audio_io_handle_t output,
2512 int delayMs)
2513{
Glenn Kastenfff6d712012-01-12 16:38:12 -08002514 return (int)mAudioCommandThread->volumeCommand(stream, volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002515 output, delayMs);
Dima Zavinfce7a472011-04-19 22:30:36 -07002516}
2517
Dima Zavinfce7a472011-04-19 22:30:36 -07002518int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
2519{
2520 return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
2521}
2522
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002523void AudioPolicyService::setEffectSuspended(int effectId,
2524 audio_session_t sessionId,
2525 bool suspended)
2526{
2527 mAudioCommandThread->setEffectSuspendedCommand(effectId, sessionId, suspended);
2528}
2529
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002530Status AudioPolicyService::onNewAudioModulesAvailable()
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002531{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07002532 mOutputCommandThread->audioModulesUpdateCommand();
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002533 return Status::ok();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002534}
2535
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002536
Dima Zavinfce7a472011-04-19 22:30:36 -07002537extern "C" {
Eric Laurent2d388ec2014-03-07 13:25:54 -08002538audio_module_handle_t aps_load_hw_module(void *service __unused,
2539 const char *name);
2540audio_io_handle_t aps_open_output(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002541 audio_devices_t *pDevices,
2542 uint32_t *pSamplingRate,
2543 audio_format_t *pFormat,
2544 audio_channel_mask_t *pChannelMask,
2545 uint32_t *pLatencyMs,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002546 audio_output_flags_t flags);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002547
Eric Laurent2d388ec2014-03-07 13:25:54 -08002548audio_io_handle_t aps_open_output_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002549 audio_module_handle_t module,
2550 audio_devices_t *pDevices,
2551 uint32_t *pSamplingRate,
2552 audio_format_t *pFormat,
2553 audio_channel_mask_t *pChannelMask,
2554 uint32_t *pLatencyMs,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002555 audio_output_flags_t flags,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002556 const audio_offload_info_t *offloadInfo);
2557audio_io_handle_t aps_open_dup_output(void *service __unused,
Dima Zavinfce7a472011-04-19 22:30:36 -07002558 audio_io_handle_t output1,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002559 audio_io_handle_t output2);
2560int aps_close_output(void *service __unused, audio_io_handle_t output);
2561int aps_suspend_output(void *service __unused, audio_io_handle_t output);
2562int aps_restore_output(void *service __unused, audio_io_handle_t output);
2563audio_io_handle_t aps_open_input(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002564 audio_devices_t *pDevices,
2565 uint32_t *pSamplingRate,
2566 audio_format_t *pFormat,
2567 audio_channel_mask_t *pChannelMask,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002568 audio_in_acoustics_t acoustics __unused);
2569audio_io_handle_t aps_open_input_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002570 audio_module_handle_t module,
2571 audio_devices_t *pDevices,
2572 uint32_t *pSamplingRate,
2573 audio_format_t *pFormat,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002574 audio_channel_mask_t *pChannelMask);
2575int aps_close_input(void *service __unused, audio_io_handle_t input);
2576int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
Glenn Kastend848eb42016-03-08 13:42:11 -08002577int aps_move_effects(void *service __unused, audio_session_t session,
Dima Zavinfce7a472011-04-19 22:30:36 -07002578 audio_io_handle_t src_output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002579 audio_io_handle_t dst_output);
2580char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
2581 const char *keys);
2582void aps_set_parameters(void *service, audio_io_handle_t io_handle,
2583 const char *kv_pairs, int delay_ms);
2584int aps_set_stream_volume(void *service, audio_stream_type_t stream,
Dima Zavinfce7a472011-04-19 22:30:36 -07002585 float volume, audio_io_handle_t output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002586 int delay_ms);
Eric Laurent2d388ec2014-03-07 13:25:54 -08002587int aps_set_voice_volume(void *service, float volume, int delay_ms);
2588};
Dima Zavinfce7a472011-04-19 22:30:36 -07002589
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08002590} // namespace android