blob: 38b58d5a7183bfa6927c42e28eeba03710fbecd5 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "AudioPolicyService"
18//#define LOG_NDEBUG 0
19
Glenn Kasten153b9fe2013-07-15 11:23:36 -070020#include "Configuration.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070021#undef __STRICT_ANSI__
22#define __STDINT_LIMITS
23#define __STDC_LIMIT_MACROS
24#include <stdint.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070025#include <sys/time.h>
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053026#include <dlfcn.h>
Mikhail Naganov959e2d02019-03-28 11:08:19 -070027
28#include <audio_utils/clock.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070029#include <binder/IServiceManager.h>
30#include <utils/Log.h>
31#include <cutils/properties.h>
32#include <binder/IPCThreadState.h>
Svet Ganovf4ddfef2018-01-16 07:37:58 -080033#include <binder/PermissionController.h>
34#include <binder/IResultReceiver.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035#include <utils/String16.h>
36#include <utils/threads.h>
37#include "AudioPolicyService.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070038#include <hardware_legacy/power.h>
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -080039#include <media/AidlConversion.h>
Eric Laurent7c7f10b2011-06-17 21:29:58 -070040#include <media/AudioEffect.h>
Chih-Hung Hsiehc84d9d22014-11-14 13:33:34 -080041#include <media/AudioParameter.h>
Andy Hungab7ef302018-05-15 19:35:29 -070042#include <mediautils/ServiceUtilities.h>
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -080043#include <mediautils/TimeCheck.h>
Michael Groovercfd28302018-12-11 19:16:46 -080044#include <sensorprivacy/SensorPrivacyManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045
Dima Zavin64760242011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070047#include <system/audio_policy.h>
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053048#include <AudioPolicyManager.h>
Mikhail Naganov61a4fac2016-10-13 14:44:18 -070049
Mathias Agopian65ab4712010-07-14 17:59:35 -070050namespace android {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -080051using binder::Status;
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
Glenn Kasten8dad0e32012-01-09 08:41:22 -080053static const char kDeadlockedString[] = "AudioPolicyService may be deadlocked\n";
54static const char kCmdDeadlockedString[] = "AudioPolicyService command thread may be deadlocked\n";
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053055static const char kAudioPolicyManagerCustomPath[] = "libaudiopolicymanagercustom.so";
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Mikhail Naganov959e2d02019-03-28 11:08:19 -070057static const int kDumpLockTimeoutNs = 1 * NANOS_PER_SECOND;
Mathias Agopian65ab4712010-07-14 17:59:35 -070058
Eric Laurent0ede8922014-05-09 18:04:42 -070059static const nsecs_t kAudioCommandTimeoutNs = seconds(3); // 3 seconds
Christer Fletcher5fa8c4b2013-01-18 15:27:03 +010060
Svet Ganovf4ddfef2018-01-16 07:37:58 -080061static const String16 sManageAudioPolicyPermission("android.permission.MANAGE_AUDIO_POLICY");
Dima Zavinfce7a472011-04-19 22:30:36 -070062
Mathias Agopian65ab4712010-07-14 17:59:35 -070063// ----------------------------------------------------------------------------
64
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053065static AudioPolicyInterface* createAudioPolicyManager(AudioPolicyClientInterface *clientInterface)
66{
67 AudioPolicyManager *apm = new AudioPolicyManager(clientInterface);
68 status_t status = apm->initialize();
69 if (status != NO_ERROR) {
70 delete apm;
71 apm = nullptr;
72 }
73 return apm;
74}
75
76static void destroyAudioPolicyManager(AudioPolicyInterface *interface)
77{
78 delete interface;
79}
80// ----------------------------------------------------------------------------
81
Mathias Agopian65ab4712010-07-14 17:59:35 -070082AudioPolicyService::AudioPolicyService()
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -070083 : BnAudioPolicyService(),
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -070084 mAudioPolicyManager(NULL),
85 mAudioPolicyClient(NULL),
86 mPhoneState(AUDIO_MODE_INVALID),
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053087 mCaptureStateNotifier(false),
88 mCreateAudioPolicyManager(createAudioPolicyManager),
89 mDestroyAudioPolicyManager(destroyAudioPolicyManager) {
90}
91
92void AudioPolicyService::loadAudioPolicyManager()
93{
94 mLibraryHandle = dlopen(kAudioPolicyManagerCustomPath, RTLD_NOW);
95 if (mLibraryHandle != nullptr) {
96 ALOGI("%s loading %s", __func__, kAudioPolicyManagerCustomPath);
97 mCreateAudioPolicyManager = reinterpret_cast<CreateAudioPolicyManagerInstance>
98 (dlsym(mLibraryHandle, "createAudioPolicyManager"));
99 const char *lastError = dlerror();
100 ALOGW_IF(mCreateAudioPolicyManager == nullptr, "%s createAudioPolicyManager is null %s",
101 __func__, lastError != nullptr ? lastError : "no error");
102
103 mDestroyAudioPolicyManager = reinterpret_cast<DestroyAudioPolicyManagerInstance>(
104 dlsym(mLibraryHandle, "destroyAudioPolicyManager"));
105 lastError = dlerror();
106 ALOGW_IF(mDestroyAudioPolicyManager == nullptr, "%s destroyAudioPolicyManager is null %s",
107 __func__, lastError != nullptr ? lastError : "no error");
108 if (mCreateAudioPolicyManager == nullptr || mDestroyAudioPolicyManager == nullptr){
109 unloadAudioPolicyManager();
110 LOG_ALWAYS_FATAL("could not find audiopolicymanager interface methods");
111 }
112 }
Eric Laurentf5ada6e2014-10-09 17:49:00 -0700113}
114
115void AudioPolicyService::onFirstRef()
116{
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700117 {
118 Mutex::Autolock _l(mLock);
Eric Laurent93575202011-01-18 18:39:02 -0800119
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700120 // start audio commands thread
121 mAudioCommandThread = new AudioCommandThread(String8("ApmAudio"), this);
122 // start output activity command thread
123 mOutputCommandThread = new AudioCommandThread(String8("ApmOutput"), this);
Eric Laurentdce54a12014-03-10 12:19:46 -0700124
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700125 mAudioPolicyClient = new AudioPolicyClient(this);
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530126
127 loadAudioPolicyManager();
128 mAudioPolicyManager = mCreateAudioPolicyManager(mAudioPolicyClient);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700129 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200130
bryant_liuba2b4392014-06-11 16:49:30 +0800131 // load audio processing modules
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000132 sp<AudioPolicyEffects> audioPolicyEffects = new AudioPolicyEffects();
133 sp<UidPolicy> uidPolicy = new UidPolicy(this);
134 sp<SensorPrivacyPolicy> sensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700135 {
136 Mutex::Autolock _l(mLock);
137 mAudioPolicyEffects = audioPolicyEffects;
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000138 mUidPolicy = uidPolicy;
139 mSensorPrivacyPolicy = sensorPrivacyPolicy;
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700140 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000141 uidPolicy->registerSelf();
142 sensorPrivacyPolicy->registerSelf();
Eric Laurentd66d7a12021-07-13 13:35:32 +0200143
Eric Laurent81dd0f52021-07-05 11:54:40 +0200144 // Create spatializer if supported
Eric Laurent52b0bd52021-09-27 15:25:40 +0200145 if (mAudioPolicyManager != nullptr) {
146 Mutex::Autolock _l(mLock);
147 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
148 AudioDeviceTypeAddrVector devices;
149 bool hasSpatializer = mAudioPolicyManager->canBeSpatialized(&attr, nullptr, devices);
150 if (hasSpatializer) {
151 mSpatializer = Spatializer::create(this);
152 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200153 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200154 AudioSystem::audioPolicyReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700155}
156
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530157void AudioPolicyService::unloadAudioPolicyManager()
158{
159 ALOGV("%s ", __func__);
160 if (mLibraryHandle != nullptr) {
161 dlclose(mLibraryHandle);
162 }
163 mLibraryHandle = nullptr;
164 mCreateAudioPolicyManager = nullptr;
165 mDestroyAudioPolicyManager = nullptr;
166}
167
Mathias Agopian65ab4712010-07-14 17:59:35 -0700168AudioPolicyService::~AudioPolicyService()
169{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700170 mAudioCommandThread->exit();
Eric Laurent657ff612014-05-07 11:58:24 -0700171 mOutputCommandThread->exit();
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700172
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530173 mDestroyAudioPolicyManager(mAudioPolicyManager);
174 unloadAudioPolicyManager();
175
Eric Laurentdce54a12014-03-10 12:19:46 -0700176 delete mAudioPolicyClient;
Eric Laurentb52c1522014-05-20 11:27:36 -0700177
178 mNotificationClients.clear();
bryant_liuba2b4392014-06-11 16:49:30 +0800179 mAudioPolicyEffects.clear();
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800180
181 mUidPolicy->unregisterSelf();
Michael Groovercfd28302018-12-11 19:16:46 -0800182 mSensorPrivacyPolicy->unregisterSelf();
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000183
184 mUidPolicy.clear();
Michael Groovercfd28302018-12-11 19:16:46 -0800185 mSensorPrivacyPolicy.clear();
Eric Laurentb52c1522014-05-20 11:27:36 -0700186}
187
188// A notification client is always registered by AudioSystem when the client process
189// connects to AudioPolicyService.
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800190Status AudioPolicyService::registerClient(const sp<media::IAudioPolicyServiceClient>& client)
Eric Laurentb52c1522014-05-20 11:27:36 -0700191{
Eric Laurent12590252015-08-21 18:40:20 -0700192 if (client == 0) {
193 ALOGW("%s got NULL client", __FUNCTION__);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800194 return Status::ok();
Eric Laurent12590252015-08-21 18:40:20 -0700195 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800196 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700197
198 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800199 pid_t pid = IPCThreadState::self()->getCallingPid();
200 int64_t token = ((int64_t)uid<<32) | pid;
201
202 if (mNotificationClients.indexOfKey(token) < 0) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700203 sp<NotificationClient> notificationClient = new NotificationClient(this,
204 client,
luochaojiang908c7d72018-06-21 14:58:04 +0800205 uid,
206 pid);
207 ALOGV("registerClient() client %p, uid %d pid %d", client.get(), uid, pid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700208
luochaojiang908c7d72018-06-21 14:58:04 +0800209 mNotificationClients.add(token, notificationClient);
Eric Laurentb52c1522014-05-20 11:27:36 -0700210
Marco Nelissenf8880202014-11-14 07:58:25 -0800211 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurentb52c1522014-05-20 11:27:36 -0700212 binder->linkToDeath(notificationClient);
213 }
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800214 return Status::ok();
Eric Laurentb52c1522014-05-20 11:27:36 -0700215}
216
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800217Status AudioPolicyService::setAudioPortCallbacksEnabled(bool enabled)
Eric Laurente8726fe2015-06-26 09:39:24 -0700218{
219 Mutex::Autolock _l(mNotificationClientsLock);
220
221 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800222 pid_t pid = IPCThreadState::self()->getCallingPid();
223 int64_t token = ((int64_t)uid<<32) | pid;
224
225 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800226 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700227 }
luochaojiang908c7d72018-06-21 14:58:04 +0800228 mNotificationClients.valueFor(token)->setAudioPortCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800229 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700230}
231
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800232Status AudioPolicyService::setAudioVolumeGroupCallbacksEnabled(bool enabled)
François Gaffiecfe17322018-11-07 13:41:29 +0100233{
234 Mutex::Autolock _l(mNotificationClientsLock);
235
236 uid_t uid = IPCThreadState::self()->getCallingUid();
237 pid_t pid = IPCThreadState::self()->getCallingPid();
238 int64_t token = ((int64_t)uid<<32) | pid;
239
240 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800241 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100242 }
243 mNotificationClients.valueFor(token)->setAudioVolumeGroupCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800244 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100245}
246
Eric Laurentb52c1522014-05-20 11:27:36 -0700247// removeNotificationClient() is called when the client process dies.
luochaojiang908c7d72018-06-21 14:58:04 +0800248void AudioPolicyService::removeNotificationClient(uid_t uid, pid_t pid)
Eric Laurentb52c1522014-05-20 11:27:36 -0700249{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000250 bool hasSameUid = false;
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800251 {
252 Mutex::Autolock _l(mNotificationClientsLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800253 int64_t token = ((int64_t)uid<<32) | pid;
254 mNotificationClients.removeItem(token);
luochaojiang908c7d72018-06-21 14:58:04 +0800255 for (size_t i = 0; i < mNotificationClients.size(); i++) {
256 if (mNotificationClients.valueAt(i)->uid() == uid) {
257 hasSameUid = true;
258 break;
259 }
260 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000261 }
262 {
263 Mutex::Autolock _l(mLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800264 if (mAudioPolicyManager && !hasSameUid) {
Eric Laurent10b71232018-04-13 18:14:44 -0700265 // called from binder death notification: no need to clear caller identity
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700266 mAudioPolicyManager->releaseResourcesForUid(uid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700267 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800268 }
Eric Laurentb52c1522014-05-20 11:27:36 -0700269}
270
271void AudioPolicyService::onAudioPortListUpdate()
272{
273 mOutputCommandThread->updateAudioPortListCommand();
274}
275
276void AudioPolicyService::doOnAudioPortListUpdate()
277{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800278 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700279 for (size_t i = 0; i < mNotificationClients.size(); i++) {
280 mNotificationClients.valueAt(i)->onAudioPortListUpdate();
281 }
282}
283
284void AudioPolicyService::onAudioPatchListUpdate()
285{
286 mOutputCommandThread->updateAudioPatchListCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700287}
288
Eric Laurentb52c1522014-05-20 11:27:36 -0700289void AudioPolicyService::doOnAudioPatchListUpdate()
290{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800291 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700292 for (size_t i = 0; i < mNotificationClients.size(); i++) {
293 mNotificationClients.valueAt(i)->onAudioPatchListUpdate();
294 }
295}
296
François Gaffiecfe17322018-11-07 13:41:29 +0100297void AudioPolicyService::onAudioVolumeGroupChanged(volume_group_t group, int flags)
298{
299 mOutputCommandThread->changeAudioVolumeGroupCommand(group, flags);
300}
301
302void AudioPolicyService::doOnAudioVolumeGroupChanged(volume_group_t group, int flags)
303{
304 Mutex::Autolock _l(mNotificationClientsLock);
305 for (size_t i = 0; i < mNotificationClients.size(); i++) {
306 mNotificationClients.valueAt(i)->onAudioVolumeGroupChanged(group, flags);
307 }
308}
309
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700310void AudioPolicyService::onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700311{
312 ALOGV("AudioPolicyService::onDynamicPolicyMixStateUpdate(%s, %d)",
313 regId.string(), state);
314 mOutputCommandThread->dynamicPolicyMixStateUpdateCommand(regId, state);
315}
316
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700317void AudioPolicyService::doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700318{
319 Mutex::Autolock _l(mNotificationClientsLock);
320 for (size_t i = 0; i < mNotificationClients.size(); i++) {
321 mNotificationClients.valueAt(i)->onDynamicPolicyMixStateUpdate(regId, state);
322 }
323}
324
Eric Laurenta9f86652018-11-28 17:23:11 -0800325void AudioPolicyService::onRecordingConfigurationUpdate(
326 int event,
327 const record_client_info_t *clientInfo,
328 const audio_config_base_t *clientConfig,
329 std::vector<effect_descriptor_t> clientEffects,
330 const audio_config_base_t *deviceConfig,
331 std::vector<effect_descriptor_t> effects,
332 audio_patch_handle_t patchHandle,
333 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800334{
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800335 mOutputCommandThread->recordingConfigurationUpdateCommand(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800336 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800337}
338
Eric Laurenta9f86652018-11-28 17:23:11 -0800339void AudioPolicyService::doOnRecordingConfigurationUpdate(
340 int event,
341 const record_client_info_t *clientInfo,
342 const audio_config_base_t *clientConfig,
343 std::vector<effect_descriptor_t> clientEffects,
344 const audio_config_base_t *deviceConfig,
345 std::vector<effect_descriptor_t> effects,
346 audio_patch_handle_t patchHandle,
347 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800348{
349 Mutex::Autolock _l(mNotificationClientsLock);
350 for (size_t i = 0; i < mNotificationClients.size(); i++) {
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800351 mNotificationClients.valueAt(i)->onRecordingConfigurationUpdate(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800352 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800353 }
354}
355
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700356void AudioPolicyService::onRoutingUpdated()
357{
358 mOutputCommandThread->routingChangedCommand();
359}
360
361void AudioPolicyService::doOnRoutingUpdated()
362{
363 Mutex::Autolock _l(mNotificationClientsLock);
364 for (size_t i = 0; i < mNotificationClients.size(); i++) {
365 mNotificationClients.valueAt(i)->onRoutingUpdated();
366 }
367}
368
Eric Laurent81dd0f52021-07-05 11:54:40 +0200369void AudioPolicyService::onCheckSpatializer()
370{
371 Mutex::Autolock _l(mLock);
Eric Laurent39095982021-08-24 18:29:27 +0200372 onCheckSpatializer_l();
373}
374
375void AudioPolicyService::onCheckSpatializer_l()
376{
377 if (mSpatializer != nullptr) {
378 mOutputCommandThread->checkSpatializerCommand();
379 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200380}
381
382void AudioPolicyService::doOnCheckSpatializer()
383{
Eric Laurent39095982021-08-24 18:29:27 +0200384 Mutex::Autolock _l(mLock);
Eric Laurent81dd0f52021-07-05 11:54:40 +0200385
Eric Laurent39095982021-08-24 18:29:27 +0200386 if (mSpatializer != nullptr) {
Eric Laurent52b0bd52021-09-27 15:25:40 +0200387 // Note: mSpatializer != nullptr => mAudioPolicyManager != nullptr
Eric Laurent39095982021-08-24 18:29:27 +0200388 if (mSpatializer->getLevel() != media::SpatializationLevel::NONE) {
389 audio_io_handle_t currentOutput = mSpatializer->getOutput();
390 audio_io_handle_t newOutput;
391 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
392 audio_config_base_t config = mSpatializer->getAudioInConfig();
393 status_t status =
394 mAudioPolicyManager->getSpatializerOutput(&config, &attr, &newOutput);
Eric Laurentb4f42a92022-01-17 17:37:31 +0100395 ALOGV("%s currentOutput %d newOutput %d channel_mask %#x",
396 __func__, currentOutput, newOutput, config.channel_mask);
Eric Laurent39095982021-08-24 18:29:27 +0200397 if (status == NO_ERROR && currentOutput == newOutput) {
398 return;
399 }
400 mLock.unlock();
401 // It is OK to call detachOutput() is none is already attached.
402 mSpatializer->detachOutput();
403 if (status != NO_ERROR || newOutput == AUDIO_IO_HANDLE_NONE) {
Eric Laurent81dd0f52021-07-05 11:54:40 +0200404 mLock.lock();
Eric Laurent39095982021-08-24 18:29:27 +0200405 return;
406 }
407 status = mSpatializer->attachOutput(newOutput);
408 mLock.lock();
409 if (status != NO_ERROR) {
410 mAudioPolicyManager->releaseSpatializerOutput(newOutput);
411 }
412 } else if (mSpatializer->getLevel() == media::SpatializationLevel::NONE
413 && mSpatializer->getOutput() != AUDIO_IO_HANDLE_NONE) {
414 mLock.unlock();
415 audio_io_handle_t output = mSpatializer->detachOutput();
416 mLock.lock();
417 if (output != AUDIO_IO_HANDLE_NONE) {
418 mAudioPolicyManager->releaseSpatializerOutput(output);
Eric Laurent81dd0f52021-07-05 11:54:40 +0200419 }
420 }
421 }
422}
423
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800424status_t AudioPolicyService::clientCreateAudioPatch(const struct audio_patch *patch,
425 audio_patch_handle_t *handle,
426 int delayMs)
427{
428 return mAudioCommandThread->createAudioPatchCommand(patch, handle, delayMs);
429}
430
431status_t AudioPolicyService::clientReleaseAudioPatch(audio_patch_handle_t handle,
432 int delayMs)
433{
434 return mAudioCommandThread->releaseAudioPatchCommand(handle, delayMs);
435}
436
Eric Laurente1715a42014-05-20 11:30:42 -0700437status_t AudioPolicyService::clientSetAudioPortConfig(const struct audio_port_config *config,
438 int delayMs)
439{
440 return mAudioCommandThread->setAudioPortConfigCommand(config, delayMs);
441}
442
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800443AudioPolicyService::NotificationClient::NotificationClient(
444 const sp<AudioPolicyService>& service,
445 const sp<media::IAudioPolicyServiceClient>& client,
446 uid_t uid,
447 pid_t pid)
luochaojiang908c7d72018-06-21 14:58:04 +0800448 : mService(service), mUid(uid), mPid(pid), mAudioPolicyServiceClient(client),
François Gaffiecfe17322018-11-07 13:41:29 +0100449 mAudioPortCallbacksEnabled(false), mAudioVolumeGroupCallbacksEnabled(false)
Eric Laurentb52c1522014-05-20 11:27:36 -0700450{
451}
452
453AudioPolicyService::NotificationClient::~NotificationClient()
454{
455}
456
457void AudioPolicyService::NotificationClient::binderDied(const wp<IBinder>& who __unused)
458{
459 sp<NotificationClient> keep(this);
460 sp<AudioPolicyService> service = mService.promote();
461 if (service != 0) {
luochaojiang908c7d72018-06-21 14:58:04 +0800462 service->removeNotificationClient(mUid, mPid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700463 }
464}
465
466void AudioPolicyService::NotificationClient::onAudioPortListUpdate()
467{
Eric Laurente8726fe2015-06-26 09:39:24 -0700468 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700469 mAudioPolicyServiceClient->onAudioPortListUpdate();
470 }
471}
472
473void AudioPolicyService::NotificationClient::onAudioPatchListUpdate()
474{
Eric Laurente8726fe2015-06-26 09:39:24 -0700475 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700476 mAudioPolicyServiceClient->onAudioPatchListUpdate();
477 }
478}
Eric Laurent57dae992011-07-24 13:36:09 -0700479
Pattydd807582021-11-04 21:01:03 +0800480void AudioPolicyService::NotificationClient::onAudioVolumeGroupChanged(volume_group_t group,
François Gaffiecfe17322018-11-07 13:41:29 +0100481 int flags)
482{
483 if (mAudioPolicyServiceClient != 0 && mAudioVolumeGroupCallbacksEnabled) {
484 mAudioPolicyServiceClient->onAudioVolumeGroupChanged(group, flags);
485 }
486}
487
488
Jean-Michel Trivide801052015-04-14 19:10:14 -0700489void AudioPolicyService::NotificationClient::onDynamicPolicyMixStateUpdate(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700490 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700491{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700492 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800493 mAudioPolicyServiceClient->onDynamicPolicyMixStateUpdate(
494 legacy2aidl_String8_string(regId).value(), state);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800495 }
496}
497
498void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate(
Eric Laurenta9f86652018-11-28 17:23:11 -0800499 int event,
500 const record_client_info_t *clientInfo,
501 const audio_config_base_t *clientConfig,
502 std::vector<effect_descriptor_t> clientEffects,
503 const audio_config_base_t *deviceConfig,
504 std::vector<effect_descriptor_t> effects,
505 audio_patch_handle_t patchHandle,
506 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800507{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700508 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800509 status_t status = [&]() -> status_t {
510 int32_t eventAidl = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(event));
511 media::RecordClientInfo clientInfoAidl = VALUE_OR_RETURN_STATUS(
512 legacy2aidl_record_client_info_t_RecordClientInfo(*clientInfo));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700513 AudioConfigBase clientConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700514 legacy2aidl_audio_config_base_t_AudioConfigBase(
515 *clientConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800516 std::vector<media::EffectDescriptor> clientEffectsAidl = VALUE_OR_RETURN_STATUS(
517 convertContainer<std::vector<media::EffectDescriptor>>(
518 clientEffects,
519 legacy2aidl_effect_descriptor_t_EffectDescriptor));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700520 AudioConfigBase deviceConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700521 legacy2aidl_audio_config_base_t_AudioConfigBase(
522 *deviceConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800523 std::vector<media::EffectDescriptor> effectsAidl = VALUE_OR_RETURN_STATUS(
524 convertContainer<std::vector<media::EffectDescriptor>>(
525 effects,
526 legacy2aidl_effect_descriptor_t_EffectDescriptor));
527 int32_t patchHandleAidl = VALUE_OR_RETURN_STATUS(
528 legacy2aidl_audio_patch_handle_t_int32_t(patchHandle));
Mikhail Naganovddceecc2021-09-03 13:58:56 -0700529 media::audio::common::AudioSource sourceAidl = VALUE_OR_RETURN_STATUS(
530 legacy2aidl_audio_source_t_AudioSource(source));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800531 return aidl_utils::statusTFromBinderStatus(
532 mAudioPolicyServiceClient->onRecordingConfigurationUpdate(eventAidl,
533 clientInfoAidl,
534 clientConfigAidl,
535 clientEffectsAidl,
536 deviceConfigAidl,
537 effectsAidl,
538 patchHandleAidl,
539 sourceAidl));
540 }();
541 ALOGW_IF(status != OK, "onRecordingConfigurationUpdate() failed: %d", status);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700542 }
543}
544
Eric Laurente8726fe2015-06-26 09:39:24 -0700545void AudioPolicyService::NotificationClient::setAudioPortCallbacksEnabled(bool enabled)
546{
547 mAudioPortCallbacksEnabled = enabled;
548}
549
François Gaffiecfe17322018-11-07 13:41:29 +0100550void AudioPolicyService::NotificationClient::setAudioVolumeGroupCallbacksEnabled(bool enabled)
551{
552 mAudioVolumeGroupCallbacksEnabled = enabled;
553}
Eric Laurente8726fe2015-06-26 09:39:24 -0700554
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700555void AudioPolicyService::NotificationClient::onRoutingUpdated()
556{
557 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
558 mAudioPolicyServiceClient->onRoutingUpdated();
559 }
560}
561
Mathias Agopian65ab4712010-07-14 17:59:35 -0700562void AudioPolicyService::binderDied(const wp<IBinder>& who) {
Glenn Kasten411e4472012-11-02 10:00:06 -0700563 ALOGW("binderDied() %p, calling pid %d", who.unsafe_get(),
Eric Laurentde070132010-07-13 04:45:46 -0700564 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700565}
566
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000567static bool dumpTryLock(Mutex& mutex) ACQUIRE(mutex) NO_THREAD_SAFETY_ANALYSIS
Mathias Agopian65ab4712010-07-14 17:59:35 -0700568{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000569 return mutex.timedLock(kDumpLockTimeoutNs) == NO_ERROR;
570}
571
572static void dumpReleaseLock(Mutex& mutex, bool locked) RELEASE(mutex) NO_THREAD_SAFETY_ANALYSIS
573{
574 if (locked) mutex.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700575}
576
577status_t AudioPolicyService::dumpInternals(int fd)
578{
579 const size_t SIZE = 256;
580 char buffer[SIZE];
581 String8 result;
582
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000583 snprintf(buffer, SIZE, "Supported System Usages:\n ");
Hayden Gomes524159d2019-12-23 14:41:47 -0800584 result.append(buffer);
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000585 std::stringstream msg;
586 size_t i = 0;
587 for (auto usage : mSupportedSystemUsages) {
588 if (i++ != 0) msg << ", ";
589 if (const char* strUsage = audio_usage_to_string(usage); strUsage) {
590 msg << strUsage;
591 } else {
592 msg << usage << " (unknown)";
593 }
Hayden Gomes524159d2019-12-23 14:41:47 -0800594 }
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +0000595 if (i == 0) {
596 msg << "None";
597 }
598 msg << std::endl;
599 result.append(msg.str().c_str());
Hayden Gomes524159d2019-12-23 14:41:47 -0800600
Mathias Agopian65ab4712010-07-14 17:59:35 -0700601 write(fd, result.string(), result.size());
Oscar Azucena829d90d2022-01-28 17:17:56 -0800602
603 mUidPolicy->dumpInternals(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700604 return NO_ERROR;
605}
606
Eric Laurente8c8b432018-10-17 10:08:02 -0700607void AudioPolicyService::updateUidStates()
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800608{
Eric Laurente8c8b432018-10-17 10:08:02 -0700609 Mutex::Autolock _l(mLock);
610 updateUidStates_l();
611}
612
613void AudioPolicyService::updateUidStates_l()
614{
Eric Laurent4eb58f12018-12-07 16:41:02 -0800615// Go over all active clients and allow capture (does not force silence) in the
616// following cases:
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800617// The client is in the active assistant list
618// AND is TOP
619// AND an accessibility service is TOP
620// AND source is either VOICE_RECOGNITION OR HOTWORD
621// OR there is no active privacy sensitive capture or call
622// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
623// AND source is VOICE_RECOGNITION OR HOTWORD
624// The client is an assistant AND active assistant is not being used
Evan Severson1f700cd2021-02-10 13:10:37 -0800625// AND an accessibility service is on TOP or a RTT call is active
Eric Laurent589171c2019-07-25 18:04:29 -0700626// AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800627// OR there is no active privacy sensitive capture or call
Evan Severson1f700cd2021-02-10 13:10:37 -0800628// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800629// AND is TOP most recent assistant and uses VOICE_RECOGNITION or HOTWORD
630// OR there is no top recent assistant and source is HOTWORD
Evan Severson1f700cd2021-02-10 13:10:37 -0800631// OR The client is an accessibility service
632// AND Is on TOP
633// AND the source is VOICE_RECOGNITION or HOTWORD
634// OR The assistant is not on TOP
Eric Laurent589171c2019-07-25 18:04:29 -0700635// AND there is no active privacy sensitive capture or call
636// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Evan Severson1f700cd2021-02-10 13:10:37 -0800637// AND is on TOP
638// AND the source is VOICE_RECOGNITION or HOTWORD
639// OR the client source is virtual (remote submix, call audio TX or RX...)
640// OR the client source is HOTWORD
641// AND is on TOP
642// OR all active clients are using HOTWORD source
643// AND no call is active
644// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
645// OR the client is the current InputMethodService
646// AND a RTT call is active AND the source is VOICE_RECOGNITION
647// OR Any client
648// AND The assistant is not on TOP
649// AND is on TOP or latest started
650// AND there is no active privacy sensitive capture or call
651// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4eb58f12018-12-07 16:41:02 -0800652
Eric Laurent4e947da2019-10-17 15:24:06 -0700653
Eric Laurent4eb58f12018-12-07 16:41:02 -0800654 sp<AudioRecordClient> topActive;
655 sp<AudioRecordClient> latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800656 sp<AudioRecordClient> topSensitiveActive;
Eric Laurentb809a752020-06-29 09:53:13 -0700657 sp<AudioRecordClient> latestSensitiveActiveOrComm;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800658 sp<AudioRecordClient> latestActiveAssistant;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700659
Eric Laurenta46bedb2018-12-07 18:01:26 -0800660 nsecs_t topStartNs = 0;
661 nsecs_t latestStartNs = 0;
Eric Laurentc21d5692020-02-25 10:24:36 -0800662 nsecs_t topSensitiveStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800663 nsecs_t latestSensitiveStartNs = 0;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800664 nsecs_t latestAssistantStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800665 bool isA11yOnTop = mUidPolicy->isA11yOnTop();
666 bool isAssistantOnTop = false;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800667 bool useActiveAssistantList = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800668 bool isSensitiveActive = false;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700669 bool isInCall = mPhoneState == AUDIO_MODE_IN_CALL;
Eric Laurentc21d5692020-02-25 10:24:36 -0800670 bool isInCommunication = mPhoneState == AUDIO_MODE_IN_COMMUNICATION;
671 bool rttCallActive = (isInCall || isInCommunication)
Eric Laurent6ede98f2019-06-11 14:50:30 -0700672 && mUidPolicy->isRttEnabled();
Eric Laurent4e947da2019-10-17 15:24:06 -0700673 bool onlyHotwordActive = true;
Eric Laurentb809a752020-06-29 09:53:13 -0700674 bool isPhoneStateOwnerActive = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800675
Michael Groovercfd28302018-12-11 19:16:46 -0800676 // if Sensor Privacy is enabled then all recordings should be silenced.
677 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
678 silenceAllRecordings_l();
679 return;
680 }
681
Eric Laurente8c8b432018-10-17 10:08:02 -0700682 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
683 sp<AudioRecordClient> current = mAudioRecordClients[i];
Svet Ganov33761132021-05-13 22:51:08 +0000684 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
685 current->attributionSource.uid));
Evan Severson1f700cd2021-02-10 13:10:37 -0800686 if (!current->active) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700687 continue;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800688 }
Eric Laurent1ff16a72019-03-14 18:35:04 -0700689
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700690 app_state_t appState = apmStatFromAmState(mUidPolicy->getUidState(currentUid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700691 // clients which app is in IDLE state are not eligible for top active or
692 // latest active
693 if (appState == APP_STATE_IDLE) {
694 continue;
695 }
696
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700697 bool isAccessibility = mUidPolicy->isA11yUid(currentUid);
Eric Laurent14a88632020-07-16 12:28:30 -0700698 // Clients capturing for Accessibility services or virtual sources are not considered
Eric Laurentc21d5692020-02-25 10:24:36 -0800699 // for top or latest active to avoid masking regular clients started before
Eric Laurent14a88632020-07-16 12:28:30 -0700700 if (!isAccessibility && !isVirtualSource(current->attributes.source)) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700701 bool isAssistant = mUidPolicy->isAssistantUid(currentUid);
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800702 bool isActiveAssistant = mUidPolicy->isActiveAssistantUid(currentUid);
Eric Laurentc21d5692020-02-25 10:24:36 -0800703 bool isPrivacySensitive =
704 (current->attributes.flags & AUDIO_FLAG_CAPTURE_PRIVATE) != 0;
Eric Laurentb809a752020-06-29 09:53:13 -0700705
Eric Laurentc21d5692020-02-25 10:24:36 -0800706 if (appState == APP_STATE_TOP) {
707 if (isPrivacySensitive) {
708 if (current->startTimeNs > topSensitiveStartNs) {
709 topSensitiveActive = current;
710 topSensitiveStartNs = current->startTimeNs;
711 }
712 } else {
713 if (current->startTimeNs > topStartNs) {
714 topActive = current;
715 topStartNs = current->startTimeNs;
716 }
717 }
718 if (isAssistant) {
719 isAssistantOnTop = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800720 if (isActiveAssistant) {
721 useActiveAssistantList = true;
722 } else if (!useActiveAssistantList) {
723 if (current->startTimeNs > latestAssistantStartNs) {
724 latestActiveAssistant = current;
725 latestAssistantStartNs = current->startTimeNs;
726 }
727 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800728 }
Eric Laurenta46bedb2018-12-07 18:01:26 -0800729 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800730 // Clients capturing for HOTWORD are not considered
731 // for latest active to avoid masking regular clients started before
732 if (!(current->attributes.source == AUDIO_SOURCE_HOTWORD
733 || ((isA11yOnTop || rttCallActive) && isAssistant))) {
734 if (isPrivacySensitive) {
Eric Laurentb809a752020-06-29 09:53:13 -0700735 // if audio mode is IN_COMMUNICATION, make sure the audio mode owner
736 // is marked latest sensitive active even if another app qualifies.
737 if (current->startTimeNs > latestSensitiveStartNs
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700738 || (isInCommunication && currentUid == mPhoneStateOwnerUid)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700739 if (!isInCommunication || latestSensitiveActiveOrComm == nullptr
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700740 || VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000741 latestSensitiveActiveOrComm->attributionSource.uid))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700742 != mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700743 latestSensitiveActiveOrComm = current;
744 latestSensitiveStartNs = current->startTimeNs;
745 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800746 }
747 isSensitiveActive = true;
748 } else {
749 if (current->startTimeNs > latestStartNs) {
750 latestActive = current;
751 latestStartNs = current->startTimeNs;
752 }
753 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800754 }
755 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700756 if (current->attributes.source != AUDIO_SOURCE_HOTWORD) {
757 onlyHotwordActive = false;
758 }
Eric Laurentb0eff0f2021-11-09 16:05:49 +0100759 if (currentUid == mPhoneStateOwnerUid &&
760 !isVirtualSource(current->attributes.source)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700761 isPhoneStateOwnerActive = true;
762 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800763 }
764
Eric Laurent1ff16a72019-03-14 18:35:04 -0700765 // if no active client with UI on Top, consider latest active as top
766 if (topActive == nullptr) {
767 topActive = latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800768 topStartNs = latestStartNs;
769 }
770 if (topSensitiveActive == nullptr) {
Eric Laurentb809a752020-06-29 09:53:13 -0700771 topSensitiveActive = latestSensitiveActiveOrComm;
Eric Laurentc21d5692020-02-25 10:24:36 -0800772 topSensitiveStartNs = latestSensitiveStartNs;
Eric Laurentb809a752020-06-29 09:53:13 -0700773 } else if (latestSensitiveActiveOrComm != nullptr) {
774 // if audio mode is IN_COMMUNICATION, favor audio mode owner over an app with
775 // foreground UI in case both are capturing with privacy sensitive flag.
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700776 uid_t latestActiveUid = VALUE_OR_FATAL(
Svet Ganov33761132021-05-13 22:51:08 +0000777 aidl2legacy_int32_t_uid_t(latestSensitiveActiveOrComm->attributionSource.uid));
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700778 if (isInCommunication && latestActiveUid == mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700779 topSensitiveActive = latestSensitiveActiveOrComm;
780 topSensitiveStartNs = latestSensitiveStartNs;
781 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800782 }
783
784 // If both privacy sensitive and regular capture are active:
785 // if the regular capture is privileged
786 // allow concurrency
787 // else
788 // favor the privacy sensitive case
789 if (topActive != nullptr && topSensitiveActive != nullptr
Ricardo Correa57a37692020-03-23 17:27:25 -0700790 && !topActive->canCaptureOutput) {
Eric Laurentc21d5692020-02-25 10:24:36 -0800791 topActive = nullptr;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800792 }
793
794 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
795 sp<AudioRecordClient> current = mAudioRecordClients[i];
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700796 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000797 current->attributionSource.uid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700798 if (!current->active) {
799 continue;
800 }
801
Eric Laurent4eb58f12018-12-07 16:41:02 -0800802 audio_source_t source = current->attributes.source;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700803 bool isTopOrLatestActive = topActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +0000804 current->attributionSource.uid == topActive->attributionSource.uid;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700805 bool isTopOrLatestSensitive = topSensitiveActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +0000806 current->attributionSource.uid == topSensitiveActive->attributionSource.uid;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800807 bool isTopOrLatestAssistant = latestActiveAssistant == nullptr ? false :
808 current->attributionSource.uid == latestActiveAssistant->attributionSource.uid;
Eric Laurentc21d5692020-02-25 10:24:36 -0800809
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000810 auto canCaptureIfInCallOrCommunication = [&](const auto &recordClient) REQUIRES(mLock) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700811 uid_t recordUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000812 recordClient->attributionSource.uid));
Ricardo Correa57a37692020-03-23 17:27:25 -0700813 bool canCaptureCall = recordClient->canCaptureOutput;
Eric Laurentb809a752020-06-29 09:53:13 -0700814 bool canCaptureCommunication = recordClient->canCaptureOutput
815 || !isPhoneStateOwnerActive
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700816 || recordUid == mPhoneStateOwnerUid;
Eric Laurentb809a752020-06-29 09:53:13 -0700817 return !(isInCall && !canCaptureCall)
818 && !(isInCommunication && !canCaptureCommunication);
Eric Laurentc21d5692020-02-25 10:24:36 -0800819 };
Eric Laurent1ff16a72019-03-14 18:35:04 -0700820
821 // By default allow capture if:
822 // The assistant is not on TOP
Eric Laurenta171e352019-05-07 13:04:45 -0700823 // AND is on TOP or latest started
Eric Laurent1ff16a72019-03-14 18:35:04 -0700824 // AND there is no active privacy sensitive capture or call
825 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
826 bool allowCapture = !isAssistantOnTop
Eric Laurentc21d5692020-02-25 10:24:36 -0800827 && (isTopOrLatestActive || isTopOrLatestSensitive)
828 && !(isSensitiveActive
Ricardo Correa57a37692020-03-23 17:27:25 -0700829 && !(isTopOrLatestSensitive || current->canCaptureOutput))
Eric Laurentc21d5692020-02-25 10:24:36 -0800830 && canCaptureIfInCallOrCommunication(current);
Eric Laurent2dc962b2019-03-01 08:25:25 -0800831
Eric Laurented726cc2021-07-01 14:26:41 +0200832 if (!current->hasOp()) {
833 // Never allow capture if app op is denied
834 allowCapture = false;
835 } else if (isVirtualSource(source)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700836 // Allow capture for virtual (remote submix, call audio TX or RX...) sources
837 allowCapture = true;
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800838 } else if (!useActiveAssistantList && mUidPolicy->isAssistantUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700839 // For assistant allow capture if:
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800840 // Active assistant list is not being used
841 // AND accessibility service is on TOP or a RTT call is active
Eric Laurent1ff16a72019-03-14 18:35:04 -0700842 // AND the source is VOICE_RECOGNITION or HOTWORD
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800843 // OR there is no active privacy sensitive capture or call
844 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
845 // AND is latest TOP assistant AND
846 // uses VOICE_RECOGNITION OR uses HOTWORD
847 // OR there is no TOP assistant and uses HOTWORD
Eric Laurent6ede98f2019-06-11 14:50:30 -0700848 if (isA11yOnTop || rttCallActive) {
Eric Laurent4eb58f12018-12-07 16:41:02 -0800849 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700850 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800851 }
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800852 } else if (!(isSensitiveActive && !current->canCaptureOutput)
853 && canCaptureIfInCallOrCommunication(current)) {
854 if (isTopOrLatestAssistant
855 && (source == AUDIO_SOURCE_VOICE_RECOGNITION
856 || source == AUDIO_SOURCE_HOTWORD)) {
857 allowCapture = true;
858 } else if (!isAssistantOnTop && (source == AUDIO_SOURCE_HOTWORD)) {
859 allowCapture = true;
860 }
861 }
862 } else if (useActiveAssistantList && mUidPolicy->isActiveAssistantUid(currentUid)) {
863 // For assistant on active list and on top allow capture if:
864 // An accessibility service is on TOP
865 // AND the source is VOICE_RECOGNITION or HOTWORD
866 // OR there is no active privacy sensitive capture or call
867 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
868 // AND uses VOICE_RECOGNITION OR uses HOTWORD
869 if (isA11yOnTop) {
870 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
871 allowCapture = true;
872 }
873 } else if (!(isSensitiveActive && !current->canCaptureOutput)
Eric Laurentc21d5692020-02-25 10:24:36 -0800874 && canCaptureIfInCallOrCommunication(current)) {
Oscar Azucenac2cdda32022-01-31 19:10:39 -0800875 if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) || (source == AUDIO_SOURCE_HOTWORD))
876 {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700877 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800878 }
879 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700880 } else if (mUidPolicy->isA11yUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700881 // For accessibility service allow capture if:
Eric Laurent47670c92019-08-28 16:59:05 -0700882 // The assistant is not on TOP
883 // AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -0700884 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent47670c92019-08-28 16:59:05 -0700885 // OR
886 // Is on TOP AND the source is VOICE_RECOGNITION or HOTWORD
887 if (!isAssistantOnTop
Ricardo Correa57a37692020-03-23 17:27:25 -0700888 && !(isSensitiveActive && !current->canCaptureOutput)
Eric Laurentc21d5692020-02-25 10:24:36 -0800889 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent47670c92019-08-28 16:59:05 -0700890 allowCapture = true;
891 }
Eric Laurent589171c2019-07-25 18:04:29 -0700892 if (isA11yOnTop) {
893 if (source == AUDIO_SOURCE_VOICE_RECOGNITION || source == AUDIO_SOURCE_HOTWORD) {
894 allowCapture = true;
895 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800896 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700897 } else if (source == AUDIO_SOURCE_HOTWORD) {
898 // For HOTWORD source allow capture when not on TOP if:
899 // All active clients are using HOTWORD source
900 // AND no call is active
901 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurentc21d5692020-02-25 10:24:36 -0800902 if (onlyHotwordActive
903 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent4e947da2019-10-17 15:24:06 -0700904 allowCapture = true;
905 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700906 } else if (mUidPolicy->isCurrentImeUid(currentUid)) {
Kohsuke Yatoha623a132020-03-24 20:10:26 -0700907 // For current InputMethodService allow capture if:
908 // A RTT call is active AND the source is VOICE_RECOGNITION
909 if (rttCallActive && source == AUDIO_SOURCE_VOICE_RECOGNITION) {
910 allowCapture = true;
911 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800912 }
Eric Laurent8c7ef892021-06-10 13:32:16 +0200913 setAppState_l(current,
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700914 allowCapture ? apmStatFromAmState(mUidPolicy->getUidState(currentUid)) :
Eric Laurent1ff16a72019-03-14 18:35:04 -0700915 APP_STATE_IDLE);
Eric Laurente8c8b432018-10-17 10:08:02 -0700916 }
917}
918
Michael Groovercfd28302018-12-11 19:16:46 -0800919void AudioPolicyService::silenceAllRecordings_l() {
920 for (size_t i = 0; i < mAudioRecordClients.size(); i++) {
921 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -0700922 if (!isVirtualSource(current->attributes.source)) {
Eric Laurent8c7ef892021-06-10 13:32:16 +0200923 setAppState_l(current, APP_STATE_IDLE);
Eric Laurent1ff16a72019-03-14 18:35:04 -0700924 }
Michael Groovercfd28302018-12-11 19:16:46 -0800925 }
926}
927
Eric Laurente8c8b432018-10-17 10:08:02 -0700928/* static */
929app_state_t AudioPolicyService::apmStatFromAmState(int amState) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700930
931 if (amState == ActivityManager::PROCESS_STATE_UNKNOWN) {
Eric Laurente8c8b432018-10-17 10:08:02 -0700932 return APP_STATE_IDLE;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700933 } else if (amState <= ActivityManager::PROCESS_STATE_TOP) {
934 // include persistent services
935 return APP_STATE_TOP;
Eric Laurente8c8b432018-10-17 10:08:02 -0700936 }
937 return APP_STATE_FOREGROUND;
938}
939
Eric Laurent4eb58f12018-12-07 16:41:02 -0800940/* static */
Eric Laurent2dc962b2019-03-01 08:25:25 -0800941bool AudioPolicyService::isVirtualSource(audio_source_t source)
Eric Laurent4eb58f12018-12-07 16:41:02 -0800942{
943 switch (source) {
944 case AUDIO_SOURCE_VOICE_UPLINK:
945 case AUDIO_SOURCE_VOICE_DOWNLINK:
946 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent2dc962b2019-03-01 08:25:25 -0800947 case AUDIO_SOURCE_REMOTE_SUBMIX:
948 case AUDIO_SOURCE_FM_TUNER:
Eric Laurent68eb2122020-04-30 17:40:57 -0700949 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent4eb58f12018-12-07 16:41:02 -0800950 return true;
951 default:
952 break;
953 }
954 return false;
955}
956
Eric Laurented726cc2021-07-01 14:26:41 +0200957/* static */
958bool AudioPolicyService::isAppOpSource(audio_source_t source)
959{
960 switch (source) {
961 case AUDIO_SOURCE_FM_TUNER:
962 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent637bd202021-09-22 11:17:11 +0200963 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurented726cc2021-07-01 14:26:41 +0200964 return false;
965 default:
966 break;
967 }
968 return true;
969}
970
Eric Laurent8c7ef892021-06-10 13:32:16 +0200971void AudioPolicyService::setAppState_l(sp<AudioRecordClient> client, app_state_t state)
Eric Laurente8c8b432018-10-17 10:08:02 -0700972{
973 AutoCallerClear acc;
974
975 if (mAudioPolicyManager) {
Eric Laurent8c7ef892021-06-10 13:32:16 +0200976 mAudioPolicyManager->setAppState(client->portId, state);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700977 }
978 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
979 if (af) {
Eric Laurentf32108e2018-10-04 17:22:04 -0700980 bool silenced = state == APP_STATE_IDLE;
Eric Laurent8c7ef892021-06-10 13:32:16 +0200981 if (client->silenced != silenced) {
982 if (client->active) {
983 if (silenced) {
984 finishRecording(client->attributionSource, client->attributes.source);
985 } else {
986 std::stringstream msg;
987 msg << "Audio recording un-silenced on session " << client->session;
988 if (!startRecording(client->attributionSource, String16(msg.str().c_str()),
989 client->attributes.source)) {
990 silenced = true;
991 }
992 }
993 }
994 af->setRecordSilenced(client->portId, silenced);
995 client->silenced = silenced;
996 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700997 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800998}
999
Glenn Kasten0f11b512014-01-31 16:18:54 -08001000status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001001{
Glenn Kasten44deb052012-02-05 18:09:08 -08001002 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001003 dumpPermissionDenial(fd);
1004 } else {
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001005 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001006 if (!locked) {
1007 String8 result(kDeadlockedString);
1008 write(fd, result.string(), result.size());
1009 }
1010
1011 dumpInternals(fd);
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001012
1013 String8 actPtr = String8::format("AudioCommandThread: %p\n", mAudioCommandThread.get());
1014 write(fd, actPtr.string(), actPtr.size());
Glenn Kasten9d1f02d2012-02-08 17:47:58 -08001015 if (mAudioCommandThread != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001016 mAudioCommandThread->dump(fd);
1017 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001018
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001019 String8 octPtr = String8::format("OutputCommandThread: %p\n", mOutputCommandThread.get());
1020 write(fd, octPtr.string(), octPtr.size());
1021 if (mOutputCommandThread != 0) {
1022 mOutputCommandThread->dump(fd);
1023 }
1024
Eric Laurentdce54a12014-03-10 12:19:46 -07001025 if (mAudioPolicyManager) {
1026 mAudioPolicyManager->dump(fd);
Mikhail Naganov1b22e542022-02-25 04:24:49 +00001027 } else {
1028 String8 apmPtr = String8::format("AudioPolicyManager: %p\n", mAudioPolicyManager);
1029 write(fd, apmPtr.string(), apmPtr.size());
Eric Laurentdce54a12014-03-10 12:19:46 -07001030 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001031
Kevin Rocard8be94972019-02-22 13:26:25 -08001032 mPackageManager.dump(fd);
1033
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001034 dumpReleaseLock(mLock, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001035 }
1036 return NO_ERROR;
1037}
1038
1039status_t AudioPolicyService::dumpPermissionDenial(int fd)
1040{
1041 const size_t SIZE = 256;
1042 char buffer[SIZE];
1043 String8 result;
1044 snprintf(buffer, SIZE, "Permission Denial: "
1045 "can't dump AudioPolicyService from pid=%d, uid=%d\n",
1046 IPCThreadState::self()->getCallingPid(),
1047 IPCThreadState::self()->getCallingUid());
1048 result.append(buffer);
1049 write(fd, result.string(), result.size());
1050 return NO_ERROR;
1051}
1052
1053status_t AudioPolicyService::onTransact(
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001054 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001055 // make sure transactions reserved to AudioFlinger do not come from other processes
1056 switch (code) {
1057 case TRANSACTION_startOutput:
1058 case TRANSACTION_stopOutput:
1059 case TRANSACTION_releaseOutput:
1060 case TRANSACTION_getInputForAttr:
1061 case TRANSACTION_startInput:
1062 case TRANSACTION_stopInput:
1063 case TRANSACTION_releaseInput:
1064 case TRANSACTION_getOutputForEffect:
1065 case TRANSACTION_registerEffect:
1066 case TRANSACTION_unregisterEffect:
1067 case TRANSACTION_setEffectEnabled:
1068 case TRANSACTION_getStrategyForStream:
1069 case TRANSACTION_getOutputForAttr:
1070 case TRANSACTION_moveEffectsToIo:
1071 ALOGW("%s: transaction %d received from PID %d",
1072 __func__, code, IPCThreadState::self()->getCallingPid());
1073 return INVALID_OPERATION;
1074 default:
1075 break;
1076 }
1077
1078 // make sure the following transactions come from system components
1079 switch (code) {
1080 case TRANSACTION_setDeviceConnectionState:
1081 case TRANSACTION_handleDeviceConfigChange:
1082 case TRANSACTION_setPhoneState:
1083//FIXME: Allow setForceUse calls from system apps until a better use case routing API is available
1084// case TRANSACTION_setForceUse:
1085 case TRANSACTION_initStreamVolume:
1086 case TRANSACTION_setStreamVolumeIndex:
1087 case TRANSACTION_setVolumeIndexForAttributes:
1088 case TRANSACTION_getStreamVolumeIndex:
1089 case TRANSACTION_getVolumeIndexForAttributes:
1090 case TRANSACTION_getMinVolumeIndexForAttributes:
1091 case TRANSACTION_getMaxVolumeIndexForAttributes:
1092 case TRANSACTION_isStreamActive:
1093 case TRANSACTION_isStreamActiveRemotely:
1094 case TRANSACTION_isSourceActive:
1095 case TRANSACTION_getDevicesForStream:
1096 case TRANSACTION_registerPolicyMixes:
1097 case TRANSACTION_setMasterMono:
1098 case TRANSACTION_getSurroundFormats:
Kriti Dang6537def2021-03-02 13:46:59 +01001099 case TRANSACTION_getReportedSurroundFormats:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001100 case TRANSACTION_setSurroundFormatEnabled:
Oscar Azucena829d90d2022-01-28 17:17:56 -08001101 case TRANSACTION_setAssistantServicesUids:
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001102 case TRANSACTION_setActiveAssistantServicesUids:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001103 case TRANSACTION_setA11yServicesUids:
1104 case TRANSACTION_setUidDeviceAffinities:
1105 case TRANSACTION_removeUidDeviceAffinities:
1106 case TRANSACTION_setUserIdDeviceAffinities:
1107 case TRANSACTION_removeUserIdDeviceAffinities:
Pattydd807582021-11-04 21:01:03 +08001108 case TRANSACTION_getHwOffloadFormatsSupportedForBluetoothMedia:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001109 case TRANSACTION_listAudioVolumeGroups:
1110 case TRANSACTION_getVolumeGroupFromAudioAttributes:
1111 case TRANSACTION_acquireSoundTriggerSession:
1112 case TRANSACTION_releaseSoundTriggerSession:
1113 case TRANSACTION_setRttEnabled:
1114 case TRANSACTION_isCallScreenModeSupported:
1115 case TRANSACTION_setDevicesRoleForStrategy:
1116 case TRANSACTION_setSupportedSystemUsages:
1117 case TRANSACTION_removeDevicesRoleForStrategy:
1118 case TRANSACTION_getDevicesForRoleAndStrategy:
1119 case TRANSACTION_getDevicesForAttributes:
1120 case TRANSACTION_setAllowedCapturePolicy:
1121 case TRANSACTION_onNewAudioModulesAvailable:
1122 case TRANSACTION_setCurrentImeUid:
1123 case TRANSACTION_registerSoundTriggerCaptureStateListener:
1124 case TRANSACTION_setDevicesRoleForCapturePreset:
1125 case TRANSACTION_addDevicesRoleForCapturePreset:
1126 case TRANSACTION_removeDevicesRoleForCapturePreset:
1127 case TRANSACTION_clearDevicesRoleForCapturePreset:
Eric Laurent81dd0f52021-07-05 11:54:40 +02001128 case TRANSACTION_getDevicesForRoleAndCapturePreset:
1129 case TRANSACTION_getSpatializer: {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001130 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
1131 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
1132 __func__, code, IPCThreadState::self()->getCallingPid(),
1133 IPCThreadState::self()->getCallingUid());
1134 return INVALID_OPERATION;
1135 }
1136 } break;
1137 default:
1138 break;
1139 }
1140
1141 std::string tag("IAudioPolicyService command " + std::to_string(code));
1142 TimeCheck check(tag.c_str());
1143
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001144 switch (code) {
1145 case SHELL_COMMAND_TRANSACTION: {
1146 int in = data.readFileDescriptor();
1147 int out = data.readFileDescriptor();
1148 int err = data.readFileDescriptor();
1149 int argc = data.readInt32();
1150 Vector<String16> args;
1151 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
1152 args.add(data.readString16());
1153 }
1154 sp<IBinder> unusedCallback;
1155 sp<IResultReceiver> resultReceiver;
1156 status_t status;
1157 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
1158 return status;
1159 }
1160 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
1161 return status;
1162 }
1163 status = shellCommand(in, out, err, args);
1164 if (resultReceiver != nullptr) {
1165 resultReceiver->send(status);
1166 }
1167 return NO_ERROR;
1168 }
1169 }
1170
Mathias Agopian65ab4712010-07-14 17:59:35 -07001171 return BnAudioPolicyService::onTransact(code, data, reply, flags);
1172}
1173
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001174// ------------------- Shell command implementation -------------------
1175
1176// NOTE: This is a remote API - make sure all args are validated
1177status_t AudioPolicyService::shellCommand(int in, int out, int err, Vector<String16>& args) {
1178 if (!checkCallingPermission(sManageAudioPolicyPermission, nullptr, nullptr)) {
1179 return PERMISSION_DENIED;
1180 }
1181 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
1182 return BAD_VALUE;
1183 }
jovanakbe066e12019-09-02 11:54:39 -07001184 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001185 return handleSetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001186 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001187 return handleResetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001188 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001189 return handleGetUidState(args, out, err);
Eric Laurent269acb42021-04-23 16:53:22 +02001190 } else if (args.size() >= 1 && args[0] == String16("purge_permission-cache")) {
1191 purgePermissionCache();
1192 return NO_ERROR;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001193 } else if (args.size() == 1 && args[0] == String16("help")) {
1194 printHelp(out);
1195 return NO_ERROR;
1196 }
1197 printHelp(err);
1198 return BAD_VALUE;
1199}
1200
jovanakbe066e12019-09-02 11:54:39 -07001201static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1202 if (userId < 0) {
1203 ALOGE("Invalid user: %d", userId);
1204 dprintf(err, "Invalid user: %d\n", userId);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001205 return BAD_VALUE;
1206 }
jovanakbe066e12019-09-02 11:54:39 -07001207
1208 PermissionController pc;
1209 uid = pc.getPackageUid(packageName, 0);
1210 if (uid <= 0) {
1211 ALOGE("Unknown package: '%s'", String8(packageName).string());
1212 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1213 return BAD_VALUE;
1214 }
1215
1216 uid = multiuser_get_uid(userId, uid);
1217 return NO_ERROR;
1218}
1219
1220status_t AudioPolicyService::handleSetUidState(Vector<String16>& args, int err) {
1221 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
1222 if (!(args.size() == 3 || args.size() == 5)) {
1223 printHelp(err);
1224 return BAD_VALUE;
1225 }
1226
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001227 bool active = false;
1228 if (args[2] == String16("active")) {
1229 active = true;
1230 } else if ((args[2] != String16("idle"))) {
1231 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
1232 return BAD_VALUE;
1233 }
jovanakbe066e12019-09-02 11:54:39 -07001234
1235 int userId = 0;
1236 if (args.size() >= 5 && args[3] == String16("--user")) {
1237 userId = atoi(String8(args[4]));
1238 }
1239
1240 uid_t uid;
1241 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1242 return BAD_VALUE;
1243 }
1244
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001245 sp<UidPolicy> uidPolicy;
1246 {
1247 Mutex::Autolock _l(mLock);
1248 uidPolicy = mUidPolicy;
1249 }
1250 if (uidPolicy) {
1251 uidPolicy->addOverrideUid(uid, active);
1252 return NO_ERROR;
1253 }
1254 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001255}
1256
1257status_t AudioPolicyService::handleResetUidState(Vector<String16>& args, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001258 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1259 if (!(args.size() == 2 || args.size() == 4)) {
1260 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001261 return BAD_VALUE;
1262 }
jovanakbe066e12019-09-02 11:54:39 -07001263
1264 int userId = 0;
1265 if (args.size() >= 4 && args[2] == String16("--user")) {
1266 userId = atoi(String8(args[3]));
1267 }
1268
1269 uid_t uid;
1270 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1271 return BAD_VALUE;
1272 }
1273
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001274 sp<UidPolicy> uidPolicy;
1275 {
1276 Mutex::Autolock _l(mLock);
1277 uidPolicy = mUidPolicy;
1278 }
1279 if (uidPolicy) {
1280 uidPolicy->removeOverrideUid(uid);
1281 return NO_ERROR;
1282 }
1283 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001284}
1285
1286status_t AudioPolicyService::handleGetUidState(Vector<String16>& args, int out, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001287 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1288 if (!(args.size() == 2 || args.size() == 4)) {
1289 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001290 return BAD_VALUE;
1291 }
jovanakbe066e12019-09-02 11:54:39 -07001292
1293 int userId = 0;
1294 if (args.size() >= 4 && args[2] == String16("--user")) {
1295 userId = atoi(String8(args[3]));
1296 }
1297
1298 uid_t uid;
1299 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1300 return BAD_VALUE;
1301 }
1302
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001303 sp<UidPolicy> uidPolicy;
1304 {
1305 Mutex::Autolock _l(mLock);
1306 uidPolicy = mUidPolicy;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001307 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001308 if (uidPolicy) {
1309 return dprintf(out, uidPolicy->isUidActive(uid) ? "active\n" : "idle\n");
1310 }
1311 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001312}
1313
1314status_t AudioPolicyService::printHelp(int out) {
1315 return dprintf(out, "Audio policy service commands:\n"
jovanakbe066e12019-09-02 11:54:39 -07001316 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
1317 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
1318 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001319 " help print this message\n");
1320}
1321
1322// ----------- AudioPolicyService::UidPolicy implementation ----------
1323
1324void AudioPolicyService::UidPolicy::registerSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001325 status_t res = mAm.linkToDeath(this);
1326 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001327 | ActivityManager::UID_OBSERVER_IDLE
Eric Laurente8c8b432018-10-17 10:08:02 -07001328 | ActivityManager::UID_OBSERVER_ACTIVE
1329 | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001330 ActivityManager::PROCESS_STATE_UNKNOWN,
1331 String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001332 if (!res) {
1333 Mutex::Autolock _l(mLock);
1334 mObserverRegistered = true;
1335 } else {
1336 ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001337
Steven Moreland2f348142019-07-02 15:59:07 -07001338 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001339 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001340}
1341
1342void AudioPolicyService::UidPolicy::unregisterSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001343 mAm.unlinkToDeath(this);
1344 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001345 Mutex::Autolock _l(mLock);
1346 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001347}
1348
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001349void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
1350 Mutex::Autolock _l(mLock);
1351 mCachedUids.clear();
1352 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001353}
1354
Eric Laurente8c8b432018-10-17 10:08:02 -07001355void AudioPolicyService::UidPolicy::checkRegistered() {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001356 bool needToReregister = false;
1357 {
1358 Mutex::Autolock _l(mLock);
1359 needToReregister = !mObserverRegistered;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001360 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001361 if (needToReregister) {
1362 // Looks like ActivityManager has died previously, attempt to re-register.
1363 registerSelf();
1364 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001365}
1366
1367bool AudioPolicyService::UidPolicy::isUidActive(uid_t uid) {
1368 if (isServiceUid(uid)) return true;
1369 checkRegistered();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001370 {
1371 Mutex::Autolock _l(mLock);
1372 auto overrideIter = mOverrideUids.find(uid);
1373 if (overrideIter != mOverrideUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001374 return overrideIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001375 }
1376 // In an absense of the ActivityManager, assume everything to be active.
1377 if (!mObserverRegistered) return true;
1378 auto cacheIter = mCachedUids.find(uid);
Mikhail Naganoveba668a2018-04-05 08:13:15 -07001379 if (cacheIter != mCachedUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001380 return cacheIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001381 }
1382 }
1383 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001384 bool active = am.isUidActive(uid, String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001385 {
1386 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001387 mCachedUids.insert(std::pair<uid_t,
1388 std::pair<bool, int>>(uid, std::pair<bool, int>(active,
1389 ActivityManager::PROCESS_STATE_UNKNOWN)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001390 }
1391 return active;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001392}
1393
Eric Laurente8c8b432018-10-17 10:08:02 -07001394int AudioPolicyService::UidPolicy::getUidState(uid_t uid) {
1395 if (isServiceUid(uid)) {
1396 return ActivityManager::PROCESS_STATE_TOP;
1397 }
1398 checkRegistered();
1399 {
1400 Mutex::Autolock _l(mLock);
1401 auto overrideIter = mOverrideUids.find(uid);
1402 if (overrideIter != mOverrideUids.end()) {
1403 if (overrideIter->second.first) {
1404 if (overrideIter->second.second != ActivityManager::PROCESS_STATE_UNKNOWN) {
1405 return overrideIter->second.second;
1406 } else {
1407 auto cacheIter = mCachedUids.find(uid);
1408 if (cacheIter != mCachedUids.end()) {
1409 return cacheIter->second.second;
1410 }
1411 }
1412 }
1413 return ActivityManager::PROCESS_STATE_UNKNOWN;
1414 }
1415 // In an absense of the ActivityManager, assume everything to be active.
1416 if (!mObserverRegistered) {
1417 return ActivityManager::PROCESS_STATE_TOP;
1418 }
1419 auto cacheIter = mCachedUids.find(uid);
1420 if (cacheIter != mCachedUids.end()) {
1421 if (cacheIter->second.first) {
1422 return cacheIter->second.second;
1423 } else {
1424 return ActivityManager::PROCESS_STATE_UNKNOWN;
1425 }
1426 }
1427 }
1428 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001429 bool active = am.isUidActive(uid, String16("audioserver"));
Eric Laurente8c8b432018-10-17 10:08:02 -07001430 int state = ActivityManager::PROCESS_STATE_UNKNOWN;
1431 if (active) {
1432 state = am.getUidProcessState(uid, String16("audioserver"));
1433 }
1434 {
1435 Mutex::Autolock _l(mLock);
1436 mCachedUids.insert(std::pair<uid_t,
1437 std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
1438 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001439
Eric Laurente8c8b432018-10-17 10:08:02 -07001440 return state;
1441}
1442
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001443void AudioPolicyService::UidPolicy::onUidActive(uid_t uid) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001444 updateUid(&mCachedUids, uid, true, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001445}
1446
1447void AudioPolicyService::UidPolicy::onUidGone(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001448 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, false);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001449}
1450
1451void AudioPolicyService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001452 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001453}
1454
Eric Laurente8c8b432018-10-17 10:08:02 -07001455void AudioPolicyService::UidPolicy::onUidStateChanged(uid_t uid,
1456 int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07001457 int64_t procStateSeq __unused,
1458 int32_t capability __unused) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001459 if (procState != ActivityManager::PROCESS_STATE_UNKNOWN) {
1460 updateUid(&mCachedUids, uid, true, procState, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001461 }
1462}
1463
1464void AudioPolicyService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001465 updateUid(&mOverrideUids, uid, active, ActivityManager::PROCESS_STATE_UNKNOWN, insert);
1466}
1467
1468void AudioPolicyService::UidPolicy::notifyService() {
1469 sp<AudioPolicyService> service = mService.promote();
1470 if (service != nullptr) {
1471 service->updateUidStates();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001472 }
1473}
1474
Eric Laurente8c8b432018-10-17 10:08:02 -07001475void AudioPolicyService::UidPolicy::updateUid(std::unordered_map<uid_t,
1476 std::pair<bool, int>> *uids,
1477 uid_t uid,
1478 bool active,
1479 int state,
1480 bool insert) {
1481 if (isServiceUid(uid)) {
1482 return;
1483 }
1484 bool wasActive = isUidActive(uid);
1485 int previousState = getUidState(uid);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001486 {
1487 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001488 updateUidLocked(uids, uid, active, state, insert);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001489 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001490 if (wasActive != isUidActive(uid) || state != previousState) {
1491 notifyService();
1492 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001493}
1494
Eric Laurente8c8b432018-10-17 10:08:02 -07001495void AudioPolicyService::UidPolicy::updateUidLocked(std::unordered_map<uid_t,
1496 std::pair<bool, int>> *uids,
1497 uid_t uid,
1498 bool active,
1499 int state,
1500 bool insert) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001501 auto it = uids->find(uid);
1502 if (it != uids->end()) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001503 if (insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001504 if (state == ActivityManager::PROCESS_STATE_UNKNOWN) {
1505 it->second.first = active;
1506 }
1507 if (it->second.first) {
1508 it->second.second = state;
1509 } else {
1510 it->second.second = ActivityManager::PROCESS_STATE_UNKNOWN;
1511 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001512 } else {
1513 uids->erase(it);
1514 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001515 } else if (insert && (state == ActivityManager::PROCESS_STATE_UNKNOWN)) {
1516 uids->insert(std::pair<uid_t, std::pair<bool, int>>(uid,
1517 std::pair<bool, int>(active, state)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001518 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001519}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001520
Eric Laurent4eb58f12018-12-07 16:41:02 -08001521bool AudioPolicyService::UidPolicy::isA11yOnTop() {
1522 for (const auto &uid : mCachedUids) {
Eric Laurent47670c92019-08-28 16:59:05 -07001523 if (!isA11yUid(uid.first)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001524 continue;
1525 }
Amith Yamasanibcbb3002019-01-23 13:53:33 -08001526 if (uid.second.second >= ActivityManager::PROCESS_STATE_TOP
1527 && uid.second.second <= ActivityManager::PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001528 return true;
1529 }
1530 }
1531 return false;
1532}
1533
Eric Laurentb78763e2018-10-17 10:08:02 -07001534bool AudioPolicyService::UidPolicy::isA11yUid(uid_t uid)
1535{
1536 std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid);
1537 return it != mA11yUids.end();
1538}
1539
Oscar Azucena829d90d2022-01-28 17:17:56 -08001540void AudioPolicyService::UidPolicy::setAssistantUids(const std::vector<uid_t>& uids) {
1541 mAssistantUids.clear();
1542 mAssistantUids = uids;
1543}
1544
1545bool AudioPolicyService::UidPolicy::isAssistantUid(uid_t uid)
1546{
1547 std::vector<uid_t>::iterator it = find(mAssistantUids.begin(), mAssistantUids.end(), uid);
1548 return it != mAssistantUids.end();
1549}
1550
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001551void AudioPolicyService::UidPolicy::setActiveAssistantUids(const std::vector<uid_t>& activeUids) {
1552 mActiveAssistantUids = activeUids;
1553}
1554
1555bool AudioPolicyService::UidPolicy::isActiveAssistantUid(uid_t uid)
1556{
1557 std::vector<uid_t>::iterator it = find(mActiveAssistantUids.begin(),
1558 mActiveAssistantUids.end(), uid);
1559 return it != mActiveAssistantUids.end();
1560}
1561
Oscar Azucena829d90d2022-01-28 17:17:56 -08001562void AudioPolicyService::UidPolicy::dumpInternals(int fd) {
1563 const size_t SIZE = 256;
1564 char buffer[SIZE];
1565 String8 result;
1566 auto appendUidsToResult = [&](const char* title, const std::vector<uid_t> &uids) {
1567 snprintf(buffer, SIZE, "\t%s: \n", title);
1568 result.append(buffer);
1569 int counter = 0;
1570 if (uids.empty()) {
1571 snprintf(buffer, SIZE, "\t\tNo UIDs present.\n");
1572 result.append(buffer);
1573 return;
1574 }
1575 for (const auto &uid : uids) {
1576 snprintf(buffer, SIZE, "\t\tUID[%d]=%d\n", counter++, uid);
1577 result.append(buffer);
1578 }
1579 };
1580
1581 snprintf(buffer, SIZE, "UID Policy:\n");
1582 result.append(buffer);
1583 snprintf(buffer, SIZE, "\tmObserverRegistered=%s\n",(mObserverRegistered ? "True":"False"));
1584 result.append(buffer);
1585
1586 appendUidsToResult("Assistants UIDs", mAssistantUids);
Oscar Azucenac2cdda32022-01-31 19:10:39 -08001587 appendUidsToResult("Active Assistants UIDs", mActiveAssistantUids);
Oscar Azucena829d90d2022-01-28 17:17:56 -08001588
1589 appendUidsToResult("Accessibility UIDs", mA11yUids);
1590
1591 snprintf(buffer, SIZE, "\tInput Method Service UID=%d\n", mCurrentImeUid);
1592 result.append(buffer);
1593
1594 snprintf(buffer, SIZE, "\tIs RTT Enabled: %s\n", (mRttEnabled ? "True":"False"));
1595 result.append(buffer);
1596
1597 write(fd, result.string(), result.size());
1598}
1599
Michael Groovercfd28302018-12-11 19:16:46 -08001600// ----------- AudioPolicyService::SensorPrivacyService implementation ----------
1601void AudioPolicyService::SensorPrivacyPolicy::registerSelf() {
1602 SensorPrivacyManager spm;
1603 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1604 spm.addSensorPrivacyListener(this);
1605}
1606
1607void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
1608 SensorPrivacyManager spm;
1609 spm.removeSensorPrivacyListener(this);
1610}
1611
1612bool AudioPolicyService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1613 return mSensorPrivacyEnabled;
1614}
1615
Evan Seversond8dc6832022-01-27 10:47:03 -08001616binder::Status AudioPolicyService::SensorPrivacyPolicy::onSensorPrivacyChanged(
1617 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Groovercfd28302018-12-11 19:16:46 -08001618 mSensorPrivacyEnabled = enabled;
1619 sp<AudioPolicyService> service = mService.promote();
1620 if (service != nullptr) {
1621 service->updateUidStates();
1622 }
1623 return binder::Status::ok();
1624}
1625
Eric Laurented726cc2021-07-01 14:26:41 +02001626// ----------- AudioPolicyService::OpRecordAudioMonitor implementation ----------
1627
1628// static
1629sp<AudioPolicyService::OpRecordAudioMonitor>
1630AudioPolicyService::OpRecordAudioMonitor::createIfNeeded(
1631 const AttributionSourceState& attributionSource, const audio_attributes_t& attr,
1632 wp<AudioCommandThread> commandThread)
1633{
Eric Laurent987ce102021-07-05 12:11:51 +02001634 if (isAudioServerOrRootUid(attributionSource.uid)) {
1635 ALOGV("not silencing record for audio or root source %s",
Eric Laurented726cc2021-07-01 14:26:41 +02001636 attributionSource.toString().c_str());
1637 return nullptr;
1638 }
1639
1640 if (!AudioPolicyService::isAppOpSource(attr.source)) {
1641 ALOGD("not monitoring app op for uid %d and source %d",
1642 attributionSource.uid, attr.source);
1643 return nullptr;
1644 }
1645
1646 if (!attributionSource.packageName.has_value()
1647 || attributionSource.packageName.value().size() == 0) {
1648 return nullptr;
1649 }
1650 return new OpRecordAudioMonitor(attributionSource, getOpForSource(attr.source), commandThread);
1651}
1652
1653AudioPolicyService::OpRecordAudioMonitor::OpRecordAudioMonitor(
1654 const AttributionSourceState& attributionSource, int32_t appOp,
1655 wp<AudioCommandThread> commandThread) :
1656 mHasOp(true), mAttributionSource(attributionSource), mAppOp(appOp),
1657 mCommandThread(commandThread)
1658{
1659}
1660
1661AudioPolicyService::OpRecordAudioMonitor::~OpRecordAudioMonitor()
1662{
1663 if (mOpCallback != 0) {
1664 mAppOpsManager.stopWatchingMode(mOpCallback);
1665 }
1666 mOpCallback.clear();
1667}
1668
1669void AudioPolicyService::OpRecordAudioMonitor::onFirstRef()
1670{
1671 checkOp();
1672 mOpCallback = new RecordAudioOpCallback(this);
1673 ALOGV("start watching op %d for %s", mAppOp, mAttributionSource.toString().c_str());
1674 // TODO: We need to always watch AppOpsManager::OP_RECORD_AUDIO too
1675 // since it controls the mic permission for legacy apps.
1676 mAppOpsManager.startWatchingMode(mAppOp, VALUE_OR_FATAL(aidl2legacy_string_view_String16(
1677 mAttributionSource.packageName.value_or(""))),
1678 mOpCallback);
1679}
1680
1681bool AudioPolicyService::OpRecordAudioMonitor::hasOp() const {
1682 return mHasOp.load();
1683}
1684
1685// Called by RecordAudioOpCallback when the app op corresponding to this OpRecordAudioMonitor
1686// is updated in AppOp callback and in onFirstRef()
1687// Note this method is never called (and never to be) for audio server / root track
1688// due to the UID in createIfNeeded(). As a result for those record track, it's:
1689// - not called from constructor,
1690// - not called from RecordAudioOpCallback because the callback is not installed in this case
1691void AudioPolicyService::OpRecordAudioMonitor::checkOp(bool updateUidStates)
1692{
1693 // TODO: We need to always check AppOpsManager::OP_RECORD_AUDIO too
1694 // since it controls the mic permission for legacy apps.
1695 const int32_t mode = mAppOpsManager.checkOp(mAppOp,
1696 mAttributionSource.uid, VALUE_OR_FATAL(aidl2legacy_string_view_String16(
1697 mAttributionSource.packageName.value_or(""))));
1698 const bool hasIt = (mode == AppOpsManager::MODE_ALLOWED);
1699 // verbose logging only log when appOp changed
1700 ALOGI_IF(hasIt != mHasOp.load(),
1701 "App op %d missing, %ssilencing record %s",
1702 mAppOp, hasIt ? "un" : "", mAttributionSource.toString().c_str());
1703 mHasOp.store(hasIt);
1704
1705 if (updateUidStates) {
1706 sp<AudioCommandThread> commandThread = mCommandThread.promote();
1707 if (commandThread != nullptr) {
1708 commandThread->updateUidStatesCommand();
1709 }
1710 }
1711}
1712
1713AudioPolicyService::OpRecordAudioMonitor::RecordAudioOpCallback::RecordAudioOpCallback(
1714 const wp<OpRecordAudioMonitor>& monitor) : mMonitor(monitor)
1715{ }
1716
1717void AudioPolicyService::OpRecordAudioMonitor::RecordAudioOpCallback::opChanged(int32_t op,
1718 const String16& packageName __unused) {
1719 sp<OpRecordAudioMonitor> monitor = mMonitor.promote();
1720 if (monitor != NULL) {
1721 if (op != monitor->getOp()) {
1722 return;
1723 }
1724 monitor->checkOp(true);
1725 }
1726}
1727
1728
Mathias Agopian65ab4712010-07-14 17:59:35 -07001729// ----------- AudioPolicyService::AudioCommandThread implementation ----------
1730
Eric Laurentbfb1b832013-01-07 09:53:42 -08001731AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
1732 const wp<AudioPolicyService>& service)
1733 : Thread(false), mName(name), mService(service)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001734{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001735}
1736
1737
1738AudioPolicyService::AudioCommandThread::~AudioCommandThread()
1739{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001740 if (!mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001741 release_wake_lock(mName.string());
1742 }
1743 mAudioCommands.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001744}
1745
1746void AudioPolicyService::AudioCommandThread::onFirstRef()
1747{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001748 run(mName.string(), ANDROID_PRIORITY_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001749}
1750
1751bool AudioPolicyService::AudioCommandThread::threadLoop()
1752{
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001753 nsecs_t waitTime = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001754
1755 mLock.lock();
1756 while (!exitPending())
1757 {
Eric Laurent59a89232014-06-08 14:14:17 -07001758 sp<AudioPolicyService> svc;
1759 while (!mAudioCommands.isEmpty() && !exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001760 nsecs_t curTime = systemTime();
1761 // commands are sorted by increasing time stamp: execute them from index 0 and up
1762 if (mAudioCommands[0]->mTime <= curTime) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001763 sp<AudioCommand> command = mAudioCommands[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001764 mAudioCommands.removeAt(0);
Eric Laurent0ede8922014-05-09 18:04:42 -07001765 mLastCommand = command;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001766
1767 switch (command->mCommand) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001768 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001769 VolumeData *data = (VolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001770 ALOGV("AudioCommandThread() processing set volume stream %d, \
Eric Laurentde070132010-07-13 04:45:46 -07001771 volume %f, output %d", data->mStream, data->mVolume, data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001772 mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07001773 command->mStatus = AudioSystem::setStreamVolume(data->mStream,
1774 data->mVolume,
1775 data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001776 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001777 }break;
1778 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001779 ParametersData *data = (ParametersData *)command->mParam.get();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001780 ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
1781 data->mKeyValuePairs.string(), data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001782 mLock.unlock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001783 command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
Andy Hungfe726a62018-09-27 15:17:25 -07001784 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001785 }break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001786 case SET_VOICE_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001787 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001788 ALOGV("AudioCommandThread() processing set voice volume volume %f",
Eric Laurentde070132010-07-13 04:45:46 -07001789 data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001790 mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001791 command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001792 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001793 }break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001794 case STOP_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001795 StopOutputData *data = (StopOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001796 ALOGV("AudioCommandThread() processing stop output portId %d",
1797 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001798 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001799 if (svc == 0) {
1800 break;
1801 }
1802 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001803 svc->doStopOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001804 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001805 }break;
1806 case RELEASE_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001807 ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001808 ALOGV("AudioCommandThread() processing release 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->doReleaseOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001816 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001817 }break;
Eric Laurent951f4552014-05-20 10:48:17 -07001818 case CREATE_AUDIO_PATCH: {
1819 CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
1820 ALOGV("AudioCommandThread() processing create audio patch");
1821 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1822 if (af == 0) {
1823 command->mStatus = PERMISSION_DENIED;
1824 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001825 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001826 command->mStatus = af->createAudioPatch(&data->mPatch, &data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001827 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001828 }
1829 } break;
1830 case RELEASE_AUDIO_PATCH: {
1831 ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
1832 ALOGV("AudioCommandThread() processing release 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->releaseAudioPatch(data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001839 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001840 }
1841 } break;
Eric Laurentb52c1522014-05-20 11:27:36 -07001842 case UPDATE_AUDIOPORT_LIST: {
1843 ALOGV("AudioCommandThread() processing update audio port list");
Eric Laurent59a89232014-06-08 14:14:17 -07001844 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001845 if (svc == 0) {
1846 break;
1847 }
1848 mLock.unlock();
1849 svc->doOnAudioPortListUpdate();
1850 mLock.lock();
1851 }break;
1852 case UPDATE_AUDIOPATCH_LIST: {
1853 ALOGV("AudioCommandThread() processing update audio patch list");
Eric Laurent59a89232014-06-08 14:14:17 -07001854 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001855 if (svc == 0) {
1856 break;
1857 }
1858 mLock.unlock();
1859 svc->doOnAudioPatchListUpdate();
1860 mLock.lock();
1861 }break;
François Gaffiecfe17322018-11-07 13:41:29 +01001862 case CHANGED_AUDIOVOLUMEGROUP: {
1863 AudioVolumeGroupData *data =
1864 static_cast<AudioVolumeGroupData *>(command->mParam.get());
1865 ALOGV("AudioCommandThread() processing update audio volume group");
1866 svc = mService.promote();
1867 if (svc == 0) {
1868 break;
1869 }
1870 mLock.unlock();
1871 svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
1872 mLock.lock();
1873 }break;
Eric Laurente1715a42014-05-20 11:30:42 -07001874 case SET_AUDIOPORT_CONFIG: {
1875 SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
1876 ALOGV("AudioCommandThread() processing set port config");
1877 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1878 if (af == 0) {
1879 command->mStatus = PERMISSION_DENIED;
1880 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001881 mLock.unlock();
Eric Laurente1715a42014-05-20 11:30:42 -07001882 command->mStatus = af->setAudioPortConfig(&data->mConfig);
Andy Hungfe726a62018-09-27 15:17:25 -07001883 mLock.lock();
Eric Laurente1715a42014-05-20 11:30:42 -07001884 }
1885 } break;
Jean-Michel Trivide801052015-04-14 19:10:14 -07001886 case DYN_POLICY_MIX_STATE_UPDATE: {
1887 DynPolicyMixStateUpdateData *data =
1888 (DynPolicyMixStateUpdateData *)command->mParam.get();
Jean-Michel Trivide801052015-04-14 19:10:14 -07001889 ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
1890 data->mRegId.string(), data->mState);
1891 svc = mService.promote();
1892 if (svc == 0) {
1893 break;
1894 }
1895 mLock.unlock();
1896 svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
1897 mLock.lock();
1898 } break;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001899 case RECORDING_CONFIGURATION_UPDATE: {
1900 RecordingConfigurationUpdateData *data =
1901 (RecordingConfigurationUpdateData *)command->mParam.get();
1902 ALOGV("AudioCommandThread() processing recording configuration update");
1903 svc = mService.promote();
1904 if (svc == 0) {
1905 break;
1906 }
1907 mLock.unlock();
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001908 svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -08001909 &data->mClientConfig, data->mClientEffects,
1910 &data->mDeviceConfig, data->mEffects,
1911 data->mPatchHandle, data->mSource);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001912 mLock.lock();
1913 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001914 case SET_EFFECT_SUSPENDED: {
1915 SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
1916 ALOGV("AudioCommandThread() processing set effect suspended");
1917 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1918 if (af != 0) {
1919 mLock.unlock();
1920 af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
1921 mLock.lock();
1922 }
1923 } break;
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001924 case AUDIO_MODULES_UPDATE: {
1925 ALOGV("AudioCommandThread() processing audio modules update");
1926 svc = mService.promote();
1927 if (svc == 0) {
1928 break;
1929 }
1930 mLock.unlock();
1931 svc->doOnNewAudioModulesAvailable();
1932 mLock.lock();
1933 } break;
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07001934 case ROUTING_UPDATED: {
1935 ALOGV("AudioCommandThread() processing routing update");
1936 svc = mService.promote();
1937 if (svc == 0) {
1938 break;
1939 }
1940 mLock.unlock();
1941 svc->doOnRoutingUpdated();
1942 mLock.lock();
1943 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001944
Eric Laurented726cc2021-07-01 14:26:41 +02001945 case UPDATE_UID_STATES: {
1946 ALOGV("AudioCommandThread() processing updateUID states");
1947 svc = mService.promote();
1948 if (svc == 0) {
1949 break;
1950 }
1951 mLock.unlock();
1952 svc->updateUidStates();
1953 mLock.lock();
1954 } break;
1955
Eric Laurent81dd0f52021-07-05 11:54:40 +02001956 case CHECK_SPATIALIZER: {
1957 ALOGV("AudioCommandThread() processing updateUID states");
1958 svc = mService.promote();
1959 if (svc == 0) {
1960 break;
1961 }
1962 mLock.unlock();
1963 svc->doOnCheckSpatializer();
1964 mLock.lock();
1965 } break;
1966
Mathias Agopian65ab4712010-07-14 17:59:35 -07001967 default:
Steve Block5ff1dd52012-01-05 23:22:43 +00001968 ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001969 }
Eric Laurent0ede8922014-05-09 18:04:42 -07001970 {
1971 Mutex::Autolock _l(command->mLock);
1972 if (command->mWaitStatus) {
1973 command->mWaitStatus = false;
1974 command->mCond.signal();
1975 }
1976 }
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001977 waitTime = -1;
Zach Janga754b4f2015-10-27 01:29:34 +00001978 // release mLock before releasing strong reference on the service as
1979 // AudioPolicyService destructor calls AudioCommandThread::exit() which
1980 // acquires mLock.
1981 mLock.unlock();
1982 svc.clear();
1983 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001984 } else {
1985 waitTime = mAudioCommands[0]->mTime - curTime;
1986 break;
1987 }
1988 }
Zach Janga754b4f2015-10-27 01:29:34 +00001989
1990 // release delayed commands wake lock if the queue is empty
1991 if (mAudioCommands.isEmpty()) {
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07001992 release_wake_lock(mName.string());
Zach Janga754b4f2015-10-27 01:29:34 +00001993 }
1994
1995 // At this stage we have either an empty command queue or the first command in the queue
1996 // has a finite delay. So unless we are exiting it is safe to wait.
1997 if (!exitPending()) {
Eric Laurent59a89232014-06-08 14:14:17 -07001998 ALOGV("AudioCommandThread() going to sleep");
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001999 if (waitTime == -1) {
2000 mWaitWorkCV.wait(mLock);
2001 } else {
2002 mWaitWorkCV.waitRelative(mLock, waitTime);
2003 }
Eric Laurent59a89232014-06-08 14:14:17 -07002004 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002005 }
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07002006 // release delayed commands wake lock before quitting
2007 if (!mAudioCommands.isEmpty()) {
2008 release_wake_lock(mName.string());
2009 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002010 mLock.unlock();
2011 return false;
2012}
2013
2014status_t AudioPolicyService::AudioCommandThread::dump(int fd)
2015{
2016 const size_t SIZE = 256;
2017 char buffer[SIZE];
2018 String8 result;
2019
Mikhail Naganov12b716c2020-04-30 22:37:43 +00002020 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002021 if (!locked) {
2022 String8 result2(kCmdDeadlockedString);
2023 write(fd, result2.string(), result2.size());
2024 }
2025
2026 snprintf(buffer, SIZE, "- Commands:\n");
2027 result = String8(buffer);
2028 result.append(" Command Time Wait pParam\n");
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002029 for (size_t i = 0; i < mAudioCommands.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002030 mAudioCommands[i]->dump(buffer, SIZE);
2031 result.append(buffer);
2032 }
2033 result.append(" Last Command\n");
Eric Laurent0ede8922014-05-09 18:04:42 -07002034 if (mLastCommand != 0) {
2035 mLastCommand->dump(buffer, SIZE);
2036 result.append(buffer);
2037 } else {
2038 result.append(" none\n");
2039 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002040
2041 write(fd, result.string(), result.size());
2042
Mikhail Naganov12b716c2020-04-30 22:37:43 +00002043 dumpReleaseLock(mLock, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002044
2045 return NO_ERROR;
2046}
2047
Glenn Kastenfff6d712012-01-12 16:38:12 -08002048status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
Eric Laurentde070132010-07-13 04:45:46 -07002049 float volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002050 audio_io_handle_t output,
Eric Laurentde070132010-07-13 04:45:46 -07002051 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002052{
Eric Laurent0ede8922014-05-09 18:04:42 -07002053 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002054 command->mCommand = SET_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002055 sp<VolumeData> data = new VolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002056 data->mStream = stream;
2057 data->mVolume = volume;
2058 data->mIO = output;
2059 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002060 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002061 ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
Eric Laurentde070132010-07-13 04:45:46 -07002062 stream, volume, output);
Eric Laurent0ede8922014-05-09 18:04:42 -07002063 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002064}
2065
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002066status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
Dima Zavinfce7a472011-04-19 22:30:36 -07002067 const char *keyValuePairs,
Eric Laurentde070132010-07-13 04:45:46 -07002068 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002069{
Eric Laurent0ede8922014-05-09 18:04:42 -07002070 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002071 command->mCommand = SET_PARAMETERS;
Eric Laurent0ede8922014-05-09 18:04:42 -07002072 sp<ParametersData> data = new ParametersData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002073 data->mIO = ioHandle;
Dima Zavinfce7a472011-04-19 22:30:36 -07002074 data->mKeyValuePairs = String8(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002075 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002076 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002077 ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
Dima Zavinfce7a472011-04-19 22:30:36 -07002078 keyValuePairs, ioHandle, delayMs);
Eric Laurent0ede8922014-05-09 18:04:42 -07002079 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002080}
2081
2082status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
2083{
Eric Laurent0ede8922014-05-09 18:04:42 -07002084 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002085 command->mCommand = SET_VOICE_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002086 sp<VoiceVolumeData> data = new VoiceVolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002087 data->mVolume = volume;
2088 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002089 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002090 ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
Eric Laurent0ede8922014-05-09 18:04:42 -07002091 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002092}
2093
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002094void AudioPolicyService::AudioCommandThread::setEffectSuspendedCommand(int effectId,
2095 audio_session_t sessionId,
2096 bool suspended)
2097{
2098 sp<AudioCommand> command = new AudioCommand();
2099 command->mCommand = SET_EFFECT_SUSPENDED;
2100 sp<SetEffectSuspendedData> data = new SetEffectSuspendedData();
2101 data->mEffectId = effectId;
2102 data->mSessionId = sessionId;
2103 data->mSuspended = suspended;
2104 command->mParam = data;
2105 ALOGV("AudioCommandThread() adding set suspended effectId %d sessionId %d suspended %d",
2106 effectId, sessionId, suspended);
2107 sendCommand(command);
2108}
2109
2110
Eric Laurentd7fe0862018-07-14 16:48:01 -07002111void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002112{
Eric Laurent0ede8922014-05-09 18:04:42 -07002113 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002114 command->mCommand = STOP_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002115 sp<StopOutputData> data = new StopOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002116 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002117 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002118 ALOGV("AudioCommandThread() adding stop output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002119 sendCommand(command);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002120}
2121
Eric Laurentd7fe0862018-07-14 16:48:01 -07002122void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002123{
Eric Laurent0ede8922014-05-09 18:04:42 -07002124 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002125 command->mCommand = RELEASE_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002126 sp<ReleaseOutputData> data = new ReleaseOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002127 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002128 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002129 ALOGV("AudioCommandThread() adding release output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002130 sendCommand(command);
2131}
2132
Eric Laurent951f4552014-05-20 10:48:17 -07002133status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
2134 const struct audio_patch *patch,
2135 audio_patch_handle_t *handle,
2136 int delayMs)
2137{
2138 status_t status = NO_ERROR;
2139
2140 sp<AudioCommand> command = new AudioCommand();
2141 command->mCommand = CREATE_AUDIO_PATCH;
2142 CreateAudioPatchData *data = new CreateAudioPatchData();
2143 data->mPatch = *patch;
2144 data->mHandle = *handle;
2145 command->mParam = data;
2146 command->mWaitStatus = true;
2147 ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
2148 status = sendCommand(command, delayMs);
2149 if (status == NO_ERROR) {
2150 *handle = data->mHandle;
2151 }
2152 return status;
2153}
2154
2155status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
2156 int delayMs)
2157{
2158 sp<AudioCommand> command = new AudioCommand();
2159 command->mCommand = RELEASE_AUDIO_PATCH;
2160 ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
2161 data->mHandle = handle;
2162 command->mParam = data;
2163 command->mWaitStatus = true;
2164 ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
2165 return sendCommand(command, delayMs);
2166}
2167
Eric Laurentb52c1522014-05-20 11:27:36 -07002168void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
2169{
2170 sp<AudioCommand> command = new AudioCommand();
2171 command->mCommand = UPDATE_AUDIOPORT_LIST;
2172 ALOGV("AudioCommandThread() adding update audio port list");
2173 sendCommand(command);
2174}
2175
Eric Laurented726cc2021-07-01 14:26:41 +02002176void AudioPolicyService::AudioCommandThread::updateUidStatesCommand()
2177{
2178 sp<AudioCommand> command = new AudioCommand();
2179 command->mCommand = UPDATE_UID_STATES;
2180 ALOGV("AudioCommandThread() adding update UID states");
2181 sendCommand(command);
2182}
2183
Eric Laurentb52c1522014-05-20 11:27:36 -07002184void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
2185{
2186 sp<AudioCommand>command = new AudioCommand();
2187 command->mCommand = UPDATE_AUDIOPATCH_LIST;
2188 ALOGV("AudioCommandThread() adding update audio patch list");
2189 sendCommand(command);
2190}
2191
François Gaffiecfe17322018-11-07 13:41:29 +01002192void AudioPolicyService::AudioCommandThread::changeAudioVolumeGroupCommand(volume_group_t group,
2193 int flags)
2194{
2195 sp<AudioCommand>command = new AudioCommand();
2196 command->mCommand = CHANGED_AUDIOVOLUMEGROUP;
2197 AudioVolumeGroupData *data= new AudioVolumeGroupData();
2198 data->mGroup = group;
2199 data->mFlags = flags;
2200 command->mParam = data;
2201 ALOGV("AudioCommandThread() adding audio volume group changed");
2202 sendCommand(command);
2203}
2204
Eric Laurente1715a42014-05-20 11:30:42 -07002205status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
2206 const struct audio_port_config *config, int delayMs)
2207{
2208 sp<AudioCommand> command = new AudioCommand();
2209 command->mCommand = SET_AUDIOPORT_CONFIG;
2210 SetAudioPortConfigData *data = new SetAudioPortConfigData();
2211 data->mConfig = *config;
2212 command->mParam = data;
2213 command->mWaitStatus = true;
2214 ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
2215 return sendCommand(command, delayMs);
2216}
2217
Jean-Michel Trivide801052015-04-14 19:10:14 -07002218void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002219 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -07002220{
2221 sp<AudioCommand> command = new AudioCommand();
2222 command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
2223 DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
2224 data->mRegId = regId;
2225 data->mState = state;
2226 command->mParam = data;
2227 ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
2228 regId.string(), state);
2229 sendCommand(command);
2230}
2231
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002232void AudioPolicyService::AudioCommandThread::recordingConfigurationUpdateCommand(
Eric Laurenta9f86652018-11-28 17:23:11 -08002233 int event,
2234 const record_client_info_t *clientInfo,
2235 const audio_config_base_t *clientConfig,
2236 std::vector<effect_descriptor_t> clientEffects,
2237 const audio_config_base_t *deviceConfig,
2238 std::vector<effect_descriptor_t> effects,
2239 audio_patch_handle_t patchHandle,
2240 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002241{
2242 sp<AudioCommand>command = new AudioCommand();
2243 command->mCommand = RECORDING_CONFIGURATION_UPDATE;
2244 RecordingConfigurationUpdateData *data = new RecordingConfigurationUpdateData();
2245 data->mEvent = event;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002246 data->mClientInfo = *clientInfo;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002247 data->mClientConfig = *clientConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002248 data->mClientEffects = clientEffects;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002249 data->mDeviceConfig = *deviceConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002250 data->mEffects = effects;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002251 data->mPatchHandle = patchHandle;
Eric Laurenta9f86652018-11-28 17:23:11 -08002252 data->mSource = source;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002253 command->mParam = data;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002254 ALOGV("AudioCommandThread() adding recording configuration update event %d, source %d uid %u",
2255 event, clientInfo->source, clientInfo->uid);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002256 sendCommand(command);
2257}
2258
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002259void AudioPolicyService::AudioCommandThread::audioModulesUpdateCommand()
2260{
2261 sp<AudioCommand> command = new AudioCommand();
2262 command->mCommand = AUDIO_MODULES_UPDATE;
2263 sendCommand(command);
2264}
2265
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002266void AudioPolicyService::AudioCommandThread::routingChangedCommand()
2267{
2268 sp<AudioCommand>command = new AudioCommand();
2269 command->mCommand = ROUTING_UPDATED;
2270 ALOGV("AudioCommandThread() adding routing update");
2271 sendCommand(command);
2272}
2273
Eric Laurent81dd0f52021-07-05 11:54:40 +02002274void AudioPolicyService::AudioCommandThread::checkSpatializerCommand()
2275{
2276 sp<AudioCommand>command = new AudioCommand();
2277 command->mCommand = CHECK_SPATIALIZER;
2278 ALOGV("AudioCommandThread() adding check spatializer");
2279 sendCommand(command);
2280}
2281
Eric Laurent0ede8922014-05-09 18:04:42 -07002282status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
2283{
2284 {
2285 Mutex::Autolock _l(mLock);
2286 insertCommand_l(command, delayMs);
2287 mWaitWorkCV.signal();
2288 }
2289 Mutex::Autolock _l(command->mLock);
2290 while (command->mWaitStatus) {
2291 nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
2292 if (command->mCond.waitRelative(command->mLock, timeOutNs) != NO_ERROR) {
2293 command->mStatus = TIMED_OUT;
2294 command->mWaitStatus = false;
2295 }
2296 }
2297 return command->mStatus;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002298}
2299
Mathias Agopian65ab4712010-07-14 17:59:35 -07002300// insertCommand_l() must be called with mLock held
Eric Laurent0ede8922014-05-09 18:04:42 -07002301void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002302{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002303 ssize_t i; // not size_t because i will count down to -1
Eric Laurent0ede8922014-05-09 18:04:42 -07002304 Vector < sp<AudioCommand> > removedCommands;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002305 command->mTime = systemTime() + milliseconds(delayMs);
2306
2307 // acquire wake lock to make sure delayed commands are processed
Eric Laurentbfb1b832013-01-07 09:53:42 -08002308 if (mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002309 acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.string());
2310 }
2311
2312 // check same pending commands with later time stamps and eliminate them
Ivan Lozano5ff158f2017-10-30 09:06:24 -07002313 for (i = (ssize_t)mAudioCommands.size()-1; i >= 0; i--) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002314 sp<AudioCommand> command2 = mAudioCommands[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07002315 // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
2316 if (command2->mTime <= command->mTime) break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002317
2318 // create audio patch or release audio patch commands are equivalent
2319 // with regard to filtering
2320 if ((command->mCommand == CREATE_AUDIO_PATCH) ||
2321 (command->mCommand == RELEASE_AUDIO_PATCH)) {
2322 if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
2323 (command2->mCommand != RELEASE_AUDIO_PATCH)) {
2324 continue;
2325 }
2326 } else if (command2->mCommand != command->mCommand) continue;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002327
2328 switch (command->mCommand) {
2329 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002330 ParametersData *data = (ParametersData *)command->mParam.get();
2331 ParametersData *data2 = (ParametersData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002332 if (data->mIO != data2->mIO) break;
Steve Block3856b092011-10-20 11:56:00 +01002333 ALOGV("Comparing parameter command %s to new command %s",
Eric Laurentde070132010-07-13 04:45:46 -07002334 data2->mKeyValuePairs.string(), data->mKeyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002335 AudioParameter param = AudioParameter(data->mKeyValuePairs);
2336 AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
2337 for (size_t j = 0; j < param.size(); j++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002338 String8 key;
2339 String8 value;
2340 param.getAt(j, key, value);
2341 for (size_t k = 0; k < param2.size(); k++) {
2342 String8 key2;
2343 String8 value2;
2344 param2.getAt(k, key2, value2);
2345 if (key2 == key) {
2346 param2.remove(key2);
2347 ALOGV("Filtering out parameter %s", key2.string());
2348 break;
2349 }
2350 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002351 }
2352 // if all keys have been filtered out, remove the command.
2353 // otherwise, update the key value pairs
2354 if (param2.size() == 0) {
2355 removedCommands.add(command2);
2356 } else {
2357 data2->mKeyValuePairs = param2.toString();
2358 }
Eric Laurent21e54562013-09-23 12:08:05 -07002359 command->mTime = command2->mTime;
2360 // force delayMs to non 0 so that code below does not request to wait for
2361 // command status as the command is now delayed
2362 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002363 } break;
2364
2365 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002366 VolumeData *data = (VolumeData *)command->mParam.get();
2367 VolumeData *data2 = (VolumeData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002368 if (data->mIO != data2->mIO) break;
2369 if (data->mStream != data2->mStream) break;
Steve Block3856b092011-10-20 11:56:00 +01002370 ALOGV("Filtering out volume command on output %d for stream %d",
Eric Laurentde070132010-07-13 04:45:46 -07002371 data->mIO, data->mStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002372 removedCommands.add(command2);
Eric Laurent21e54562013-09-23 12:08:05 -07002373 command->mTime = command2->mTime;
2374 // force delayMs to non 0 so that code below does not request to wait for
2375 // command status as the command is now delayed
2376 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002377 } break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002378
Eric Laurentbaf35fe2016-07-27 15:36:53 -07002379 case SET_VOICE_VOLUME: {
2380 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
2381 VoiceVolumeData *data2 = (VoiceVolumeData *)command2->mParam.get();
2382 ALOGV("Filtering out voice volume command value %f replaced by %f",
2383 data2->mVolume, data->mVolume);
2384 removedCommands.add(command2);
2385 command->mTime = command2->mTime;
2386 // force delayMs to non 0 so that code below does not request to wait for
2387 // command status as the command is now delayed
2388 delayMs = 1;
2389 } break;
2390
Eric Laurente45b48a2014-09-04 16:40:57 -07002391 case CREATE_AUDIO_PATCH:
2392 case RELEASE_AUDIO_PATCH: {
2393 audio_patch_handle_t handle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002394 struct audio_patch patch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002395 if (command->mCommand == CREATE_AUDIO_PATCH) {
2396 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002397 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002398 } else {
2399 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
Mikhail Naganov7be71d22018-05-23 16:51:46 -07002400 memset(&patch, 0, sizeof(patch));
Eric Laurente45b48a2014-09-04 16:40:57 -07002401 }
2402 audio_patch_handle_t handle2;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002403 struct audio_patch patch2;
Eric Laurente45b48a2014-09-04 16:40:57 -07002404 if (command2->mCommand == CREATE_AUDIO_PATCH) {
2405 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002406 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002407 } else {
2408 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
Glenn Kastenf60b6b62015-07-06 10:53:26 -07002409 memset(&patch2, 0, sizeof(patch2));
Eric Laurente45b48a2014-09-04 16:40:57 -07002410 }
2411 if (handle != handle2) break;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002412 /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
2413 same output. */
2414 if( (command->mCommand == CREATE_AUDIO_PATCH) &&
2415 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
2416 bool isOutputDiff = false;
2417 if (patch.num_sources == patch2.num_sources) {
2418 for (unsigned count = 0; count < patch.num_sources; count++) {
2419 if (patch.sources[count].id != patch2.sources[count].id) {
2420 isOutputDiff = true;
2421 break;
2422 }
2423 }
2424 if (isOutputDiff)
2425 break;
2426 }
2427 }
Eric Laurente45b48a2014-09-04 16:40:57 -07002428 ALOGV("Filtering out %s audio patch command for handle %d",
2429 (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
2430 removedCommands.add(command2);
2431 command->mTime = command2->mTime;
2432 // force delayMs to non 0 so that code below does not request to wait for
2433 // command status as the command is now delayed
2434 delayMs = 1;
2435 } break;
2436
Jean-Michel Trivide801052015-04-14 19:10:14 -07002437 case DYN_POLICY_MIX_STATE_UPDATE: {
2438
2439 } break;
2440
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002441 case RECORDING_CONFIGURATION_UPDATE: {
2442
2443 } break;
2444
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002445 case ROUTING_UPDATED: {
2446
2447 } break;
2448
Mathias Agopian65ab4712010-07-14 17:59:35 -07002449 default:
2450 break;
2451 }
2452 }
2453
2454 // remove filtered commands
2455 for (size_t j = 0; j < removedCommands.size(); j++) {
2456 // removed commands always have time stamps greater than current command
2457 for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002458 if (mAudioCommands[k].get() == removedCommands[j].get()) {
Steve Block3856b092011-10-20 11:56:00 +01002459 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002460 mAudioCommands.removeAt(k);
2461 break;
2462 }
2463 }
2464 }
2465 removedCommands.clear();
2466
Eric Laurentaa79bef2015-01-15 14:33:51 -08002467 // Disable wait for status if delay is not 0.
2468 // Except for create audio patch command because the returned patch handle
2469 // is needed by audio policy manager
2470 if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
Eric Laurentcec4abb2012-07-03 12:23:02 -07002471 command->mWaitStatus = false;
2472 }
Eric Laurentcec4abb2012-07-03 12:23:02 -07002473
Mathias Agopian65ab4712010-07-14 17:59:35 -07002474 // insert command at the right place according to its time stamp
Eric Laurent1e693b52014-07-09 15:03:28 -07002475 ALOGV("inserting command: %d at index %zd, num commands %zu",
2476 command->mCommand, i+1, mAudioCommands.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002477 mAudioCommands.insertAt(command, i + 1);
2478}
2479
2480void AudioPolicyService::AudioCommandThread::exit()
2481{
Steve Block3856b092011-10-20 11:56:00 +01002482 ALOGV("AudioCommandThread::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002483 {
2484 AutoMutex _l(mLock);
2485 requestExit();
2486 mWaitWorkCV.signal();
2487 }
Zach Janga754b4f2015-10-27 01:29:34 +00002488 // Note that we can call it from the thread loop if all other references have been released
2489 // but it will safely return WOULD_BLOCK in this case
Mathias Agopian65ab4712010-07-14 17:59:35 -07002490 requestExitAndWait();
2491}
2492
2493void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
2494{
2495 snprintf(buffer, size, " %02d %06d.%03d %01u %p\n",
2496 mCommand,
2497 (int)ns2s(mTime),
2498 (int)ns2ms(mTime)%1000,
2499 mWaitStatus,
Eric Laurent0ede8922014-05-09 18:04:42 -07002500 mParam.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002501}
2502
Dima Zavinfce7a472011-04-19 22:30:36 -07002503/******* helpers for the service_ops callbacks defined below *********/
2504void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
2505 const char *keyValuePairs,
2506 int delayMs)
2507{
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002508 mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
Dima Zavinfce7a472011-04-19 22:30:36 -07002509 delayMs);
2510}
2511
2512int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
2513 float volume,
2514 audio_io_handle_t output,
2515 int delayMs)
2516{
Glenn Kastenfff6d712012-01-12 16:38:12 -08002517 return (int)mAudioCommandThread->volumeCommand(stream, volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002518 output, delayMs);
Dima Zavinfce7a472011-04-19 22:30:36 -07002519}
2520
Dima Zavinfce7a472011-04-19 22:30:36 -07002521int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
2522{
2523 return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
2524}
2525
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002526void AudioPolicyService::setEffectSuspended(int effectId,
2527 audio_session_t sessionId,
2528 bool suspended)
2529{
2530 mAudioCommandThread->setEffectSuspendedCommand(effectId, sessionId, suspended);
2531}
2532
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002533Status AudioPolicyService::onNewAudioModulesAvailable()
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002534{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07002535 mOutputCommandThread->audioModulesUpdateCommand();
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002536 return Status::ok();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002537}
2538
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002539
Dima Zavinfce7a472011-04-19 22:30:36 -07002540extern "C" {
Eric Laurent2d388ec2014-03-07 13:25:54 -08002541audio_module_handle_t aps_load_hw_module(void *service __unused,
2542 const char *name);
2543audio_io_handle_t aps_open_output(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002544 audio_devices_t *pDevices,
2545 uint32_t *pSamplingRate,
2546 audio_format_t *pFormat,
2547 audio_channel_mask_t *pChannelMask,
2548 uint32_t *pLatencyMs,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002549 audio_output_flags_t flags);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002550
Eric Laurent2d388ec2014-03-07 13:25:54 -08002551audio_io_handle_t aps_open_output_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002552 audio_module_handle_t module,
2553 audio_devices_t *pDevices,
2554 uint32_t *pSamplingRate,
2555 audio_format_t *pFormat,
2556 audio_channel_mask_t *pChannelMask,
2557 uint32_t *pLatencyMs,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002558 audio_output_flags_t flags,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002559 const audio_offload_info_t *offloadInfo);
2560audio_io_handle_t aps_open_dup_output(void *service __unused,
Dima Zavinfce7a472011-04-19 22:30:36 -07002561 audio_io_handle_t output1,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002562 audio_io_handle_t output2);
2563int aps_close_output(void *service __unused, audio_io_handle_t output);
2564int aps_suspend_output(void *service __unused, audio_io_handle_t output);
2565int aps_restore_output(void *service __unused, audio_io_handle_t output);
2566audio_io_handle_t aps_open_input(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002567 audio_devices_t *pDevices,
2568 uint32_t *pSamplingRate,
2569 audio_format_t *pFormat,
2570 audio_channel_mask_t *pChannelMask,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002571 audio_in_acoustics_t acoustics __unused);
2572audio_io_handle_t aps_open_input_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002573 audio_module_handle_t module,
2574 audio_devices_t *pDevices,
2575 uint32_t *pSamplingRate,
2576 audio_format_t *pFormat,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002577 audio_channel_mask_t *pChannelMask);
2578int aps_close_input(void *service __unused, audio_io_handle_t input);
2579int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
Glenn Kastend848eb42016-03-08 13:42:11 -08002580int aps_move_effects(void *service __unused, audio_session_t session,
Dima Zavinfce7a472011-04-19 22:30:36 -07002581 audio_io_handle_t src_output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002582 audio_io_handle_t dst_output);
2583char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
2584 const char *keys);
2585void aps_set_parameters(void *service, audio_io_handle_t io_handle,
2586 const char *kv_pairs, int delay_ms);
2587int aps_set_stream_volume(void *service, audio_stream_type_t stream,
Dima Zavinfce7a472011-04-19 22:30:36 -07002588 float volume, audio_io_handle_t output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002589 int delay_ms);
Eric Laurent2d388ec2014-03-07 13:25:54 -08002590int aps_set_voice_volume(void *service, float volume, int delay_ms);
2591};
Dima Zavinfce7a472011-04-19 22:30:36 -07002592
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08002593} // namespace android