blob: 443b9f72036e8d78ffaedeec02cbb09c89f18f6c [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 }
Eric Laurent15903592022-02-24 20:44:36 +0100400 size_t numActiveTracks = countActiveClientsOnOutput_l(newOutput);
Eric Laurent39095982021-08-24 18:29:27 +0200401 mLock.unlock();
402 // It is OK to call detachOutput() is none is already attached.
403 mSpatializer->detachOutput();
404 if (status != NO_ERROR || newOutput == AUDIO_IO_HANDLE_NONE) {
Eric Laurent81dd0f52021-07-05 11:54:40 +0200405 mLock.lock();
Eric Laurent39095982021-08-24 18:29:27 +0200406 return;
407 }
Eric Laurent15903592022-02-24 20:44:36 +0100408 status = mSpatializer->attachOutput(newOutput, numActiveTracks);
Eric Laurent39095982021-08-24 18:29:27 +0200409 mLock.lock();
410 if (status != NO_ERROR) {
411 mAudioPolicyManager->releaseSpatializerOutput(newOutput);
412 }
413 } else if (mSpatializer->getLevel() == media::SpatializationLevel::NONE
414 && mSpatializer->getOutput() != AUDIO_IO_HANDLE_NONE) {
415 mLock.unlock();
416 audio_io_handle_t output = mSpatializer->detachOutput();
417 mLock.lock();
418 if (output != AUDIO_IO_HANDLE_NONE) {
419 mAudioPolicyManager->releaseSpatializerOutput(output);
Eric Laurent81dd0f52021-07-05 11:54:40 +0200420 }
421 }
422 }
423}
424
Eric Laurent15903592022-02-24 20:44:36 +0100425size_t AudioPolicyService::countActiveClientsOnOutput_l(audio_io_handle_t output) REQUIRES(mLock) {
426 size_t count = 0;
427 for (size_t i = 0; i < mAudioPlaybackClients.size(); i++) {
428 auto client = mAudioPlaybackClients.valueAt(i);
429 if (client->io == output && client->active) {
430 count++;
431 }
432 }
433 return count;
434}
435
436void AudioPolicyService::onUpdateActiveSpatializerTracks_l() {
437 if (mSpatializer == nullptr) {
438 return;
439 }
440 mOutputCommandThread->updateActiveSpatializerTracksCommand();
441}
442
443void AudioPolicyService::doOnUpdateActiveSpatializerTracks()
444{
445 Mutex::Autolock _l(mLock);
446 if (mSpatializer == nullptr) {
447 return;
448 }
449 mSpatializer->updateActiveTracks(countActiveClientsOnOutput_l(mSpatializer->getOutput()));
450}
451
452
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800453status_t AudioPolicyService::clientCreateAudioPatch(const struct audio_patch *patch,
454 audio_patch_handle_t *handle,
455 int delayMs)
456{
457 return mAudioCommandThread->createAudioPatchCommand(patch, handle, delayMs);
458}
459
460status_t AudioPolicyService::clientReleaseAudioPatch(audio_patch_handle_t handle,
461 int delayMs)
462{
463 return mAudioCommandThread->releaseAudioPatchCommand(handle, delayMs);
464}
465
Eric Laurente1715a42014-05-20 11:30:42 -0700466status_t AudioPolicyService::clientSetAudioPortConfig(const struct audio_port_config *config,
467 int delayMs)
468{
469 return mAudioCommandThread->setAudioPortConfigCommand(config, delayMs);
470}
471
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800472AudioPolicyService::NotificationClient::NotificationClient(
473 const sp<AudioPolicyService>& service,
474 const sp<media::IAudioPolicyServiceClient>& client,
475 uid_t uid,
476 pid_t pid)
luochaojiang908c7d72018-06-21 14:58:04 +0800477 : mService(service), mUid(uid), mPid(pid), mAudioPolicyServiceClient(client),
François Gaffiecfe17322018-11-07 13:41:29 +0100478 mAudioPortCallbacksEnabled(false), mAudioVolumeGroupCallbacksEnabled(false)
Eric Laurentb52c1522014-05-20 11:27:36 -0700479{
480}
481
482AudioPolicyService::NotificationClient::~NotificationClient()
483{
484}
485
486void AudioPolicyService::NotificationClient::binderDied(const wp<IBinder>& who __unused)
487{
488 sp<NotificationClient> keep(this);
489 sp<AudioPolicyService> service = mService.promote();
490 if (service != 0) {
luochaojiang908c7d72018-06-21 14:58:04 +0800491 service->removeNotificationClient(mUid, mPid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700492 }
493}
494
495void AudioPolicyService::NotificationClient::onAudioPortListUpdate()
496{
Eric Laurente8726fe2015-06-26 09:39:24 -0700497 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700498 mAudioPolicyServiceClient->onAudioPortListUpdate();
499 }
500}
501
502void AudioPolicyService::NotificationClient::onAudioPatchListUpdate()
503{
Eric Laurente8726fe2015-06-26 09:39:24 -0700504 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700505 mAudioPolicyServiceClient->onAudioPatchListUpdate();
506 }
507}
Eric Laurent57dae992011-07-24 13:36:09 -0700508
Pattydd807582021-11-04 21:01:03 +0800509void AudioPolicyService::NotificationClient::onAudioVolumeGroupChanged(volume_group_t group,
François Gaffiecfe17322018-11-07 13:41:29 +0100510 int flags)
511{
512 if (mAudioPolicyServiceClient != 0 && mAudioVolumeGroupCallbacksEnabled) {
513 mAudioPolicyServiceClient->onAudioVolumeGroupChanged(group, flags);
514 }
515}
516
517
Jean-Michel Trivide801052015-04-14 19:10:14 -0700518void AudioPolicyService::NotificationClient::onDynamicPolicyMixStateUpdate(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700519 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700520{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700521 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800522 mAudioPolicyServiceClient->onDynamicPolicyMixStateUpdate(
523 legacy2aidl_String8_string(regId).value(), state);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800524 }
525}
526
527void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate(
Eric Laurenta9f86652018-11-28 17:23:11 -0800528 int event,
529 const record_client_info_t *clientInfo,
530 const audio_config_base_t *clientConfig,
531 std::vector<effect_descriptor_t> clientEffects,
532 const audio_config_base_t *deviceConfig,
533 std::vector<effect_descriptor_t> effects,
534 audio_patch_handle_t patchHandle,
535 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800536{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700537 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800538 status_t status = [&]() -> status_t {
539 int32_t eventAidl = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(event));
540 media::RecordClientInfo clientInfoAidl = VALUE_OR_RETURN_STATUS(
541 legacy2aidl_record_client_info_t_RecordClientInfo(*clientInfo));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700542 AudioConfigBase clientConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700543 legacy2aidl_audio_config_base_t_AudioConfigBase(
544 *clientConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800545 std::vector<media::EffectDescriptor> clientEffectsAidl = VALUE_OR_RETURN_STATUS(
546 convertContainer<std::vector<media::EffectDescriptor>>(
547 clientEffects,
548 legacy2aidl_effect_descriptor_t_EffectDescriptor));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700549 AudioConfigBase deviceConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700550 legacy2aidl_audio_config_base_t_AudioConfigBase(
551 *deviceConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800552 std::vector<media::EffectDescriptor> effectsAidl = VALUE_OR_RETURN_STATUS(
553 convertContainer<std::vector<media::EffectDescriptor>>(
554 effects,
555 legacy2aidl_effect_descriptor_t_EffectDescriptor));
556 int32_t patchHandleAidl = VALUE_OR_RETURN_STATUS(
557 legacy2aidl_audio_patch_handle_t_int32_t(patchHandle));
Mikhail Naganovddceecc2021-09-03 13:58:56 -0700558 media::audio::common::AudioSource sourceAidl = VALUE_OR_RETURN_STATUS(
559 legacy2aidl_audio_source_t_AudioSource(source));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800560 return aidl_utils::statusTFromBinderStatus(
561 mAudioPolicyServiceClient->onRecordingConfigurationUpdate(eventAidl,
562 clientInfoAidl,
563 clientConfigAidl,
564 clientEffectsAidl,
565 deviceConfigAidl,
566 effectsAidl,
567 patchHandleAidl,
568 sourceAidl));
569 }();
570 ALOGW_IF(status != OK, "onRecordingConfigurationUpdate() failed: %d", status);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700571 }
572}
573
Eric Laurente8726fe2015-06-26 09:39:24 -0700574void AudioPolicyService::NotificationClient::setAudioPortCallbacksEnabled(bool enabled)
575{
576 mAudioPortCallbacksEnabled = enabled;
577}
578
François Gaffiecfe17322018-11-07 13:41:29 +0100579void AudioPolicyService::NotificationClient::setAudioVolumeGroupCallbacksEnabled(bool enabled)
580{
581 mAudioVolumeGroupCallbacksEnabled = enabled;
582}
Eric Laurente8726fe2015-06-26 09:39:24 -0700583
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700584void AudioPolicyService::NotificationClient::onRoutingUpdated()
585{
586 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
587 mAudioPolicyServiceClient->onRoutingUpdated();
588 }
589}
590
Mathias Agopian65ab4712010-07-14 17:59:35 -0700591void AudioPolicyService::binderDied(const wp<IBinder>& who) {
Glenn Kasten411e4472012-11-02 10:00:06 -0700592 ALOGW("binderDied() %p, calling pid %d", who.unsafe_get(),
Eric Laurentde070132010-07-13 04:45:46 -0700593 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700594}
595
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000596static bool dumpTryLock(Mutex& mutex) ACQUIRE(mutex) NO_THREAD_SAFETY_ANALYSIS
Mathias Agopian65ab4712010-07-14 17:59:35 -0700597{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000598 return mutex.timedLock(kDumpLockTimeoutNs) == NO_ERROR;
599}
600
601static void dumpReleaseLock(Mutex& mutex, bool locked) RELEASE(mutex) NO_THREAD_SAFETY_ANALYSIS
602{
603 if (locked) mutex.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700604}
605
606status_t AudioPolicyService::dumpInternals(int fd)
607{
608 const size_t SIZE = 256;
609 char buffer[SIZE];
610 String8 result;
611
Eric Laurentdce54a12014-03-10 12:19:46 -0700612 snprintf(buffer, SIZE, "AudioPolicyManager: %p\n", mAudioPolicyManager);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700613 result.append(buffer);
614 snprintf(buffer, SIZE, "Command Thread: %p\n", mAudioCommandThread.get());
615 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700616
Hayden Gomes524159d2019-12-23 14:41:47 -0800617 snprintf(buffer, SIZE, "Supported System Usages:\n");
618 result.append(buffer);
619 for (std::vector<audio_usage_t>::iterator it = mSupportedSystemUsages.begin();
620 it != mSupportedSystemUsages.end(); ++it) {
621 snprintf(buffer, SIZE, "\t%d\n", *it);
622 result.append(buffer);
623 }
624
Mathias Agopian65ab4712010-07-14 17:59:35 -0700625 write(fd, result.string(), result.size());
Oscar Azucena829d90d2022-01-28 17:17:56 -0800626
627 mUidPolicy->dumpInternals(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700628 return NO_ERROR;
629}
630
Eric Laurente8c8b432018-10-17 10:08:02 -0700631void AudioPolicyService::updateUidStates()
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800632{
Eric Laurente8c8b432018-10-17 10:08:02 -0700633 Mutex::Autolock _l(mLock);
634 updateUidStates_l();
635}
636
637void AudioPolicyService::updateUidStates_l()
638{
Eric Laurent4eb58f12018-12-07 16:41:02 -0800639// Go over all active clients and allow capture (does not force silence) in the
640// following cases:
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800641// The client is in the active assistant list
642// AND is TOP
643// AND an accessibility service is TOP
644// AND source is either VOICE_RECOGNITION OR HOTWORD
645// OR there is no active privacy sensitive capture or call
646// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
647// AND source is VOICE_RECOGNITION OR HOTWORD
648// The client is an assistant AND active assistant is not being used
Evan Severson1f700cd2021-02-10 13:10:37 -0800649// AND an accessibility service is on TOP or a RTT call is active
Eric Laurent589171c2019-07-25 18:04:29 -0700650// AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800651// OR there is no active privacy sensitive capture or call
Evan Severson1f700cd2021-02-10 13:10:37 -0800652// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800653// AND is TOP most recent assistant and uses VOICE_RECOGNITION or HOTWORD
654// OR there is no top recent assistant and source is HOTWORD
Evan Severson1f700cd2021-02-10 13:10:37 -0800655// OR The client is an accessibility service
656// AND Is on TOP
657// AND the source is VOICE_RECOGNITION or HOTWORD
658// OR The assistant is not on TOP
Eric Laurent589171c2019-07-25 18:04:29 -0700659// AND there is no active privacy sensitive capture or call
660// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Evan Severson1f700cd2021-02-10 13:10:37 -0800661// AND is on TOP
662// AND the source is VOICE_RECOGNITION or HOTWORD
663// OR the client source is virtual (remote submix, call audio TX or RX...)
664// OR the client source is HOTWORD
665// AND is on TOP
666// OR all active clients are using HOTWORD source
667// AND no call is active
668// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
669// OR the client is the current InputMethodService
670// AND a RTT call is active AND the source is VOICE_RECOGNITION
671// OR Any client
672// AND The assistant is not on TOP
673// AND is on TOP or latest started
674// AND there is no active privacy sensitive capture or call
675// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4eb58f12018-12-07 16:41:02 -0800676
Eric Laurent4e947da2019-10-17 15:24:06 -0700677
Eric Laurent4eb58f12018-12-07 16:41:02 -0800678 sp<AudioRecordClient> topActive;
679 sp<AudioRecordClient> latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800680 sp<AudioRecordClient> topSensitiveActive;
Eric Laurentb809a752020-06-29 09:53:13 -0700681 sp<AudioRecordClient> latestSensitiveActiveOrComm;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800682 sp<AudioRecordClient> latestActiveAssistant;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700683
Eric Laurenta46bedb2018-12-07 18:01:26 -0800684 nsecs_t topStartNs = 0;
685 nsecs_t latestStartNs = 0;
Eric Laurentc21d5692020-02-25 10:24:36 -0800686 nsecs_t topSensitiveStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800687 nsecs_t latestSensitiveStartNs = 0;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800688 nsecs_t latestAssistantStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800689 bool isA11yOnTop = mUidPolicy->isA11yOnTop();
690 bool isAssistantOnTop = false;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800691 bool useActiveAssistantList = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800692 bool isSensitiveActive = false;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700693 bool isInCall = mPhoneState == AUDIO_MODE_IN_CALL;
Eric Laurentc21d5692020-02-25 10:24:36 -0800694 bool isInCommunication = mPhoneState == AUDIO_MODE_IN_COMMUNICATION;
695 bool rttCallActive = (isInCall || isInCommunication)
Eric Laurent6ede98f2019-06-11 14:50:30 -0700696 && mUidPolicy->isRttEnabled();
Eric Laurent4e947da2019-10-17 15:24:06 -0700697 bool onlyHotwordActive = true;
Eric Laurentb809a752020-06-29 09:53:13 -0700698 bool isPhoneStateOwnerActive = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800699
Michael Groovercfd28302018-12-11 19:16:46 -0800700 // if Sensor Privacy is enabled then all recordings should be silenced.
701 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
702 silenceAllRecordings_l();
703 return;
704 }
705
Eric Laurente8c8b432018-10-17 10:08:02 -0700706 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
707 sp<AudioRecordClient> current = mAudioRecordClients[i];
Svet Ganov33761132021-05-13 22:51:08 +0000708 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
709 current->attributionSource.uid));
Evan Severson1f700cd2021-02-10 13:10:37 -0800710 if (!current->active) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700711 continue;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800712 }
Eric Laurent1ff16a72019-03-14 18:35:04 -0700713
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700714 app_state_t appState = apmStatFromAmState(mUidPolicy->getUidState(currentUid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700715 // clients which app is in IDLE state are not eligible for top active or
716 // latest active
717 if (appState == APP_STATE_IDLE) {
718 continue;
719 }
720
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700721 bool isAccessibility = mUidPolicy->isA11yUid(currentUid);
Eric Laurent14a88632020-07-16 12:28:30 -0700722 // Clients capturing for Accessibility services or virtual sources are not considered
Eric Laurentc21d5692020-02-25 10:24:36 -0800723 // for top or latest active to avoid masking regular clients started before
Eric Laurent14a88632020-07-16 12:28:30 -0700724 if (!isAccessibility && !isVirtualSource(current->attributes.source)) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700725 bool isAssistant = mUidPolicy->isAssistantUid(currentUid);
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800726 bool isActiveAssistant = mUidPolicy->isActiveAssistantUid(currentUid);
Eric Laurentc21d5692020-02-25 10:24:36 -0800727 bool isPrivacySensitive =
728 (current->attributes.flags & AUDIO_FLAG_CAPTURE_PRIVATE) != 0;
Eric Laurentb809a752020-06-29 09:53:13 -0700729
Eric Laurentc21d5692020-02-25 10:24:36 -0800730 if (appState == APP_STATE_TOP) {
731 if (isPrivacySensitive) {
732 if (current->startTimeNs > topSensitiveStartNs) {
733 topSensitiveActive = current;
734 topSensitiveStartNs = current->startTimeNs;
735 }
736 } else {
737 if (current->startTimeNs > topStartNs) {
738 topActive = current;
739 topStartNs = current->startTimeNs;
740 }
741 }
742 if (isAssistant) {
743 isAssistantOnTop = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800744 if (isActiveAssistant) {
745 useActiveAssistantList = true;
746 } else if (!useActiveAssistantList) {
747 if (current->startTimeNs > latestAssistantStartNs) {
748 latestActiveAssistant = current;
749 latestAssistantStartNs = current->startTimeNs;
750 }
751 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800752 }
Eric Laurenta46bedb2018-12-07 18:01:26 -0800753 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800754 // Clients capturing for HOTWORD are not considered
755 // for latest active to avoid masking regular clients started before
756 if (!(current->attributes.source == AUDIO_SOURCE_HOTWORD
757 || ((isA11yOnTop || rttCallActive) && isAssistant))) {
758 if (isPrivacySensitive) {
Eric Laurentb809a752020-06-29 09:53:13 -0700759 // if audio mode is IN_COMMUNICATION, make sure the audio mode owner
760 // is marked latest sensitive active even if another app qualifies.
761 if (current->startTimeNs > latestSensitiveStartNs
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700762 || (isInCommunication && currentUid == mPhoneStateOwnerUid)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700763 if (!isInCommunication || latestSensitiveActiveOrComm == nullptr
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700764 || VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000765 latestSensitiveActiveOrComm->attributionSource.uid))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700766 != mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700767 latestSensitiveActiveOrComm = current;
768 latestSensitiveStartNs = current->startTimeNs;
769 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800770 }
771 isSensitiveActive = true;
772 } else {
773 if (current->startTimeNs > latestStartNs) {
774 latestActive = current;
775 latestStartNs = current->startTimeNs;
776 }
777 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800778 }
779 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700780 if (current->attributes.source != AUDIO_SOURCE_HOTWORD) {
781 onlyHotwordActive = false;
782 }
Eric Laurentb0eff0f2021-11-09 16:05:49 +0100783 if (currentUid == mPhoneStateOwnerUid &&
784 !isVirtualSource(current->attributes.source)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700785 isPhoneStateOwnerActive = true;
786 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800787 }
788
Eric Laurent1ff16a72019-03-14 18:35:04 -0700789 // if no active client with UI on Top, consider latest active as top
790 if (topActive == nullptr) {
791 topActive = latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800792 topStartNs = latestStartNs;
793 }
794 if (topSensitiveActive == nullptr) {
Eric Laurentb809a752020-06-29 09:53:13 -0700795 topSensitiveActive = latestSensitiveActiveOrComm;
Eric Laurentc21d5692020-02-25 10:24:36 -0800796 topSensitiveStartNs = latestSensitiveStartNs;
Eric Laurentb809a752020-06-29 09:53:13 -0700797 } else if (latestSensitiveActiveOrComm != nullptr) {
798 // if audio mode is IN_COMMUNICATION, favor audio mode owner over an app with
799 // foreground UI in case both are capturing with privacy sensitive flag.
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700800 uid_t latestActiveUid = VALUE_OR_FATAL(
Svet Ganov33761132021-05-13 22:51:08 +0000801 aidl2legacy_int32_t_uid_t(latestSensitiveActiveOrComm->attributionSource.uid));
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700802 if (isInCommunication && latestActiveUid == mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700803 topSensitiveActive = latestSensitiveActiveOrComm;
804 topSensitiveStartNs = latestSensitiveStartNs;
805 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800806 }
807
808 // If both privacy sensitive and regular capture are active:
809 // if the regular capture is privileged
810 // allow concurrency
811 // else
812 // favor the privacy sensitive case
813 if (topActive != nullptr && topSensitiveActive != nullptr
Ricardo Correa57a37692020-03-23 17:27:25 -0700814 && !topActive->canCaptureOutput) {
Eric Laurentc21d5692020-02-25 10:24:36 -0800815 topActive = nullptr;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800816 }
817
818 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
819 sp<AudioRecordClient> current = mAudioRecordClients[i];
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700820 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000821 current->attributionSource.uid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700822 if (!current->active) {
823 continue;
824 }
825
Eric Laurent4eb58f12018-12-07 16:41:02 -0800826 audio_source_t source = current->attributes.source;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700827 bool isTopOrLatestActive = topActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +0000828 current->attributionSource.uid == topActive->attributionSource.uid;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700829 bool isTopOrLatestSensitive = topSensitiveActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +0000830 current->attributionSource.uid == topSensitiveActive->attributionSource.uid;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800831 bool isTopOrLatestAssistant = latestActiveAssistant == nullptr ? false :
832 current->attributionSource.uid == latestActiveAssistant->attributionSource.uid;
Eric Laurentc21d5692020-02-25 10:24:36 -0800833
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000834 auto canCaptureIfInCallOrCommunication = [&](const auto &recordClient) REQUIRES(mLock) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700835 uid_t recordUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000836 recordClient->attributionSource.uid));
Ricardo Correa57a37692020-03-23 17:27:25 -0700837 bool canCaptureCall = recordClient->canCaptureOutput;
Eric Laurentb809a752020-06-29 09:53:13 -0700838 bool canCaptureCommunication = recordClient->canCaptureOutput
839 || !isPhoneStateOwnerActive
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700840 || recordUid == mPhoneStateOwnerUid;
Eric Laurentb809a752020-06-29 09:53:13 -0700841 return !(isInCall && !canCaptureCall)
842 && !(isInCommunication && !canCaptureCommunication);
Eric Laurentc21d5692020-02-25 10:24:36 -0800843 };
Eric Laurent1ff16a72019-03-14 18:35:04 -0700844
845 // By default allow capture if:
846 // The assistant is not on TOP
Eric Laurenta171e352019-05-07 13:04:45 -0700847 // AND is on TOP or latest started
Eric Laurent1ff16a72019-03-14 18:35:04 -0700848 // AND there is no active privacy sensitive capture or call
849 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
850 bool allowCapture = !isAssistantOnTop
Eric Laurentc21d5692020-02-25 10:24:36 -0800851 && (isTopOrLatestActive || isTopOrLatestSensitive)
852 && !(isSensitiveActive
Ricardo Correa57a37692020-03-23 17:27:25 -0700853 && !(isTopOrLatestSensitive || current->canCaptureOutput))
Eric Laurentc21d5692020-02-25 10:24:36 -0800854 && canCaptureIfInCallOrCommunication(current);
Eric Laurent2dc962b2019-03-01 08:25:25 -0800855
Eric Laurented726cc2021-07-01 14:26:41 +0200856 if (!current->hasOp()) {
857 // Never allow capture if app op is denied
858 allowCapture = false;
859 } else if (isVirtualSource(source)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700860 // Allow capture for virtual (remote submix, call audio TX or RX...) sources
861 allowCapture = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800862 } else if (!useActiveAssistantList && mUidPolicy->isAssistantUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700863 // For assistant allow capture if:
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800864 // Active assistant list is not being used
865 // AND accessibility service is on TOP or a RTT call is active
Eric Laurent1ff16a72019-03-14 18:35:04 -0700866 // AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800867 // OR there is no active privacy sensitive capture or call
868 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
869 // AND is latest TOP assistant AND
870 // uses VOICE_RECOGNITION OR uses HOTWORD
871 // OR there is no TOP assistant and uses HOTWORD
Eric Laurent6ede98f2019-06-11 14:50:30 -0700872 if (isA11yOnTop || rttCallActive) {
Eric Laurent4eb58f12018-12-07 16:41:02 -0800873 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700874 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800875 }
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800876 } else if (!(isSensitiveActive && !current->canCaptureOutput)
877 && canCaptureIfInCallOrCommunication(current)) {
878 if (isTopOrLatestAssistant
879 && (source == AUDIO_SOURCE_VOICE_RECOGNITION
880 || source == AUDIO_SOURCE_HOTWORD)) {
881 allowCapture = true;
882 } else if (!isAssistantOnTop && (source == AUDIO_SOURCE_HOTWORD)) {
883 allowCapture = true;
884 }
885 }
886 } else if (useActiveAssistantList && mUidPolicy->isActiveAssistantUid(currentUid)) {
887 // For assistant on active list and on top allow capture if:
888 // An accessibility service is on TOP
889 // AND the source is VOICE_RECOGNITION or HOTWORD
890 // OR there is no active privacy sensitive capture or call
891 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
892 // AND uses VOICE_RECOGNITION OR uses HOTWORD
893 if (isA11yOnTop) {
894 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
895 allowCapture = true;
896 }
897 } else if (!(isSensitiveActive && !current->canCaptureOutput)
Eric Laurentc21d5692020-02-25 10:24:36 -0800898 && canCaptureIfInCallOrCommunication(current)) {
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800899 if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) || (source == AUDIO_SOURCE_HOTWORD))
900 {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700901 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800902 }
903 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700904 } else if (mUidPolicy->isA11yUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700905 // For accessibility service allow capture if:
Eric Laurent47670c92019-08-28 16:59:05 -0700906 // The assistant is not on TOP
907 // AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -0700908 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent47670c92019-08-28 16:59:05 -0700909 // OR
910 // Is on TOP AND the source is VOICE_RECOGNITION or HOTWORD
911 if (!isAssistantOnTop
Ricardo Correa57a37692020-03-23 17:27:25 -0700912 && !(isSensitiveActive && !current->canCaptureOutput)
Eric Laurentc21d5692020-02-25 10:24:36 -0800913 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent47670c92019-08-28 16:59:05 -0700914 allowCapture = true;
915 }
Eric Laurent589171c2019-07-25 18:04:29 -0700916 if (isA11yOnTop) {
917 if (source == AUDIO_SOURCE_VOICE_RECOGNITION || source == AUDIO_SOURCE_HOTWORD) {
918 allowCapture = true;
919 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800920 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700921 } else if (source == AUDIO_SOURCE_HOTWORD) {
922 // For HOTWORD source allow capture when not on TOP if:
923 // All active clients are using HOTWORD source
924 // AND no call is active
925 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurentc21d5692020-02-25 10:24:36 -0800926 if (onlyHotwordActive
927 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent4e947da2019-10-17 15:24:06 -0700928 allowCapture = true;
929 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700930 } else if (mUidPolicy->isCurrentImeUid(currentUid)) {
Kohsuke Yatoha623a132020-03-24 20:10:26 -0700931 // For current InputMethodService allow capture if:
932 // A RTT call is active AND the source is VOICE_RECOGNITION
933 if (rttCallActive && source == AUDIO_SOURCE_VOICE_RECOGNITION) {
934 allowCapture = true;
935 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800936 }
Eric Laurent8c7ef892021-06-10 13:32:16 +0200937 setAppState_l(current,
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700938 allowCapture ? apmStatFromAmState(mUidPolicy->getUidState(currentUid)) :
Eric Laurent1ff16a72019-03-14 18:35:04 -0700939 APP_STATE_IDLE);
Eric Laurente8c8b432018-10-17 10:08:02 -0700940 }
941}
942
Michael Groovercfd28302018-12-11 19:16:46 -0800943void AudioPolicyService::silenceAllRecordings_l() {
944 for (size_t i = 0; i < mAudioRecordClients.size(); i++) {
945 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -0700946 if (!isVirtualSource(current->attributes.source)) {
Eric Laurent8c7ef892021-06-10 13:32:16 +0200947 setAppState_l(current, APP_STATE_IDLE);
Eric Laurent1ff16a72019-03-14 18:35:04 -0700948 }
Michael Groovercfd28302018-12-11 19:16:46 -0800949 }
950}
951
Eric Laurente8c8b432018-10-17 10:08:02 -0700952/* static */
953app_state_t AudioPolicyService::apmStatFromAmState(int amState) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700954
955 if (amState == ActivityManager::PROCESS_STATE_UNKNOWN) {
Eric Laurente8c8b432018-10-17 10:08:02 -0700956 return APP_STATE_IDLE;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700957 } else if (amState <= ActivityManager::PROCESS_STATE_TOP) {
958 // include persistent services
959 return APP_STATE_TOP;
Eric Laurente8c8b432018-10-17 10:08:02 -0700960 }
961 return APP_STATE_FOREGROUND;
962}
963
Eric Laurent4eb58f12018-12-07 16:41:02 -0800964/* static */
Eric Laurent2dc962b2019-03-01 08:25:25 -0800965bool AudioPolicyService::isVirtualSource(audio_source_t source)
Eric Laurent4eb58f12018-12-07 16:41:02 -0800966{
967 switch (source) {
968 case AUDIO_SOURCE_VOICE_UPLINK:
969 case AUDIO_SOURCE_VOICE_DOWNLINK:
970 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent2dc962b2019-03-01 08:25:25 -0800971 case AUDIO_SOURCE_REMOTE_SUBMIX:
972 case AUDIO_SOURCE_FM_TUNER:
Eric Laurent68eb2122020-04-30 17:40:57 -0700973 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent4eb58f12018-12-07 16:41:02 -0800974 return true;
975 default:
976 break;
977 }
978 return false;
979}
980
Eric Laurented726cc2021-07-01 14:26:41 +0200981/* static */
982bool AudioPolicyService::isAppOpSource(audio_source_t source)
983{
984 switch (source) {
985 case AUDIO_SOURCE_FM_TUNER:
986 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent637bd202021-09-22 11:17:11 +0200987 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurented726cc2021-07-01 14:26:41 +0200988 return false;
989 default:
990 break;
991 }
992 return true;
993}
994
Eric Laurent8c7ef892021-06-10 13:32:16 +0200995void AudioPolicyService::setAppState_l(sp<AudioRecordClient> client, app_state_t state)
Eric Laurente8c8b432018-10-17 10:08:02 -0700996{
997 AutoCallerClear acc;
998
999 if (mAudioPolicyManager) {
Eric Laurent8c7ef892021-06-10 13:32:16 +02001000 mAudioPolicyManager->setAppState(client->portId, state);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001001 }
1002 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1003 if (af) {
Eric Laurentf32108e2018-10-04 17:22:04 -07001004 bool silenced = state == APP_STATE_IDLE;
Eric Laurent8c7ef892021-06-10 13:32:16 +02001005 if (client->silenced != silenced) {
1006 if (client->active) {
1007 if (silenced) {
1008 finishRecording(client->attributionSource, client->attributes.source);
1009 } else {
1010 std::stringstream msg;
1011 msg << "Audio recording un-silenced on session " << client->session;
1012 if (!startRecording(client->attributionSource, String16(msg.str().c_str()),
1013 client->attributes.source)) {
1014 silenced = true;
1015 }
1016 }
1017 }
1018 af->setRecordSilenced(client->portId, silenced);
1019 client->silenced = silenced;
1020 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001021 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001022}
1023
Glenn Kasten0f11b512014-01-31 16:18:54 -08001024status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001025{
Glenn Kasten44deb052012-02-05 18:09:08 -08001026 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001027 dumpPermissionDenial(fd);
1028 } else {
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001029 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001030 if (!locked) {
1031 String8 result(kDeadlockedString);
1032 write(fd, result.string(), result.size());
1033 }
1034
1035 dumpInternals(fd);
Glenn Kasten9d1f02d2012-02-08 17:47:58 -08001036 if (mAudioCommandThread != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001037 mAudioCommandThread->dump(fd);
1038 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001039
Eric Laurentdce54a12014-03-10 12:19:46 -07001040 if (mAudioPolicyManager) {
1041 mAudioPolicyManager->dump(fd);
1042 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001043
Kevin Rocard8be94972019-02-22 13:26:25 -08001044 mPackageManager.dump(fd);
1045
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001046 dumpReleaseLock(mLock, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001047 }
1048 return NO_ERROR;
1049}
1050
1051status_t AudioPolicyService::dumpPermissionDenial(int fd)
1052{
1053 const size_t SIZE = 256;
1054 char buffer[SIZE];
1055 String8 result;
1056 snprintf(buffer, SIZE, "Permission Denial: "
1057 "can't dump AudioPolicyService from pid=%d, uid=%d\n",
1058 IPCThreadState::self()->getCallingPid(),
1059 IPCThreadState::self()->getCallingUid());
1060 result.append(buffer);
1061 write(fd, result.string(), result.size());
1062 return NO_ERROR;
1063}
1064
1065status_t AudioPolicyService::onTransact(
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001066 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001067 // make sure transactions reserved to AudioFlinger do not come from other processes
1068 switch (code) {
1069 case TRANSACTION_startOutput:
1070 case TRANSACTION_stopOutput:
1071 case TRANSACTION_releaseOutput:
1072 case TRANSACTION_getInputForAttr:
1073 case TRANSACTION_startInput:
1074 case TRANSACTION_stopInput:
1075 case TRANSACTION_releaseInput:
1076 case TRANSACTION_getOutputForEffect:
1077 case TRANSACTION_registerEffect:
1078 case TRANSACTION_unregisterEffect:
1079 case TRANSACTION_setEffectEnabled:
1080 case TRANSACTION_getStrategyForStream:
1081 case TRANSACTION_getOutputForAttr:
1082 case TRANSACTION_moveEffectsToIo:
1083 ALOGW("%s: transaction %d received from PID %d",
1084 __func__, code, IPCThreadState::self()->getCallingPid());
1085 return INVALID_OPERATION;
1086 default:
1087 break;
1088 }
1089
1090 // make sure the following transactions come from system components
1091 switch (code) {
1092 case TRANSACTION_setDeviceConnectionState:
1093 case TRANSACTION_handleDeviceConfigChange:
1094 case TRANSACTION_setPhoneState:
1095//FIXME: Allow setForceUse calls from system apps until a better use case routing API is available
1096// case TRANSACTION_setForceUse:
1097 case TRANSACTION_initStreamVolume:
1098 case TRANSACTION_setStreamVolumeIndex:
1099 case TRANSACTION_setVolumeIndexForAttributes:
1100 case TRANSACTION_getStreamVolumeIndex:
1101 case TRANSACTION_getVolumeIndexForAttributes:
1102 case TRANSACTION_getMinVolumeIndexForAttributes:
1103 case TRANSACTION_getMaxVolumeIndexForAttributes:
1104 case TRANSACTION_isStreamActive:
1105 case TRANSACTION_isStreamActiveRemotely:
1106 case TRANSACTION_isSourceActive:
1107 case TRANSACTION_getDevicesForStream:
1108 case TRANSACTION_registerPolicyMixes:
1109 case TRANSACTION_setMasterMono:
1110 case TRANSACTION_getSurroundFormats:
Kriti Dang6537def2021-03-02 13:46:59 +01001111 case TRANSACTION_getReportedSurroundFormats:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001112 case TRANSACTION_setSurroundFormatEnabled:
Oscar Azucena829d90d2022-01-28 17:17:56 -08001113 case TRANSACTION_setAssistantServicesUids:
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001114 case TRANSACTION_setActiveAssistantServicesUids:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001115 case TRANSACTION_setA11yServicesUids:
1116 case TRANSACTION_setUidDeviceAffinities:
1117 case TRANSACTION_removeUidDeviceAffinities:
1118 case TRANSACTION_setUserIdDeviceAffinities:
1119 case TRANSACTION_removeUserIdDeviceAffinities:
Pattydd807582021-11-04 21:01:03 +08001120 case TRANSACTION_getHwOffloadFormatsSupportedForBluetoothMedia:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001121 case TRANSACTION_listAudioVolumeGroups:
1122 case TRANSACTION_getVolumeGroupFromAudioAttributes:
1123 case TRANSACTION_acquireSoundTriggerSession:
1124 case TRANSACTION_releaseSoundTriggerSession:
1125 case TRANSACTION_setRttEnabled:
1126 case TRANSACTION_isCallScreenModeSupported:
1127 case TRANSACTION_setDevicesRoleForStrategy:
1128 case TRANSACTION_setSupportedSystemUsages:
1129 case TRANSACTION_removeDevicesRoleForStrategy:
1130 case TRANSACTION_getDevicesForRoleAndStrategy:
1131 case TRANSACTION_getDevicesForAttributes:
1132 case TRANSACTION_setAllowedCapturePolicy:
1133 case TRANSACTION_onNewAudioModulesAvailable:
1134 case TRANSACTION_setCurrentImeUid:
1135 case TRANSACTION_registerSoundTriggerCaptureStateListener:
1136 case TRANSACTION_setDevicesRoleForCapturePreset:
1137 case TRANSACTION_addDevicesRoleForCapturePreset:
1138 case TRANSACTION_removeDevicesRoleForCapturePreset:
1139 case TRANSACTION_clearDevicesRoleForCapturePreset:
Eric Laurent81dd0f52021-07-05 11:54:40 +02001140 case TRANSACTION_getDevicesForRoleAndCapturePreset:
1141 case TRANSACTION_getSpatializer: {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001142 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
1143 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
1144 __func__, code, IPCThreadState::self()->getCallingPid(),
1145 IPCThreadState::self()->getCallingUid());
1146 return INVALID_OPERATION;
1147 }
1148 } break;
1149 default:
1150 break;
1151 }
1152
1153 std::string tag("IAudioPolicyService command " + std::to_string(code));
1154 TimeCheck check(tag.c_str());
1155
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001156 switch (code) {
1157 case SHELL_COMMAND_TRANSACTION: {
1158 int in = data.readFileDescriptor();
1159 int out = data.readFileDescriptor();
1160 int err = data.readFileDescriptor();
1161 int argc = data.readInt32();
1162 Vector<String16> args;
1163 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
1164 args.add(data.readString16());
1165 }
1166 sp<IBinder> unusedCallback;
1167 sp<IResultReceiver> resultReceiver;
1168 status_t status;
1169 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
1170 return status;
1171 }
1172 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
1173 return status;
1174 }
1175 status = shellCommand(in, out, err, args);
1176 if (resultReceiver != nullptr) {
1177 resultReceiver->send(status);
1178 }
1179 return NO_ERROR;
1180 }
1181 }
1182
Mathias Agopian65ab4712010-07-14 17:59:35 -07001183 return BnAudioPolicyService::onTransact(code, data, reply, flags);
1184}
1185
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001186// ------------------- Shell command implementation -------------------
1187
1188// NOTE: This is a remote API - make sure all args are validated
1189status_t AudioPolicyService::shellCommand(int in, int out, int err, Vector<String16>& args) {
1190 if (!checkCallingPermission(sManageAudioPolicyPermission, nullptr, nullptr)) {
1191 return PERMISSION_DENIED;
1192 }
1193 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
1194 return BAD_VALUE;
1195 }
jovanakbe066e12019-09-02 11:54:39 -07001196 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001197 return handleSetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001198 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001199 return handleResetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001200 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001201 return handleGetUidState(args, out, err);
Eric Laurent269acb42021-04-23 16:53:22 +02001202 } else if (args.size() >= 1 && args[0] == String16("purge_permission-cache")) {
1203 purgePermissionCache();
1204 return NO_ERROR;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001205 } else if (args.size() == 1 && args[0] == String16("help")) {
1206 printHelp(out);
1207 return NO_ERROR;
1208 }
1209 printHelp(err);
1210 return BAD_VALUE;
1211}
1212
jovanakbe066e12019-09-02 11:54:39 -07001213static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1214 if (userId < 0) {
1215 ALOGE("Invalid user: %d", userId);
1216 dprintf(err, "Invalid user: %d\n", userId);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001217 return BAD_VALUE;
1218 }
jovanakbe066e12019-09-02 11:54:39 -07001219
1220 PermissionController pc;
1221 uid = pc.getPackageUid(packageName, 0);
1222 if (uid <= 0) {
1223 ALOGE("Unknown package: '%s'", String8(packageName).string());
1224 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1225 return BAD_VALUE;
1226 }
1227
1228 uid = multiuser_get_uid(userId, uid);
1229 return NO_ERROR;
1230}
1231
1232status_t AudioPolicyService::handleSetUidState(Vector<String16>& args, int err) {
1233 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
1234 if (!(args.size() == 3 || args.size() == 5)) {
1235 printHelp(err);
1236 return BAD_VALUE;
1237 }
1238
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001239 bool active = false;
1240 if (args[2] == String16("active")) {
1241 active = true;
1242 } else if ((args[2] != String16("idle"))) {
1243 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
1244 return BAD_VALUE;
1245 }
jovanakbe066e12019-09-02 11:54:39 -07001246
1247 int userId = 0;
1248 if (args.size() >= 5 && args[3] == String16("--user")) {
1249 userId = atoi(String8(args[4]));
1250 }
1251
1252 uid_t uid;
1253 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1254 return BAD_VALUE;
1255 }
1256
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001257 sp<UidPolicy> uidPolicy;
1258 {
1259 Mutex::Autolock _l(mLock);
1260 uidPolicy = mUidPolicy;
1261 }
1262 if (uidPolicy) {
1263 uidPolicy->addOverrideUid(uid, active);
1264 return NO_ERROR;
1265 }
1266 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001267}
1268
1269status_t AudioPolicyService::handleResetUidState(Vector<String16>& args, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001270 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1271 if (!(args.size() == 2 || args.size() == 4)) {
1272 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001273 return BAD_VALUE;
1274 }
jovanakbe066e12019-09-02 11:54:39 -07001275
1276 int userId = 0;
1277 if (args.size() >= 4 && args[2] == String16("--user")) {
1278 userId = atoi(String8(args[3]));
1279 }
1280
1281 uid_t uid;
1282 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1283 return BAD_VALUE;
1284 }
1285
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001286 sp<UidPolicy> uidPolicy;
1287 {
1288 Mutex::Autolock _l(mLock);
1289 uidPolicy = mUidPolicy;
1290 }
1291 if (uidPolicy) {
1292 uidPolicy->removeOverrideUid(uid);
1293 return NO_ERROR;
1294 }
1295 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001296}
1297
1298status_t AudioPolicyService::handleGetUidState(Vector<String16>& args, int out, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001299 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1300 if (!(args.size() == 2 || args.size() == 4)) {
1301 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001302 return BAD_VALUE;
1303 }
jovanakbe066e12019-09-02 11:54:39 -07001304
1305 int userId = 0;
1306 if (args.size() >= 4 && args[2] == String16("--user")) {
1307 userId = atoi(String8(args[3]));
1308 }
1309
1310 uid_t uid;
1311 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1312 return BAD_VALUE;
1313 }
1314
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001315 sp<UidPolicy> uidPolicy;
1316 {
1317 Mutex::Autolock _l(mLock);
1318 uidPolicy = mUidPolicy;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001319 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001320 if (uidPolicy) {
1321 return dprintf(out, uidPolicy->isUidActive(uid) ? "active\n" : "idle\n");
1322 }
1323 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001324}
1325
1326status_t AudioPolicyService::printHelp(int out) {
1327 return dprintf(out, "Audio policy service commands:\n"
jovanakbe066e12019-09-02 11:54:39 -07001328 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
1329 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
1330 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001331 " help print this message\n");
1332}
1333
1334// ----------- AudioPolicyService::UidPolicy implementation ----------
1335
1336void AudioPolicyService::UidPolicy::registerSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001337 status_t res = mAm.linkToDeath(this);
1338 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001339 | ActivityManager::UID_OBSERVER_IDLE
Eric Laurente8c8b432018-10-17 10:08:02 -07001340 | ActivityManager::UID_OBSERVER_ACTIVE
1341 | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001342 ActivityManager::PROCESS_STATE_UNKNOWN,
1343 String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001344 if (!res) {
1345 Mutex::Autolock _l(mLock);
1346 mObserverRegistered = true;
1347 } else {
1348 ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001349
Steven Moreland2f348142019-07-02 15:59:07 -07001350 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001351 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001352}
1353
1354void AudioPolicyService::UidPolicy::unregisterSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001355 mAm.unlinkToDeath(this);
1356 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001357 Mutex::Autolock _l(mLock);
1358 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001359}
1360
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001361void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
1362 Mutex::Autolock _l(mLock);
1363 mCachedUids.clear();
1364 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001365}
1366
Eric Laurente8c8b432018-10-17 10:08:02 -07001367void AudioPolicyService::UidPolicy::checkRegistered() {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001368 bool needToReregister = false;
1369 {
1370 Mutex::Autolock _l(mLock);
1371 needToReregister = !mObserverRegistered;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001372 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001373 if (needToReregister) {
1374 // Looks like ActivityManager has died previously, attempt to re-register.
1375 registerSelf();
1376 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001377}
1378
1379bool AudioPolicyService::UidPolicy::isUidActive(uid_t uid) {
1380 if (isServiceUid(uid)) return true;
1381 checkRegistered();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001382 {
1383 Mutex::Autolock _l(mLock);
1384 auto overrideIter = mOverrideUids.find(uid);
1385 if (overrideIter != mOverrideUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001386 return overrideIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001387 }
1388 // In an absense of the ActivityManager, assume everything to be active.
1389 if (!mObserverRegistered) return true;
1390 auto cacheIter = mCachedUids.find(uid);
Mikhail Naganoveba668a2018-04-05 08:13:15 -07001391 if (cacheIter != mCachedUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001392 return cacheIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001393 }
1394 }
1395 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001396 bool active = am.isUidActive(uid, String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001397 {
1398 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001399 mCachedUids.insert(std::pair<uid_t,
1400 std::pair<bool, int>>(uid, std::pair<bool, int>(active,
1401 ActivityManager::PROCESS_STATE_UNKNOWN)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001402 }
1403 return active;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001404}
1405
Eric Laurente8c8b432018-10-17 10:08:02 -07001406int AudioPolicyService::UidPolicy::getUidState(uid_t uid) {
1407 if (isServiceUid(uid)) {
1408 return ActivityManager::PROCESS_STATE_TOP;
1409 }
1410 checkRegistered();
1411 {
1412 Mutex::Autolock _l(mLock);
1413 auto overrideIter = mOverrideUids.find(uid);
1414 if (overrideIter != mOverrideUids.end()) {
1415 if (overrideIter->second.first) {
1416 if (overrideIter->second.second != ActivityManager::PROCESS_STATE_UNKNOWN) {
1417 return overrideIter->second.second;
1418 } else {
1419 auto cacheIter = mCachedUids.find(uid);
1420 if (cacheIter != mCachedUids.end()) {
1421 return cacheIter->second.second;
1422 }
1423 }
1424 }
1425 return ActivityManager::PROCESS_STATE_UNKNOWN;
1426 }
1427 // In an absense of the ActivityManager, assume everything to be active.
1428 if (!mObserverRegistered) {
1429 return ActivityManager::PROCESS_STATE_TOP;
1430 }
1431 auto cacheIter = mCachedUids.find(uid);
1432 if (cacheIter != mCachedUids.end()) {
1433 if (cacheIter->second.first) {
1434 return cacheIter->second.second;
1435 } else {
1436 return ActivityManager::PROCESS_STATE_UNKNOWN;
1437 }
1438 }
1439 }
1440 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001441 bool active = am.isUidActive(uid, String16("audioserver"));
Eric Laurente8c8b432018-10-17 10:08:02 -07001442 int state = ActivityManager::PROCESS_STATE_UNKNOWN;
1443 if (active) {
1444 state = am.getUidProcessState(uid, String16("audioserver"));
1445 }
1446 {
1447 Mutex::Autolock _l(mLock);
1448 mCachedUids.insert(std::pair<uid_t,
1449 std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
1450 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001451
Eric Laurente8c8b432018-10-17 10:08:02 -07001452 return state;
1453}
1454
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001455void AudioPolicyService::UidPolicy::onUidActive(uid_t uid) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001456 updateUid(&mCachedUids, uid, true, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001457}
1458
1459void AudioPolicyService::UidPolicy::onUidGone(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001460 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, false);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001461}
1462
1463void AudioPolicyService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001464 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001465}
1466
Eric Laurente8c8b432018-10-17 10:08:02 -07001467void AudioPolicyService::UidPolicy::onUidStateChanged(uid_t uid,
1468 int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07001469 int64_t procStateSeq __unused,
1470 int32_t capability __unused) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001471 if (procState != ActivityManager::PROCESS_STATE_UNKNOWN) {
1472 updateUid(&mCachedUids, uid, true, procState, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001473 }
1474}
1475
1476void AudioPolicyService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001477 updateUid(&mOverrideUids, uid, active, ActivityManager::PROCESS_STATE_UNKNOWN, insert);
1478}
1479
1480void AudioPolicyService::UidPolicy::notifyService() {
1481 sp<AudioPolicyService> service = mService.promote();
1482 if (service != nullptr) {
1483 service->updateUidStates();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001484 }
1485}
1486
Eric Laurente8c8b432018-10-17 10:08:02 -07001487void AudioPolicyService::UidPolicy::updateUid(std::unordered_map<uid_t,
1488 std::pair<bool, int>> *uids,
1489 uid_t uid,
1490 bool active,
1491 int state,
1492 bool insert) {
1493 if (isServiceUid(uid)) {
1494 return;
1495 }
1496 bool wasActive = isUidActive(uid);
1497 int previousState = getUidState(uid);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001498 {
1499 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001500 updateUidLocked(uids, uid, active, state, insert);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001501 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001502 if (wasActive != isUidActive(uid) || state != previousState) {
1503 notifyService();
1504 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001505}
1506
Eric Laurente8c8b432018-10-17 10:08:02 -07001507void AudioPolicyService::UidPolicy::updateUidLocked(std::unordered_map<uid_t,
1508 std::pair<bool, int>> *uids,
1509 uid_t uid,
1510 bool active,
1511 int state,
1512 bool insert) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001513 auto it = uids->find(uid);
1514 if (it != uids->end()) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001515 if (insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001516 if (state == ActivityManager::PROCESS_STATE_UNKNOWN) {
1517 it->second.first = active;
1518 }
1519 if (it->second.first) {
1520 it->second.second = state;
1521 } else {
1522 it->second.second = ActivityManager::PROCESS_STATE_UNKNOWN;
1523 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001524 } else {
1525 uids->erase(it);
1526 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001527 } else if (insert && (state == ActivityManager::PROCESS_STATE_UNKNOWN)) {
1528 uids->insert(std::pair<uid_t, std::pair<bool, int>>(uid,
1529 std::pair<bool, int>(active, state)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001530 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001531}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001532
Eric Laurent4eb58f12018-12-07 16:41:02 -08001533bool AudioPolicyService::UidPolicy::isA11yOnTop() {
1534 for (const auto &uid : mCachedUids) {
Eric Laurent47670c92019-08-28 16:59:05 -07001535 if (!isA11yUid(uid.first)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001536 continue;
1537 }
Amith Yamasanibcbb3002019-01-23 13:53:33 -08001538 if (uid.second.second >= ActivityManager::PROCESS_STATE_TOP
1539 && uid.second.second <= ActivityManager::PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001540 return true;
1541 }
1542 }
1543 return false;
1544}
1545
Eric Laurentb78763e2018-10-17 10:08:02 -07001546bool AudioPolicyService::UidPolicy::isA11yUid(uid_t uid)
1547{
1548 std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid);
1549 return it != mA11yUids.end();
1550}
1551
Oscar Azucena829d90d2022-01-28 17:17:56 -08001552void AudioPolicyService::UidPolicy::setAssistantUids(const std::vector<uid_t>& uids) {
1553 mAssistantUids.clear();
1554 mAssistantUids = uids;
1555}
1556
1557bool AudioPolicyService::UidPolicy::isAssistantUid(uid_t uid)
1558{
1559 std::vector<uid_t>::iterator it = find(mAssistantUids.begin(), mAssistantUids.end(), uid);
1560 return it != mAssistantUids.end();
1561}
1562
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001563void AudioPolicyService::UidPolicy::setActiveAssistantUids(const std::vector<uid_t>& activeUids) {
1564 mActiveAssistantUids = activeUids;
1565}
1566
1567bool AudioPolicyService::UidPolicy::isActiveAssistantUid(uid_t uid)
1568{
1569 std::vector<uid_t>::iterator it = find(mActiveAssistantUids.begin(),
1570 mActiveAssistantUids.end(), uid);
1571 return it != mActiveAssistantUids.end();
1572}
1573
Oscar Azucena829d90d2022-01-28 17:17:56 -08001574void AudioPolicyService::UidPolicy::dumpInternals(int fd) {
1575 const size_t SIZE = 256;
1576 char buffer[SIZE];
1577 String8 result;
1578 auto appendUidsToResult = [&](const char* title, const std::vector<uid_t> &uids) {
1579 snprintf(buffer, SIZE, "\t%s: \n", title);
1580 result.append(buffer);
1581 int counter = 0;
1582 if (uids.empty()) {
1583 snprintf(buffer, SIZE, "\t\tNo UIDs present.\n");
1584 result.append(buffer);
1585 return;
1586 }
1587 for (const auto &uid : uids) {
1588 snprintf(buffer, SIZE, "\t\tUID[%d]=%d\n", counter++, uid);
1589 result.append(buffer);
1590 }
1591 };
1592
1593 snprintf(buffer, SIZE, "UID Policy:\n");
1594 result.append(buffer);
1595 snprintf(buffer, SIZE, "\tmObserverRegistered=%s\n",(mObserverRegistered ? "True":"False"));
1596 result.append(buffer);
1597
1598 appendUidsToResult("Assistants UIDs", mAssistantUids);
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001599 appendUidsToResult("Active Assistants UIDs", mActiveAssistantUids);
Oscar Azucena829d90d2022-01-28 17:17:56 -08001600
1601 appendUidsToResult("Accessibility UIDs", mA11yUids);
1602
1603 snprintf(buffer, SIZE, "\tInput Method Service UID=%d\n", mCurrentImeUid);
1604 result.append(buffer);
1605
1606 snprintf(buffer, SIZE, "\tIs RTT Enabled: %s\n", (mRttEnabled ? "True":"False"));
1607 result.append(buffer);
1608
1609 write(fd, result.string(), result.size());
1610}
1611
Michael Groovercfd28302018-12-11 19:16:46 -08001612// ----------- AudioPolicyService::SensorPrivacyService implementation ----------
1613void AudioPolicyService::SensorPrivacyPolicy::registerSelf() {
1614 SensorPrivacyManager spm;
1615 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1616 spm.addSensorPrivacyListener(this);
1617}
1618
1619void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
1620 SensorPrivacyManager spm;
1621 spm.removeSensorPrivacyListener(this);
1622}
1623
1624bool AudioPolicyService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1625 return mSensorPrivacyEnabled;
1626}
1627
Evan Seversond8dc6832022-01-27 10:47:03 -08001628binder::Status AudioPolicyService::SensorPrivacyPolicy::onSensorPrivacyChanged(
1629 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Groovercfd28302018-12-11 19:16:46 -08001630 mSensorPrivacyEnabled = enabled;
1631 sp<AudioPolicyService> service = mService.promote();
1632 if (service != nullptr) {
1633 service->updateUidStates();
1634 }
1635 return binder::Status::ok();
1636}
1637
Eric Laurented726cc2021-07-01 14:26:41 +02001638// ----------- AudioPolicyService::OpRecordAudioMonitor implementation ----------
1639
1640// static
1641sp<AudioPolicyService::OpRecordAudioMonitor>
1642AudioPolicyService::OpRecordAudioMonitor::createIfNeeded(
1643 const AttributionSourceState& attributionSource, const audio_attributes_t& attr,
1644 wp<AudioCommandThread> commandThread)
1645{
Eric Laurent987ce102021-07-05 12:11:51 +02001646 if (isAudioServerOrRootUid(attributionSource.uid)) {
1647 ALOGV("not silencing record for audio or root source %s",
Eric Laurented726cc2021-07-01 14:26:41 +02001648 attributionSource.toString().c_str());
1649 return nullptr;
1650 }
1651
1652 if (!AudioPolicyService::isAppOpSource(attr.source)) {
1653 ALOGD("not monitoring app op for uid %d and source %d",
1654 attributionSource.uid, attr.source);
1655 return nullptr;
1656 }
1657
1658 if (!attributionSource.packageName.has_value()
1659 || attributionSource.packageName.value().size() == 0) {
1660 return nullptr;
1661 }
1662 return new OpRecordAudioMonitor(attributionSource, getOpForSource(attr.source), commandThread);
1663}
1664
1665AudioPolicyService::OpRecordAudioMonitor::OpRecordAudioMonitor(
1666 const AttributionSourceState& attributionSource, int32_t appOp,
1667 wp<AudioCommandThread> commandThread) :
1668 mHasOp(true), mAttributionSource(attributionSource), mAppOp(appOp),
1669 mCommandThread(commandThread)
1670{
1671}
1672
1673AudioPolicyService::OpRecordAudioMonitor::~OpRecordAudioMonitor()
1674{
1675 if (mOpCallback != 0) {
1676 mAppOpsManager.stopWatchingMode(mOpCallback);
1677 }
1678 mOpCallback.clear();
1679}
1680
1681void AudioPolicyService::OpRecordAudioMonitor::onFirstRef()
1682{
1683 checkOp();
1684 mOpCallback = new RecordAudioOpCallback(this);
1685 ALOGV("start watching op %d for %s", mAppOp, mAttributionSource.toString().c_str());
1686 // TODO: We need to always watch AppOpsManager::OP_RECORD_AUDIO too
1687 // since it controls the mic permission for legacy apps.
1688 mAppOpsManager.startWatchingMode(mAppOp, VALUE_OR_FATAL(aidl2legacy_string_view_String16(
1689 mAttributionSource.packageName.value_or(""))),
1690 mOpCallback);
1691}
1692
1693bool AudioPolicyService::OpRecordAudioMonitor::hasOp() const {
1694 return mHasOp.load();
1695}
1696
1697// Called by RecordAudioOpCallback when the app op corresponding to this OpRecordAudioMonitor
1698// is updated in AppOp callback and in onFirstRef()
1699// Note this method is never called (and never to be) for audio server / root track
1700// due to the UID in createIfNeeded(). As a result for those record track, it's:
1701// - not called from constructor,
1702// - not called from RecordAudioOpCallback because the callback is not installed in this case
1703void AudioPolicyService::OpRecordAudioMonitor::checkOp(bool updateUidStates)
1704{
1705 // TODO: We need to always check AppOpsManager::OP_RECORD_AUDIO too
1706 // since it controls the mic permission for legacy apps.
1707 const int32_t mode = mAppOpsManager.checkOp(mAppOp,
1708 mAttributionSource.uid, VALUE_OR_FATAL(aidl2legacy_string_view_String16(
1709 mAttributionSource.packageName.value_or(""))));
1710 const bool hasIt = (mode == AppOpsManager::MODE_ALLOWED);
1711 // verbose logging only log when appOp changed
1712 ALOGI_IF(hasIt != mHasOp.load(),
1713 "App op %d missing, %ssilencing record %s",
1714 mAppOp, hasIt ? "un" : "", mAttributionSource.toString().c_str());
1715 mHasOp.store(hasIt);
1716
1717 if (updateUidStates) {
1718 sp<AudioCommandThread> commandThread = mCommandThread.promote();
1719 if (commandThread != nullptr) {
1720 commandThread->updateUidStatesCommand();
1721 }
1722 }
1723}
1724
1725AudioPolicyService::OpRecordAudioMonitor::RecordAudioOpCallback::RecordAudioOpCallback(
1726 const wp<OpRecordAudioMonitor>& monitor) : mMonitor(monitor)
1727{ }
1728
1729void AudioPolicyService::OpRecordAudioMonitor::RecordAudioOpCallback::opChanged(int32_t op,
1730 const String16& packageName __unused) {
1731 sp<OpRecordAudioMonitor> monitor = mMonitor.promote();
1732 if (monitor != NULL) {
1733 if (op != monitor->getOp()) {
1734 return;
1735 }
1736 monitor->checkOp(true);
1737 }
1738}
1739
1740
Mathias Agopian65ab4712010-07-14 17:59:35 -07001741// ----------- AudioPolicyService::AudioCommandThread implementation ----------
1742
Eric Laurentbfb1b832013-01-07 09:53:42 -08001743AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
1744 const wp<AudioPolicyService>& service)
1745 : Thread(false), mName(name), mService(service)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001746{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001747}
1748
1749
1750AudioPolicyService::AudioCommandThread::~AudioCommandThread()
1751{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001752 if (!mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001753 release_wake_lock(mName.string());
1754 }
1755 mAudioCommands.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001756}
1757
1758void AudioPolicyService::AudioCommandThread::onFirstRef()
1759{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001760 run(mName.string(), ANDROID_PRIORITY_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001761}
1762
1763bool AudioPolicyService::AudioCommandThread::threadLoop()
1764{
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001765 nsecs_t waitTime = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001766
1767 mLock.lock();
1768 while (!exitPending())
1769 {
Eric Laurent59a89232014-06-08 14:14:17 -07001770 sp<AudioPolicyService> svc;
1771 while (!mAudioCommands.isEmpty() && !exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001772 nsecs_t curTime = systemTime();
1773 // commands are sorted by increasing time stamp: execute them from index 0 and up
1774 if (mAudioCommands[0]->mTime <= curTime) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001775 sp<AudioCommand> command = mAudioCommands[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001776 mAudioCommands.removeAt(0);
Eric Laurent0ede8922014-05-09 18:04:42 -07001777 mLastCommand = command;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001778
1779 switch (command->mCommand) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001780 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001781 VolumeData *data = (VolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001782 ALOGV("AudioCommandThread() processing set volume stream %d, \
Eric Laurentde070132010-07-13 04:45:46 -07001783 volume %f, output %d", data->mStream, data->mVolume, data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001784 mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07001785 command->mStatus = AudioSystem::setStreamVolume(data->mStream,
1786 data->mVolume,
1787 data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001788 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001789 }break;
1790 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001791 ParametersData *data = (ParametersData *)command->mParam.get();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001792 ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
1793 data->mKeyValuePairs.string(), data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001794 mLock.unlock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001795 command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
Andy Hungfe726a62018-09-27 15:17:25 -07001796 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001797 }break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001798 case SET_VOICE_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001799 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001800 ALOGV("AudioCommandThread() processing set voice volume volume %f",
Eric Laurentde070132010-07-13 04:45:46 -07001801 data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001802 mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001803 command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001804 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001805 }break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001806 case STOP_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001807 StopOutputData *data = (StopOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001808 ALOGV("AudioCommandThread() processing stop output portId %d",
1809 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001810 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001811 if (svc == 0) {
1812 break;
1813 }
1814 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001815 svc->doStopOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001816 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001817 }break;
1818 case RELEASE_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001819 ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001820 ALOGV("AudioCommandThread() processing release output portId %d",
1821 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001822 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001823 if (svc == 0) {
1824 break;
1825 }
1826 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001827 svc->doReleaseOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001828 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001829 }break;
Eric Laurent951f4552014-05-20 10:48:17 -07001830 case CREATE_AUDIO_PATCH: {
1831 CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
1832 ALOGV("AudioCommandThread() processing create audio patch");
1833 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1834 if (af == 0) {
1835 command->mStatus = PERMISSION_DENIED;
1836 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001837 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001838 command->mStatus = af->createAudioPatch(&data->mPatch, &data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001839 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001840 }
1841 } break;
1842 case RELEASE_AUDIO_PATCH: {
1843 ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
1844 ALOGV("AudioCommandThread() processing release audio patch");
1845 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1846 if (af == 0) {
1847 command->mStatus = PERMISSION_DENIED;
1848 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001849 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001850 command->mStatus = af->releaseAudioPatch(data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001851 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001852 }
1853 } break;
Eric Laurentb52c1522014-05-20 11:27:36 -07001854 case UPDATE_AUDIOPORT_LIST: {
1855 ALOGV("AudioCommandThread() processing update audio port list");
Eric Laurent59a89232014-06-08 14:14:17 -07001856 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001857 if (svc == 0) {
1858 break;
1859 }
1860 mLock.unlock();
1861 svc->doOnAudioPortListUpdate();
1862 mLock.lock();
1863 }break;
1864 case UPDATE_AUDIOPATCH_LIST: {
1865 ALOGV("AudioCommandThread() processing update audio patch list");
Eric Laurent59a89232014-06-08 14:14:17 -07001866 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001867 if (svc == 0) {
1868 break;
1869 }
1870 mLock.unlock();
1871 svc->doOnAudioPatchListUpdate();
1872 mLock.lock();
1873 }break;
François Gaffiecfe17322018-11-07 13:41:29 +01001874 case CHANGED_AUDIOVOLUMEGROUP: {
1875 AudioVolumeGroupData *data =
1876 static_cast<AudioVolumeGroupData *>(command->mParam.get());
1877 ALOGV("AudioCommandThread() processing update audio volume group");
1878 svc = mService.promote();
1879 if (svc == 0) {
1880 break;
1881 }
1882 mLock.unlock();
1883 svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
1884 mLock.lock();
1885 }break;
Eric Laurente1715a42014-05-20 11:30:42 -07001886 case SET_AUDIOPORT_CONFIG: {
1887 SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
1888 ALOGV("AudioCommandThread() processing set port config");
1889 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1890 if (af == 0) {
1891 command->mStatus = PERMISSION_DENIED;
1892 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001893 mLock.unlock();
Eric Laurente1715a42014-05-20 11:30:42 -07001894 command->mStatus = af->setAudioPortConfig(&data->mConfig);
Andy Hungfe726a62018-09-27 15:17:25 -07001895 mLock.lock();
Eric Laurente1715a42014-05-20 11:30:42 -07001896 }
1897 } break;
Jean-Michel Trivide801052015-04-14 19:10:14 -07001898 case DYN_POLICY_MIX_STATE_UPDATE: {
1899 DynPolicyMixStateUpdateData *data =
1900 (DynPolicyMixStateUpdateData *)command->mParam.get();
Jean-Michel Trivide801052015-04-14 19:10:14 -07001901 ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
1902 data->mRegId.string(), data->mState);
1903 svc = mService.promote();
1904 if (svc == 0) {
1905 break;
1906 }
1907 mLock.unlock();
1908 svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
1909 mLock.lock();
1910 } break;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001911 case RECORDING_CONFIGURATION_UPDATE: {
1912 RecordingConfigurationUpdateData *data =
1913 (RecordingConfigurationUpdateData *)command->mParam.get();
1914 ALOGV("AudioCommandThread() processing recording configuration update");
1915 svc = mService.promote();
1916 if (svc == 0) {
1917 break;
1918 }
1919 mLock.unlock();
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001920 svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -08001921 &data->mClientConfig, data->mClientEffects,
1922 &data->mDeviceConfig, data->mEffects,
1923 data->mPatchHandle, data->mSource);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001924 mLock.lock();
1925 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001926 case SET_EFFECT_SUSPENDED: {
1927 SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
1928 ALOGV("AudioCommandThread() processing set effect suspended");
1929 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1930 if (af != 0) {
1931 mLock.unlock();
1932 af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
1933 mLock.lock();
1934 }
1935 } break;
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001936 case AUDIO_MODULES_UPDATE: {
1937 ALOGV("AudioCommandThread() processing audio modules update");
1938 svc = mService.promote();
1939 if (svc == 0) {
1940 break;
1941 }
1942 mLock.unlock();
1943 svc->doOnNewAudioModulesAvailable();
1944 mLock.lock();
1945 } break;
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07001946 case ROUTING_UPDATED: {
1947 ALOGV("AudioCommandThread() processing routing update");
1948 svc = mService.promote();
1949 if (svc == 0) {
1950 break;
1951 }
1952 mLock.unlock();
1953 svc->doOnRoutingUpdated();
1954 mLock.lock();
1955 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001956
Eric Laurented726cc2021-07-01 14:26:41 +02001957 case UPDATE_UID_STATES: {
1958 ALOGV("AudioCommandThread() processing updateUID states");
1959 svc = mService.promote();
1960 if (svc == 0) {
1961 break;
1962 }
1963 mLock.unlock();
1964 svc->updateUidStates();
1965 mLock.lock();
1966 } break;
1967
Eric Laurent15903592022-02-24 20:44:36 +01001968 case CHECK_SPATIALIZER_OUTPUT: {
1969 ALOGV("AudioCommandThread() processing check spatializer");
Eric Laurent81dd0f52021-07-05 11:54:40 +02001970 svc = mService.promote();
1971 if (svc == 0) {
1972 break;
1973 }
1974 mLock.unlock();
1975 svc->doOnCheckSpatializer();
1976 mLock.lock();
1977 } break;
1978
Eric Laurent15903592022-02-24 20:44:36 +01001979 case UPDATE_ACTIVE_SPATIALIZER_TRACKS: {
1980 ALOGV("AudioCommandThread() processing update spatializer tracks");
1981 svc = mService.promote();
1982 if (svc == 0) {
1983 break;
1984 }
1985 mLock.unlock();
1986 svc->doOnUpdateActiveSpatializerTracks();
1987 mLock.lock();
1988 } break;
1989
Mathias Agopian65ab4712010-07-14 17:59:35 -07001990 default:
Steve Block5ff1dd52012-01-05 23:22:43 +00001991 ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001992 }
Eric Laurent0ede8922014-05-09 18:04:42 -07001993 {
1994 Mutex::Autolock _l(command->mLock);
1995 if (command->mWaitStatus) {
1996 command->mWaitStatus = false;
1997 command->mCond.signal();
1998 }
1999 }
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002000 waitTime = -1;
Zach Janga754b4f2015-10-27 01:29:34 +00002001 // release mLock before releasing strong reference on the service as
2002 // AudioPolicyService destructor calls AudioCommandThread::exit() which
2003 // acquires mLock.
2004 mLock.unlock();
2005 svc.clear();
2006 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002007 } else {
2008 waitTime = mAudioCommands[0]->mTime - curTime;
2009 break;
2010 }
2011 }
Zach Janga754b4f2015-10-27 01:29:34 +00002012
2013 // release delayed commands wake lock if the queue is empty
2014 if (mAudioCommands.isEmpty()) {
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002015 release_wake_lock(mName.string());
Zach Janga754b4f2015-10-27 01:29:34 +00002016 }
2017
2018 // At this stage we have either an empty command queue or the first command in the queue
2019 // has a finite delay. So unless we are exiting it is safe to wait.
2020 if (!exitPending()) {
Eric Laurent59a89232014-06-08 14:14:17 -07002021 ALOGV("AudioCommandThread() going to sleep");
Eric Laurentd7eda8d2016-02-02 17:18:39 -08002022 if (waitTime == -1) {
2023 mWaitWorkCV.wait(mLock);
2024 } else {
2025 mWaitWorkCV.waitRelative(mLock, waitTime);
2026 }
Eric Laurent59a89232014-06-08 14:14:17 -07002027 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002028 }
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002029 // release delayed commands wake lock before quitting
2030 if (!mAudioCommands.isEmpty()) {
2031 release_wake_lock(mName.string());
2032 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002033 mLock.unlock();
2034 return false;
2035}
2036
2037status_t AudioPolicyService::AudioCommandThread::dump(int fd)
2038{
2039 const size_t SIZE = 256;
2040 char buffer[SIZE];
2041 String8 result;
2042
2043 snprintf(buffer, SIZE, "AudioCommandThread %p Dump\n", this);
2044 result.append(buffer);
2045 write(fd, result.string(), result.size());
2046
Mikhail Naganov12b716c2020-04-30 22:37:43 +00002047 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002048 if (!locked) {
2049 String8 result2(kCmdDeadlockedString);
2050 write(fd, result2.string(), result2.size());
2051 }
2052
2053 snprintf(buffer, SIZE, "- Commands:\n");
2054 result = String8(buffer);
2055 result.append(" Command Time Wait pParam\n");
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002056 for (size_t i = 0; i < mAudioCommands.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002057 mAudioCommands[i]->dump(buffer, SIZE);
2058 result.append(buffer);
2059 }
2060 result.append(" Last Command\n");
Eric Laurent0ede8922014-05-09 18:04:42 -07002061 if (mLastCommand != 0) {
2062 mLastCommand->dump(buffer, SIZE);
2063 result.append(buffer);
2064 } else {
2065 result.append(" none\n");
2066 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002067
2068 write(fd, result.string(), result.size());
2069
Mikhail Naganov12b716c2020-04-30 22:37:43 +00002070 dumpReleaseLock(mLock, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002071
2072 return NO_ERROR;
2073}
2074
Glenn Kastenfff6d712012-01-12 16:38:12 -08002075status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
Eric Laurentde070132010-07-13 04:45:46 -07002076 float volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002077 audio_io_handle_t output,
Eric Laurentde070132010-07-13 04:45:46 -07002078 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002079{
Eric Laurent0ede8922014-05-09 18:04:42 -07002080 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002081 command->mCommand = SET_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002082 sp<VolumeData> data = new VolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002083 data->mStream = stream;
2084 data->mVolume = volume;
2085 data->mIO = output;
2086 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002087 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002088 ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
Eric Laurentde070132010-07-13 04:45:46 -07002089 stream, volume, output);
Eric Laurent0ede8922014-05-09 18:04:42 -07002090 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002091}
2092
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002093status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
Dima Zavinfce7a472011-04-19 22:30:36 -07002094 const char *keyValuePairs,
Eric Laurentde070132010-07-13 04:45:46 -07002095 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002096{
Eric Laurent0ede8922014-05-09 18:04:42 -07002097 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002098 command->mCommand = SET_PARAMETERS;
Eric Laurent0ede8922014-05-09 18:04:42 -07002099 sp<ParametersData> data = new ParametersData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002100 data->mIO = ioHandle;
Dima Zavinfce7a472011-04-19 22:30:36 -07002101 data->mKeyValuePairs = String8(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002102 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002103 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002104 ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
Dima Zavinfce7a472011-04-19 22:30:36 -07002105 keyValuePairs, ioHandle, delayMs);
Eric Laurent0ede8922014-05-09 18:04:42 -07002106 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002107}
2108
2109status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
2110{
Eric Laurent0ede8922014-05-09 18:04:42 -07002111 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002112 command->mCommand = SET_VOICE_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002113 sp<VoiceVolumeData> data = new VoiceVolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002114 data->mVolume = volume;
2115 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002116 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002117 ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
Eric Laurent0ede8922014-05-09 18:04:42 -07002118 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002119}
2120
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002121void AudioPolicyService::AudioCommandThread::setEffectSuspendedCommand(int effectId,
2122 audio_session_t sessionId,
2123 bool suspended)
2124{
2125 sp<AudioCommand> command = new AudioCommand();
2126 command->mCommand = SET_EFFECT_SUSPENDED;
2127 sp<SetEffectSuspendedData> data = new SetEffectSuspendedData();
2128 data->mEffectId = effectId;
2129 data->mSessionId = sessionId;
2130 data->mSuspended = suspended;
2131 command->mParam = data;
2132 ALOGV("AudioCommandThread() adding set suspended effectId %d sessionId %d suspended %d",
2133 effectId, sessionId, suspended);
2134 sendCommand(command);
2135}
2136
2137
Eric Laurentd7fe0862018-07-14 16:48:01 -07002138void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002139{
Eric Laurent0ede8922014-05-09 18:04:42 -07002140 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002141 command->mCommand = STOP_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002142 sp<StopOutputData> data = new StopOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002143 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002144 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002145 ALOGV("AudioCommandThread() adding stop output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002146 sendCommand(command);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002147}
2148
Eric Laurentd7fe0862018-07-14 16:48:01 -07002149void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002150{
Eric Laurent0ede8922014-05-09 18:04:42 -07002151 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002152 command->mCommand = RELEASE_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002153 sp<ReleaseOutputData> data = new ReleaseOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002154 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002155 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002156 ALOGV("AudioCommandThread() adding release output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002157 sendCommand(command);
2158}
2159
Eric Laurent951f4552014-05-20 10:48:17 -07002160status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
2161 const struct audio_patch *patch,
2162 audio_patch_handle_t *handle,
2163 int delayMs)
2164{
2165 status_t status = NO_ERROR;
2166
2167 sp<AudioCommand> command = new AudioCommand();
2168 command->mCommand = CREATE_AUDIO_PATCH;
2169 CreateAudioPatchData *data = new CreateAudioPatchData();
2170 data->mPatch = *patch;
2171 data->mHandle = *handle;
2172 command->mParam = data;
2173 command->mWaitStatus = true;
2174 ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
2175 status = sendCommand(command, delayMs);
2176 if (status == NO_ERROR) {
2177 *handle = data->mHandle;
2178 }
2179 return status;
2180}
2181
2182status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
2183 int delayMs)
2184{
2185 sp<AudioCommand> command = new AudioCommand();
2186 command->mCommand = RELEASE_AUDIO_PATCH;
2187 ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
2188 data->mHandle = handle;
2189 command->mParam = data;
2190 command->mWaitStatus = true;
2191 ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
2192 return sendCommand(command, delayMs);
2193}
2194
Eric Laurentb52c1522014-05-20 11:27:36 -07002195void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
2196{
2197 sp<AudioCommand> command = new AudioCommand();
2198 command->mCommand = UPDATE_AUDIOPORT_LIST;
2199 ALOGV("AudioCommandThread() adding update audio port list");
2200 sendCommand(command);
2201}
2202
Eric Laurented726cc2021-07-01 14:26:41 +02002203void AudioPolicyService::AudioCommandThread::updateUidStatesCommand()
2204{
2205 sp<AudioCommand> command = new AudioCommand();
2206 command->mCommand = UPDATE_UID_STATES;
2207 ALOGV("AudioCommandThread() adding update UID states");
2208 sendCommand(command);
2209}
2210
Eric Laurentb52c1522014-05-20 11:27:36 -07002211void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
2212{
2213 sp<AudioCommand>command = new AudioCommand();
2214 command->mCommand = UPDATE_AUDIOPATCH_LIST;
2215 ALOGV("AudioCommandThread() adding update audio patch list");
2216 sendCommand(command);
2217}
2218
François Gaffiecfe17322018-11-07 13:41:29 +01002219void AudioPolicyService::AudioCommandThread::changeAudioVolumeGroupCommand(volume_group_t group,
2220 int flags)
2221{
2222 sp<AudioCommand>command = new AudioCommand();
2223 command->mCommand = CHANGED_AUDIOVOLUMEGROUP;
2224 AudioVolumeGroupData *data= new AudioVolumeGroupData();
2225 data->mGroup = group;
2226 data->mFlags = flags;
2227 command->mParam = data;
2228 ALOGV("AudioCommandThread() adding audio volume group changed");
2229 sendCommand(command);
2230}
2231
Eric Laurente1715a42014-05-20 11:30:42 -07002232status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
2233 const struct audio_port_config *config, int delayMs)
2234{
2235 sp<AudioCommand> command = new AudioCommand();
2236 command->mCommand = SET_AUDIOPORT_CONFIG;
2237 SetAudioPortConfigData *data = new SetAudioPortConfigData();
2238 data->mConfig = *config;
2239 command->mParam = data;
2240 command->mWaitStatus = true;
2241 ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
2242 return sendCommand(command, delayMs);
2243}
2244
Jean-Michel Trivide801052015-04-14 19:10:14 -07002245void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002246 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -07002247{
2248 sp<AudioCommand> command = new AudioCommand();
2249 command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
2250 DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
2251 data->mRegId = regId;
2252 data->mState = state;
2253 command->mParam = data;
2254 ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
2255 regId.string(), state);
2256 sendCommand(command);
2257}
2258
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002259void AudioPolicyService::AudioCommandThread::recordingConfigurationUpdateCommand(
Eric Laurenta9f86652018-11-28 17:23:11 -08002260 int event,
2261 const record_client_info_t *clientInfo,
2262 const audio_config_base_t *clientConfig,
2263 std::vector<effect_descriptor_t> clientEffects,
2264 const audio_config_base_t *deviceConfig,
2265 std::vector<effect_descriptor_t> effects,
2266 audio_patch_handle_t patchHandle,
2267 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002268{
2269 sp<AudioCommand>command = new AudioCommand();
2270 command->mCommand = RECORDING_CONFIGURATION_UPDATE;
2271 RecordingConfigurationUpdateData *data = new RecordingConfigurationUpdateData();
2272 data->mEvent = event;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002273 data->mClientInfo = *clientInfo;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002274 data->mClientConfig = *clientConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002275 data->mClientEffects = clientEffects;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002276 data->mDeviceConfig = *deviceConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002277 data->mEffects = effects;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002278 data->mPatchHandle = patchHandle;
Eric Laurenta9f86652018-11-28 17:23:11 -08002279 data->mSource = source;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002280 command->mParam = data;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002281 ALOGV("AudioCommandThread() adding recording configuration update event %d, source %d uid %u",
2282 event, clientInfo->source, clientInfo->uid);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002283 sendCommand(command);
2284}
2285
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002286void AudioPolicyService::AudioCommandThread::audioModulesUpdateCommand()
2287{
2288 sp<AudioCommand> command = new AudioCommand();
2289 command->mCommand = AUDIO_MODULES_UPDATE;
2290 sendCommand(command);
2291}
2292
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002293void AudioPolicyService::AudioCommandThread::routingChangedCommand()
2294{
2295 sp<AudioCommand>command = new AudioCommand();
2296 command->mCommand = ROUTING_UPDATED;
2297 ALOGV("AudioCommandThread() adding routing update");
2298 sendCommand(command);
2299}
2300
Eric Laurent81dd0f52021-07-05 11:54:40 +02002301void AudioPolicyService::AudioCommandThread::checkSpatializerCommand()
2302{
2303 sp<AudioCommand>command = new AudioCommand();
Eric Laurent15903592022-02-24 20:44:36 +01002304 command->mCommand = CHECK_SPATIALIZER_OUTPUT;
Eric Laurent81dd0f52021-07-05 11:54:40 +02002305 ALOGV("AudioCommandThread() adding check spatializer");
2306 sendCommand(command);
2307}
2308
Eric Laurent15903592022-02-24 20:44:36 +01002309void AudioPolicyService::AudioCommandThread::updateActiveSpatializerTracksCommand()
2310{
2311 sp<AudioCommand>command = new AudioCommand();
2312 command->mCommand = UPDATE_ACTIVE_SPATIALIZER_TRACKS;
2313 ALOGV("AudioCommandThread() adding update active spatializer tracks");
2314 sendCommand(command);
2315}
2316
Eric Laurent0ede8922014-05-09 18:04:42 -07002317status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
2318{
2319 {
2320 Mutex::Autolock _l(mLock);
2321 insertCommand_l(command, delayMs);
2322 mWaitWorkCV.signal();
2323 }
2324 Mutex::Autolock _l(command->mLock);
2325 while (command->mWaitStatus) {
2326 nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
2327 if (command->mCond.waitRelative(command->mLock, timeOutNs) != NO_ERROR) {
2328 command->mStatus = TIMED_OUT;
2329 command->mWaitStatus = false;
2330 }
2331 }
2332 return command->mStatus;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002333}
2334
Mathias Agopian65ab4712010-07-14 17:59:35 -07002335// insertCommand_l() must be called with mLock held
Eric Laurent0ede8922014-05-09 18:04:42 -07002336void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002337{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002338 ssize_t i; // not size_t because i will count down to -1
Eric Laurent0ede8922014-05-09 18:04:42 -07002339 Vector < sp<AudioCommand> > removedCommands;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002340 command->mTime = systemTime() + milliseconds(delayMs);
2341
2342 // acquire wake lock to make sure delayed commands are processed
Eric Laurentbfb1b832013-01-07 09:53:42 -08002343 if (mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002344 acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.string());
2345 }
2346
2347 // check same pending commands with later time stamps and eliminate them
Ivan Lozano5ff158f2017-10-30 09:06:24 -07002348 for (i = (ssize_t)mAudioCommands.size()-1; i >= 0; i--) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002349 sp<AudioCommand> command2 = mAudioCommands[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07002350 // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
2351 if (command2->mTime <= command->mTime) break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002352
2353 // create audio patch or release audio patch commands are equivalent
2354 // with regard to filtering
2355 if ((command->mCommand == CREATE_AUDIO_PATCH) ||
2356 (command->mCommand == RELEASE_AUDIO_PATCH)) {
2357 if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
2358 (command2->mCommand != RELEASE_AUDIO_PATCH)) {
2359 continue;
2360 }
2361 } else if (command2->mCommand != command->mCommand) continue;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002362
2363 switch (command->mCommand) {
2364 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002365 ParametersData *data = (ParametersData *)command->mParam.get();
2366 ParametersData *data2 = (ParametersData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002367 if (data->mIO != data2->mIO) break;
Steve Block3856b092011-10-20 11:56:00 +01002368 ALOGV("Comparing parameter command %s to new command %s",
Eric Laurentde070132010-07-13 04:45:46 -07002369 data2->mKeyValuePairs.string(), data->mKeyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002370 AudioParameter param = AudioParameter(data->mKeyValuePairs);
2371 AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
2372 for (size_t j = 0; j < param.size(); j++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002373 String8 key;
2374 String8 value;
2375 param.getAt(j, key, value);
2376 for (size_t k = 0; k < param2.size(); k++) {
2377 String8 key2;
2378 String8 value2;
2379 param2.getAt(k, key2, value2);
2380 if (key2 == key) {
2381 param2.remove(key2);
2382 ALOGV("Filtering out parameter %s", key2.string());
2383 break;
2384 }
2385 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002386 }
2387 // if all keys have been filtered out, remove the command.
2388 // otherwise, update the key value pairs
2389 if (param2.size() == 0) {
2390 removedCommands.add(command2);
2391 } else {
2392 data2->mKeyValuePairs = param2.toString();
2393 }
Eric Laurent21e54562013-09-23 12:08:05 -07002394 command->mTime = command2->mTime;
2395 // force delayMs to non 0 so that code below does not request to wait for
2396 // command status as the command is now delayed
2397 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002398 } break;
2399
2400 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002401 VolumeData *data = (VolumeData *)command->mParam.get();
2402 VolumeData *data2 = (VolumeData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002403 if (data->mIO != data2->mIO) break;
2404 if (data->mStream != data2->mStream) break;
Steve Block3856b092011-10-20 11:56:00 +01002405 ALOGV("Filtering out volume command on output %d for stream %d",
Eric Laurentde070132010-07-13 04:45:46 -07002406 data->mIO, data->mStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002407 removedCommands.add(command2);
Eric Laurent21e54562013-09-23 12:08:05 -07002408 command->mTime = command2->mTime;
2409 // force delayMs to non 0 so that code below does not request to wait for
2410 // command status as the command is now delayed
2411 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002412 } break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002413
Eric Laurentbaf35fe2016-07-27 15:36:53 -07002414 case SET_VOICE_VOLUME: {
2415 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
2416 VoiceVolumeData *data2 = (VoiceVolumeData *)command2->mParam.get();
2417 ALOGV("Filtering out voice volume command value %f replaced by %f",
2418 data2->mVolume, data->mVolume);
2419 removedCommands.add(command2);
2420 command->mTime = command2->mTime;
2421 // force delayMs to non 0 so that code below does not request to wait for
2422 // command status as the command is now delayed
2423 delayMs = 1;
2424 } break;
2425
Eric Laurente45b48a2014-09-04 16:40:57 -07002426 case CREATE_AUDIO_PATCH:
2427 case RELEASE_AUDIO_PATCH: {
2428 audio_patch_handle_t handle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002429 struct audio_patch patch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002430 if (command->mCommand == CREATE_AUDIO_PATCH) {
2431 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002432 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002433 } else {
2434 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
Mikhail Naganov7be71d22018-05-23 16:51:46 -07002435 memset(&patch, 0, sizeof(patch));
Eric Laurente45b48a2014-09-04 16:40:57 -07002436 }
2437 audio_patch_handle_t handle2;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002438 struct audio_patch patch2;
Eric Laurente45b48a2014-09-04 16:40:57 -07002439 if (command2->mCommand == CREATE_AUDIO_PATCH) {
2440 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002441 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002442 } else {
2443 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
Glenn Kastenf60b6b62015-07-06 10:53:26 -07002444 memset(&patch2, 0, sizeof(patch2));
Eric Laurente45b48a2014-09-04 16:40:57 -07002445 }
2446 if (handle != handle2) break;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002447 /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
2448 same output. */
2449 if( (command->mCommand == CREATE_AUDIO_PATCH) &&
2450 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
2451 bool isOutputDiff = false;
2452 if (patch.num_sources == patch2.num_sources) {
2453 for (unsigned count = 0; count < patch.num_sources; count++) {
2454 if (patch.sources[count].id != patch2.sources[count].id) {
2455 isOutputDiff = true;
2456 break;
2457 }
2458 }
2459 if (isOutputDiff)
2460 break;
2461 }
2462 }
Eric Laurente45b48a2014-09-04 16:40:57 -07002463 ALOGV("Filtering out %s audio patch command for handle %d",
2464 (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
2465 removedCommands.add(command2);
2466 command->mTime = command2->mTime;
2467 // force delayMs to non 0 so that code below does not request to wait for
2468 // command status as the command is now delayed
2469 delayMs = 1;
2470 } break;
2471
Jean-Michel Trivide801052015-04-14 19:10:14 -07002472 case DYN_POLICY_MIX_STATE_UPDATE: {
2473
2474 } break;
2475
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002476 case RECORDING_CONFIGURATION_UPDATE: {
2477
2478 } break;
2479
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002480 case ROUTING_UPDATED: {
2481
2482 } break;
2483
Mathias Agopian65ab4712010-07-14 17:59:35 -07002484 default:
2485 break;
2486 }
2487 }
2488
2489 // remove filtered commands
2490 for (size_t j = 0; j < removedCommands.size(); j++) {
2491 // removed commands always have time stamps greater than current command
2492 for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002493 if (mAudioCommands[k].get() == removedCommands[j].get()) {
Steve Block3856b092011-10-20 11:56:00 +01002494 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002495 mAudioCommands.removeAt(k);
2496 break;
2497 }
2498 }
2499 }
2500 removedCommands.clear();
2501
Eric Laurentaa79bef2015-01-15 14:33:51 -08002502 // Disable wait for status if delay is not 0.
2503 // Except for create audio patch command because the returned patch handle
2504 // is needed by audio policy manager
2505 if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
Eric Laurentcec4abb2012-07-03 12:23:02 -07002506 command->mWaitStatus = false;
2507 }
Eric Laurentcec4abb2012-07-03 12:23:02 -07002508
Mathias Agopian65ab4712010-07-14 17:59:35 -07002509 // insert command at the right place according to its time stamp
Eric Laurent1e693b52014-07-09 15:03:28 -07002510 ALOGV("inserting command: %d at index %zd, num commands %zu",
2511 command->mCommand, i+1, mAudioCommands.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002512 mAudioCommands.insertAt(command, i + 1);
2513}
2514
2515void AudioPolicyService::AudioCommandThread::exit()
2516{
Steve Block3856b092011-10-20 11:56:00 +01002517 ALOGV("AudioCommandThread::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002518 {
2519 AutoMutex _l(mLock);
2520 requestExit();
2521 mWaitWorkCV.signal();
2522 }
Zach Janga754b4f2015-10-27 01:29:34 +00002523 // Note that we can call it from the thread loop if all other references have been released
2524 // but it will safely return WOULD_BLOCK in this case
Mathias Agopian65ab4712010-07-14 17:59:35 -07002525 requestExitAndWait();
2526}
2527
2528void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
2529{
2530 snprintf(buffer, size, " %02d %06d.%03d %01u %p\n",
2531 mCommand,
2532 (int)ns2s(mTime),
2533 (int)ns2ms(mTime)%1000,
2534 mWaitStatus,
Eric Laurent0ede8922014-05-09 18:04:42 -07002535 mParam.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002536}
2537
Dima Zavinfce7a472011-04-19 22:30:36 -07002538/******* helpers for the service_ops callbacks defined below *********/
2539void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
2540 const char *keyValuePairs,
2541 int delayMs)
2542{
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002543 mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
Dima Zavinfce7a472011-04-19 22:30:36 -07002544 delayMs);
2545}
2546
2547int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
2548 float volume,
2549 audio_io_handle_t output,
2550 int delayMs)
2551{
Glenn Kastenfff6d712012-01-12 16:38:12 -08002552 return (int)mAudioCommandThread->volumeCommand(stream, volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002553 output, delayMs);
Dima Zavinfce7a472011-04-19 22:30:36 -07002554}
2555
Dima Zavinfce7a472011-04-19 22:30:36 -07002556int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
2557{
2558 return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
2559}
2560
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002561void AudioPolicyService::setEffectSuspended(int effectId,
2562 audio_session_t sessionId,
2563 bool suspended)
2564{
2565 mAudioCommandThread->setEffectSuspendedCommand(effectId, sessionId, suspended);
2566}
2567
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002568Status AudioPolicyService::onNewAudioModulesAvailable()
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002569{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07002570 mOutputCommandThread->audioModulesUpdateCommand();
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002571 return Status::ok();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002572}
2573
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002574
Dima Zavinfce7a472011-04-19 22:30:36 -07002575extern "C" {
Eric Laurent2d388ec2014-03-07 13:25:54 -08002576audio_module_handle_t aps_load_hw_module(void *service __unused,
2577 const char *name);
2578audio_io_handle_t aps_open_output(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002579 audio_devices_t *pDevices,
2580 uint32_t *pSamplingRate,
2581 audio_format_t *pFormat,
2582 audio_channel_mask_t *pChannelMask,
2583 uint32_t *pLatencyMs,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002584 audio_output_flags_t flags);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002585
Eric Laurent2d388ec2014-03-07 13:25:54 -08002586audio_io_handle_t aps_open_output_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002587 audio_module_handle_t module,
2588 audio_devices_t *pDevices,
2589 uint32_t *pSamplingRate,
2590 audio_format_t *pFormat,
2591 audio_channel_mask_t *pChannelMask,
2592 uint32_t *pLatencyMs,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002593 audio_output_flags_t flags,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002594 const audio_offload_info_t *offloadInfo);
2595audio_io_handle_t aps_open_dup_output(void *service __unused,
Dima Zavinfce7a472011-04-19 22:30:36 -07002596 audio_io_handle_t output1,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002597 audio_io_handle_t output2);
2598int aps_close_output(void *service __unused, audio_io_handle_t output);
2599int aps_suspend_output(void *service __unused, audio_io_handle_t output);
2600int aps_restore_output(void *service __unused, audio_io_handle_t output);
2601audio_io_handle_t aps_open_input(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002602 audio_devices_t *pDevices,
2603 uint32_t *pSamplingRate,
2604 audio_format_t *pFormat,
2605 audio_channel_mask_t *pChannelMask,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002606 audio_in_acoustics_t acoustics __unused);
2607audio_io_handle_t aps_open_input_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002608 audio_module_handle_t module,
2609 audio_devices_t *pDevices,
2610 uint32_t *pSamplingRate,
2611 audio_format_t *pFormat,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002612 audio_channel_mask_t *pChannelMask);
2613int aps_close_input(void *service __unused, audio_io_handle_t input);
2614int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
Glenn Kastend848eb42016-03-08 13:42:11 -08002615int aps_move_effects(void *service __unused, audio_session_t session,
Dima Zavinfce7a472011-04-19 22:30:36 -07002616 audio_io_handle_t src_output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002617 audio_io_handle_t dst_output);
2618char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
2619 const char *keys);
2620void aps_set_parameters(void *service, audio_io_handle_t io_handle,
2621 const char *kv_pairs, int delay_ms);
2622int aps_set_stream_volume(void *service, audio_stream_type_t stream,
Dima Zavinfce7a472011-04-19 22:30:36 -07002623 float volume, audio_io_handle_t output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002624 int delay_ms);
Eric Laurent2d388ec2014-03-07 13:25:54 -08002625int aps_set_voice_volume(void *service, float volume, int delay_ms);
2626};
Dima Zavinfce7a472011-04-19 22:30:36 -07002627
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08002628} // namespace android