blob: fb6b09600c8088278788b6a94f8143f2d9ca4938 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "AudioPolicyService"
18//#define LOG_NDEBUG 0
19
Glenn Kasten153b9fe2013-07-15 11:23:36 -070020#include "Configuration.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070021#undef __STRICT_ANSI__
22#define __STDINT_LIMITS
23#define __STDC_LIMIT_MACROS
24#include <stdint.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070025#include <sys/time.h>
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053026#include <dlfcn.h>
Mikhail Naganov959e2d02019-03-28 11:08:19 -070027
28#include <audio_utils/clock.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070029#include <binder/IServiceManager.h>
30#include <utils/Log.h>
31#include <cutils/properties.h>
32#include <binder/IPCThreadState.h>
Svet Ganovf4ddfef2018-01-16 07:37:58 -080033#include <binder/PermissionController.h>
34#include <binder/IResultReceiver.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035#include <utils/String16.h>
36#include <utils/threads.h>
37#include "AudioPolicyService.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070038#include <hardware_legacy/power.h>
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -080039#include <media/AidlConversion.h>
Eric Laurent7c7f10b2011-06-17 21:29:58 -070040#include <media/AudioEffect.h>
Chih-Hung Hsiehc84d9d22014-11-14 13:33:34 -080041#include <media/AudioParameter.h>
Andy Hungab7ef302018-05-15 19:35:29 -070042#include <mediautils/ServiceUtilities.h>
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -080043#include <mediautils/TimeCheck.h>
Michael Groovercfd28302018-12-11 19:16:46 -080044#include <sensorprivacy/SensorPrivacyManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045
Dima Zavin64760242011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070047#include <system/audio_policy.h>
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053048#include <AudioPolicyManager.h>
Mikhail Naganov61a4fac2016-10-13 14:44:18 -070049
Mathias Agopian65ab4712010-07-14 17:59:35 -070050namespace android {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -080051using binder::Status;
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
Glenn Kasten8dad0e32012-01-09 08:41:22 -080053static const char kDeadlockedString[] = "AudioPolicyService may be deadlocked\n";
54static const char kCmdDeadlockedString[] = "AudioPolicyService command thread may be deadlocked\n";
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053055static const char kAudioPolicyManagerCustomPath[] = "libaudiopolicymanagercustom.so";
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Mikhail Naganov959e2d02019-03-28 11:08:19 -070057static const int kDumpLockTimeoutNs = 1 * NANOS_PER_SECOND;
Mathias Agopian65ab4712010-07-14 17:59:35 -070058
Eric Laurent0ede8922014-05-09 18:04:42 -070059static const nsecs_t kAudioCommandTimeoutNs = seconds(3); // 3 seconds
Christer Fletcher5fa8c4b2013-01-18 15:27:03 +010060
Svet Ganovf4ddfef2018-01-16 07:37:58 -080061static const String16 sManageAudioPolicyPermission("android.permission.MANAGE_AUDIO_POLICY");
Dima Zavinfce7a472011-04-19 22:30:36 -070062
Mathias Agopian65ab4712010-07-14 17:59:35 -070063// ----------------------------------------------------------------------------
64
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053065static AudioPolicyInterface* createAudioPolicyManager(AudioPolicyClientInterface *clientInterface)
66{
67 AudioPolicyManager *apm = new AudioPolicyManager(clientInterface);
68 status_t status = apm->initialize();
69 if (status != NO_ERROR) {
70 delete apm;
71 apm = nullptr;
72 }
73 return apm;
74}
75
76static void destroyAudioPolicyManager(AudioPolicyInterface *interface)
77{
78 delete interface;
79}
80// ----------------------------------------------------------------------------
81
Mathias Agopian65ab4712010-07-14 17:59:35 -070082AudioPolicyService::AudioPolicyService()
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -070083 : BnAudioPolicyService(),
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -070084 mAudioPolicyManager(NULL),
85 mAudioPolicyClient(NULL),
86 mPhoneState(AUDIO_MODE_INVALID),
Jaideep Sharmaba9053b2021-01-25 21:24:26 +053087 mCaptureStateNotifier(false),
88 mCreateAudioPolicyManager(createAudioPolicyManager),
89 mDestroyAudioPolicyManager(destroyAudioPolicyManager) {
90}
91
92void AudioPolicyService::loadAudioPolicyManager()
93{
94 mLibraryHandle = dlopen(kAudioPolicyManagerCustomPath, RTLD_NOW);
95 if (mLibraryHandle != nullptr) {
96 ALOGI("%s loading %s", __func__, kAudioPolicyManagerCustomPath);
97 mCreateAudioPolicyManager = reinterpret_cast<CreateAudioPolicyManagerInstance>
98 (dlsym(mLibraryHandle, "createAudioPolicyManager"));
99 const char *lastError = dlerror();
100 ALOGW_IF(mCreateAudioPolicyManager == nullptr, "%s createAudioPolicyManager is null %s",
101 __func__, lastError != nullptr ? lastError : "no error");
102
103 mDestroyAudioPolicyManager = reinterpret_cast<DestroyAudioPolicyManagerInstance>(
104 dlsym(mLibraryHandle, "destroyAudioPolicyManager"));
105 lastError = dlerror();
106 ALOGW_IF(mDestroyAudioPolicyManager == nullptr, "%s destroyAudioPolicyManager is null %s",
107 __func__, lastError != nullptr ? lastError : "no error");
108 if (mCreateAudioPolicyManager == nullptr || mDestroyAudioPolicyManager == nullptr){
109 unloadAudioPolicyManager();
110 LOG_ALWAYS_FATAL("could not find audiopolicymanager interface methods");
111 }
112 }
Eric Laurentf5ada6e2014-10-09 17:49:00 -0700113}
114
115void AudioPolicyService::onFirstRef()
116{
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700117 {
118 Mutex::Autolock _l(mLock);
Eric Laurent93575202011-01-18 18:39:02 -0800119
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700120 // start audio commands thread
121 mAudioCommandThread = new AudioCommandThread(String8("ApmAudio"), this);
122 // start output activity command thread
123 mOutputCommandThread = new AudioCommandThread(String8("ApmOutput"), this);
Eric Laurentdce54a12014-03-10 12:19:46 -0700124
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700125 mAudioPolicyClient = new AudioPolicyClient(this);
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530126
127 loadAudioPolicyManager();
128 mAudioPolicyManager = mCreateAudioPolicyManager(mAudioPolicyClient);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700129 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200130
bryant_liuba2b4392014-06-11 16:49:30 +0800131 // load audio processing modules
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000132 sp<AudioPolicyEffects> audioPolicyEffects = new AudioPolicyEffects();
133 sp<UidPolicy> uidPolicy = new UidPolicy(this);
134 sp<SensorPrivacyPolicy> sensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700135 {
136 Mutex::Autolock _l(mLock);
137 mAudioPolicyEffects = audioPolicyEffects;
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000138 mUidPolicy = uidPolicy;
139 mSensorPrivacyPolicy = sensorPrivacyPolicy;
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700140 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000141 uidPolicy->registerSelf();
142 sensorPrivacyPolicy->registerSelf();
Eric Laurentd66d7a12021-07-13 13:35:32 +0200143
Eric Laurent81dd0f52021-07-05 11:54:40 +0200144 // Create spatializer if supported
Eric Laurent52b0bd52021-09-27 15:25:40 +0200145 if (mAudioPolicyManager != nullptr) {
146 Mutex::Autolock _l(mLock);
147 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
148 AudioDeviceTypeAddrVector devices;
149 bool hasSpatializer = mAudioPolicyManager->canBeSpatialized(&attr, nullptr, devices);
150 if (hasSpatializer) {
151 mSpatializer = Spatializer::create(this);
152 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200153 }
Eric Laurentd66d7a12021-07-13 13:35:32 +0200154 AudioSystem::audioPolicyReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700155}
156
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530157void AudioPolicyService::unloadAudioPolicyManager()
158{
159 ALOGV("%s ", __func__);
160 if (mLibraryHandle != nullptr) {
161 dlclose(mLibraryHandle);
162 }
163 mLibraryHandle = nullptr;
164 mCreateAudioPolicyManager = nullptr;
165 mDestroyAudioPolicyManager = nullptr;
166}
167
Mathias Agopian65ab4712010-07-14 17:59:35 -0700168AudioPolicyService::~AudioPolicyService()
169{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700170 mAudioCommandThread->exit();
Eric Laurent657ff612014-05-07 11:58:24 -0700171 mOutputCommandThread->exit();
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700172
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530173 mDestroyAudioPolicyManager(mAudioPolicyManager);
174 unloadAudioPolicyManager();
175
Eric Laurentdce54a12014-03-10 12:19:46 -0700176 delete mAudioPolicyClient;
Eric Laurentb52c1522014-05-20 11:27:36 -0700177
178 mNotificationClients.clear();
bryant_liuba2b4392014-06-11 16:49:30 +0800179 mAudioPolicyEffects.clear();
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800180
181 mUidPolicy->unregisterSelf();
Michael Groovercfd28302018-12-11 19:16:46 -0800182 mSensorPrivacyPolicy->unregisterSelf();
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000183
184 mUidPolicy.clear();
Michael Groovercfd28302018-12-11 19:16:46 -0800185 mSensorPrivacyPolicy.clear();
Eric Laurentb52c1522014-05-20 11:27:36 -0700186}
187
188// A notification client is always registered by AudioSystem when the client process
189// connects to AudioPolicyService.
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800190Status AudioPolicyService::registerClient(const sp<media::IAudioPolicyServiceClient>& client)
Eric Laurentb52c1522014-05-20 11:27:36 -0700191{
Eric Laurent12590252015-08-21 18:40:20 -0700192 if (client == 0) {
193 ALOGW("%s got NULL client", __FUNCTION__);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800194 return Status::ok();
Eric Laurent12590252015-08-21 18:40:20 -0700195 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800196 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700197
198 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800199 pid_t pid = IPCThreadState::self()->getCallingPid();
200 int64_t token = ((int64_t)uid<<32) | pid;
201
202 if (mNotificationClients.indexOfKey(token) < 0) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700203 sp<NotificationClient> notificationClient = new NotificationClient(this,
204 client,
luochaojiang908c7d72018-06-21 14:58:04 +0800205 uid,
206 pid);
207 ALOGV("registerClient() client %p, uid %d pid %d", client.get(), uid, pid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700208
luochaojiang908c7d72018-06-21 14:58:04 +0800209 mNotificationClients.add(token, notificationClient);
Eric Laurentb52c1522014-05-20 11:27:36 -0700210
Marco Nelissenf8880202014-11-14 07:58:25 -0800211 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurentb52c1522014-05-20 11:27:36 -0700212 binder->linkToDeath(notificationClient);
213 }
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800214 return Status::ok();
Eric Laurentb52c1522014-05-20 11:27:36 -0700215}
216
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800217Status AudioPolicyService::setAudioPortCallbacksEnabled(bool enabled)
Eric Laurente8726fe2015-06-26 09:39:24 -0700218{
219 Mutex::Autolock _l(mNotificationClientsLock);
220
221 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800222 pid_t pid = IPCThreadState::self()->getCallingPid();
223 int64_t token = ((int64_t)uid<<32) | pid;
224
225 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800226 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700227 }
luochaojiang908c7d72018-06-21 14:58:04 +0800228 mNotificationClients.valueFor(token)->setAudioPortCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800229 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700230}
231
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800232Status AudioPolicyService::setAudioVolumeGroupCallbacksEnabled(bool enabled)
François Gaffiecfe17322018-11-07 13:41:29 +0100233{
234 Mutex::Autolock _l(mNotificationClientsLock);
235
236 uid_t uid = IPCThreadState::self()->getCallingUid();
237 pid_t pid = IPCThreadState::self()->getCallingPid();
238 int64_t token = ((int64_t)uid<<32) | pid;
239
240 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800241 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100242 }
243 mNotificationClients.valueFor(token)->setAudioVolumeGroupCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800244 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100245}
246
Eric Laurentb52c1522014-05-20 11:27:36 -0700247// removeNotificationClient() is called when the client process dies.
luochaojiang908c7d72018-06-21 14:58:04 +0800248void AudioPolicyService::removeNotificationClient(uid_t uid, pid_t pid)
Eric Laurentb52c1522014-05-20 11:27:36 -0700249{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000250 bool hasSameUid = false;
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800251 {
252 Mutex::Autolock _l(mNotificationClientsLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800253 int64_t token = ((int64_t)uid<<32) | pid;
254 mNotificationClients.removeItem(token);
luochaojiang908c7d72018-06-21 14:58:04 +0800255 for (size_t i = 0; i < mNotificationClients.size(); i++) {
256 if (mNotificationClients.valueAt(i)->uid() == uid) {
257 hasSameUid = true;
258 break;
259 }
260 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000261 }
262 {
263 Mutex::Autolock _l(mLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800264 if (mAudioPolicyManager && !hasSameUid) {
Eric Laurent10b71232018-04-13 18:14:44 -0700265 // called from binder death notification: no need to clear caller identity
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700266 mAudioPolicyManager->releaseResourcesForUid(uid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700267 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800268 }
Eric Laurentb52c1522014-05-20 11:27:36 -0700269}
270
271void AudioPolicyService::onAudioPortListUpdate()
272{
273 mOutputCommandThread->updateAudioPortListCommand();
274}
275
276void AudioPolicyService::doOnAudioPortListUpdate()
277{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800278 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700279 for (size_t i = 0; i < mNotificationClients.size(); i++) {
280 mNotificationClients.valueAt(i)->onAudioPortListUpdate();
281 }
282}
283
284void AudioPolicyService::onAudioPatchListUpdate()
285{
286 mOutputCommandThread->updateAudioPatchListCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700287}
288
Eric Laurentb52c1522014-05-20 11:27:36 -0700289void AudioPolicyService::doOnAudioPatchListUpdate()
290{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800291 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700292 for (size_t i = 0; i < mNotificationClients.size(); i++) {
293 mNotificationClients.valueAt(i)->onAudioPatchListUpdate();
294 }
295}
296
François Gaffiecfe17322018-11-07 13:41:29 +0100297void AudioPolicyService::onAudioVolumeGroupChanged(volume_group_t group, int flags)
298{
299 mOutputCommandThread->changeAudioVolumeGroupCommand(group, flags);
300}
301
302void AudioPolicyService::doOnAudioVolumeGroupChanged(volume_group_t group, int flags)
303{
304 Mutex::Autolock _l(mNotificationClientsLock);
305 for (size_t i = 0; i < mNotificationClients.size(); i++) {
306 mNotificationClients.valueAt(i)->onAudioVolumeGroupChanged(group, flags);
307 }
308}
309
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700310void AudioPolicyService::onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700311{
312 ALOGV("AudioPolicyService::onDynamicPolicyMixStateUpdate(%s, %d)",
313 regId.string(), state);
314 mOutputCommandThread->dynamicPolicyMixStateUpdateCommand(regId, state);
315}
316
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700317void AudioPolicyService::doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700318{
319 Mutex::Autolock _l(mNotificationClientsLock);
320 for (size_t i = 0; i < mNotificationClients.size(); i++) {
321 mNotificationClients.valueAt(i)->onDynamicPolicyMixStateUpdate(regId, state);
322 }
323}
324
Eric Laurenta9f86652018-11-28 17:23:11 -0800325void AudioPolicyService::onRecordingConfigurationUpdate(
326 int event,
327 const record_client_info_t *clientInfo,
328 const audio_config_base_t *clientConfig,
329 std::vector<effect_descriptor_t> clientEffects,
330 const audio_config_base_t *deviceConfig,
331 std::vector<effect_descriptor_t> effects,
332 audio_patch_handle_t patchHandle,
333 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800334{
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800335 mOutputCommandThread->recordingConfigurationUpdateCommand(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800336 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800337}
338
Eric Laurenta9f86652018-11-28 17:23:11 -0800339void AudioPolicyService::doOnRecordingConfigurationUpdate(
340 int event,
341 const record_client_info_t *clientInfo,
342 const audio_config_base_t *clientConfig,
343 std::vector<effect_descriptor_t> clientEffects,
344 const audio_config_base_t *deviceConfig,
345 std::vector<effect_descriptor_t> effects,
346 audio_patch_handle_t patchHandle,
347 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800348{
349 Mutex::Autolock _l(mNotificationClientsLock);
350 for (size_t i = 0; i < mNotificationClients.size(); i++) {
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800351 mNotificationClients.valueAt(i)->onRecordingConfigurationUpdate(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800352 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800353 }
354}
355
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700356void AudioPolicyService::onRoutingUpdated()
357{
358 mOutputCommandThread->routingChangedCommand();
359}
360
361void AudioPolicyService::doOnRoutingUpdated()
362{
363 Mutex::Autolock _l(mNotificationClientsLock);
364 for (size_t i = 0; i < mNotificationClients.size(); i++) {
365 mNotificationClients.valueAt(i)->onRoutingUpdated();
366 }
367}
368
Eric Laurent81dd0f52021-07-05 11:54:40 +0200369void AudioPolicyService::onCheckSpatializer()
370{
371 Mutex::Autolock _l(mLock);
Eric Laurent39095982021-08-24 18:29:27 +0200372 onCheckSpatializer_l();
373}
374
375void AudioPolicyService::onCheckSpatializer_l()
376{
377 if (mSpatializer != nullptr) {
378 mOutputCommandThread->checkSpatializerCommand();
379 }
Eric Laurent81dd0f52021-07-05 11:54:40 +0200380}
381
382void AudioPolicyService::doOnCheckSpatializer()
383{
Eric Laurent39095982021-08-24 18:29:27 +0200384 Mutex::Autolock _l(mLock);
Eric Laurent81dd0f52021-07-05 11:54:40 +0200385
Eric Laurent39095982021-08-24 18:29:27 +0200386 if (mSpatializer != nullptr) {
Eric Laurent52b0bd52021-09-27 15:25:40 +0200387 // Note: mSpatializer != nullptr => mAudioPolicyManager != nullptr
Eric Laurent39095982021-08-24 18:29:27 +0200388 if (mSpatializer->getLevel() != media::SpatializationLevel::NONE) {
389 audio_io_handle_t currentOutput = mSpatializer->getOutput();
390 audio_io_handle_t newOutput;
391 const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA);
392 audio_config_base_t config = mSpatializer->getAudioInConfig();
393 status_t status =
394 mAudioPolicyManager->getSpatializerOutput(&config, &attr, &newOutput);
Eric Laurentb4f42a92022-01-17 17:37:31 +0100395 ALOGV("%s currentOutput %d newOutput %d channel_mask %#x",
396 __func__, currentOutput, newOutput, config.channel_mask);
Eric Laurent39095982021-08-24 18:29:27 +0200397 if (status == NO_ERROR && currentOutput == newOutput) {
398 return;
399 }
400 mLock.unlock();
401 // It is OK to call detachOutput() is none is already attached.
402 mSpatializer->detachOutput();
403 if (status != NO_ERROR || newOutput == AUDIO_IO_HANDLE_NONE) {
Eric Laurent81dd0f52021-07-05 11:54:40 +0200404 mLock.lock();
Eric Laurent39095982021-08-24 18:29:27 +0200405 return;
406 }
407 status = mSpatializer->attachOutput(newOutput);
408 mLock.lock();
409 if (status != NO_ERROR) {
410 mAudioPolicyManager->releaseSpatializerOutput(newOutput);
411 }
412 } else if (mSpatializer->getLevel() == media::SpatializationLevel::NONE
413 && mSpatializer->getOutput() != AUDIO_IO_HANDLE_NONE) {
414 mLock.unlock();
415 audio_io_handle_t output = mSpatializer->detachOutput();
416 mLock.lock();
417 if (output != AUDIO_IO_HANDLE_NONE) {
418 mAudioPolicyManager->releaseSpatializerOutput(output);
Eric Laurent81dd0f52021-07-05 11:54:40 +0200419 }
420 }
421 }
422}
423
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800424status_t AudioPolicyService::clientCreateAudioPatch(const struct audio_patch *patch,
425 audio_patch_handle_t *handle,
426 int delayMs)
427{
428 return mAudioCommandThread->createAudioPatchCommand(patch, handle, delayMs);
429}
430
431status_t AudioPolicyService::clientReleaseAudioPatch(audio_patch_handle_t handle,
432 int delayMs)
433{
434 return mAudioCommandThread->releaseAudioPatchCommand(handle, delayMs);
435}
436
Eric Laurente1715a42014-05-20 11:30:42 -0700437status_t AudioPolicyService::clientSetAudioPortConfig(const struct audio_port_config *config,
438 int delayMs)
439{
440 return mAudioCommandThread->setAudioPortConfigCommand(config, delayMs);
441}
442
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800443AudioPolicyService::NotificationClient::NotificationClient(
444 const sp<AudioPolicyService>& service,
445 const sp<media::IAudioPolicyServiceClient>& client,
446 uid_t uid,
447 pid_t pid)
luochaojiang908c7d72018-06-21 14:58:04 +0800448 : mService(service), mUid(uid), mPid(pid), mAudioPolicyServiceClient(client),
François Gaffiecfe17322018-11-07 13:41:29 +0100449 mAudioPortCallbacksEnabled(false), mAudioVolumeGroupCallbacksEnabled(false)
Eric Laurentb52c1522014-05-20 11:27:36 -0700450{
451}
452
453AudioPolicyService::NotificationClient::~NotificationClient()
454{
455}
456
457void AudioPolicyService::NotificationClient::binderDied(const wp<IBinder>& who __unused)
458{
459 sp<NotificationClient> keep(this);
460 sp<AudioPolicyService> service = mService.promote();
461 if (service != 0) {
luochaojiang908c7d72018-06-21 14:58:04 +0800462 service->removeNotificationClient(mUid, mPid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700463 }
464}
465
466void AudioPolicyService::NotificationClient::onAudioPortListUpdate()
467{
Eric Laurente8726fe2015-06-26 09:39:24 -0700468 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700469 mAudioPolicyServiceClient->onAudioPortListUpdate();
470 }
471}
472
473void AudioPolicyService::NotificationClient::onAudioPatchListUpdate()
474{
Eric Laurente8726fe2015-06-26 09:39:24 -0700475 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700476 mAudioPolicyServiceClient->onAudioPatchListUpdate();
477 }
478}
Eric Laurent57dae992011-07-24 13:36:09 -0700479
Pattydd807582021-11-04 21:01:03 +0800480void AudioPolicyService::NotificationClient::onAudioVolumeGroupChanged(volume_group_t group,
François Gaffiecfe17322018-11-07 13:41:29 +0100481 int flags)
482{
483 if (mAudioPolicyServiceClient != 0 && mAudioVolumeGroupCallbacksEnabled) {
484 mAudioPolicyServiceClient->onAudioVolumeGroupChanged(group, flags);
485 }
486}
487
488
Jean-Michel Trivide801052015-04-14 19:10:14 -0700489void AudioPolicyService::NotificationClient::onDynamicPolicyMixStateUpdate(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700490 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700491{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700492 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800493 mAudioPolicyServiceClient->onDynamicPolicyMixStateUpdate(
494 legacy2aidl_String8_string(regId).value(), state);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800495 }
496}
497
498void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate(
Eric Laurenta9f86652018-11-28 17:23:11 -0800499 int event,
500 const record_client_info_t *clientInfo,
501 const audio_config_base_t *clientConfig,
502 std::vector<effect_descriptor_t> clientEffects,
503 const audio_config_base_t *deviceConfig,
504 std::vector<effect_descriptor_t> effects,
505 audio_patch_handle_t patchHandle,
506 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800507{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700508 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800509 status_t status = [&]() -> status_t {
510 int32_t eventAidl = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(event));
511 media::RecordClientInfo clientInfoAidl = VALUE_OR_RETURN_STATUS(
512 legacy2aidl_record_client_info_t_RecordClientInfo(*clientInfo));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700513 AudioConfigBase clientConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700514 legacy2aidl_audio_config_base_t_AudioConfigBase(
515 *clientConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800516 std::vector<media::EffectDescriptor> clientEffectsAidl = VALUE_OR_RETURN_STATUS(
517 convertContainer<std::vector<media::EffectDescriptor>>(
518 clientEffects,
519 legacy2aidl_effect_descriptor_t_EffectDescriptor));
Mikhail Naganovdbf03642021-08-25 18:15:32 -0700520 AudioConfigBase deviceConfigAidl = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -0700521 legacy2aidl_audio_config_base_t_AudioConfigBase(
522 *deviceConfig, true /*isInput*/));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800523 std::vector<media::EffectDescriptor> effectsAidl = VALUE_OR_RETURN_STATUS(
524 convertContainer<std::vector<media::EffectDescriptor>>(
525 effects,
526 legacy2aidl_effect_descriptor_t_EffectDescriptor));
527 int32_t patchHandleAidl = VALUE_OR_RETURN_STATUS(
528 legacy2aidl_audio_patch_handle_t_int32_t(patchHandle));
Mikhail Naganovddceecc2021-09-03 13:58:56 -0700529 media::audio::common::AudioSource sourceAidl = VALUE_OR_RETURN_STATUS(
530 legacy2aidl_audio_source_t_AudioSource(source));
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800531 return aidl_utils::statusTFromBinderStatus(
532 mAudioPolicyServiceClient->onRecordingConfigurationUpdate(eventAidl,
533 clientInfoAidl,
534 clientConfigAidl,
535 clientEffectsAidl,
536 deviceConfigAidl,
537 effectsAidl,
538 patchHandleAidl,
539 sourceAidl));
540 }();
541 ALOGW_IF(status != OK, "onRecordingConfigurationUpdate() failed: %d", status);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700542 }
543}
544
Eric Laurente8726fe2015-06-26 09:39:24 -0700545void AudioPolicyService::NotificationClient::setAudioPortCallbacksEnabled(bool enabled)
546{
547 mAudioPortCallbacksEnabled = enabled;
548}
549
François Gaffiecfe17322018-11-07 13:41:29 +0100550void AudioPolicyService::NotificationClient::setAudioVolumeGroupCallbacksEnabled(bool enabled)
551{
552 mAudioVolumeGroupCallbacksEnabled = enabled;
553}
Eric Laurente8726fe2015-06-26 09:39:24 -0700554
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700555void AudioPolicyService::NotificationClient::onRoutingUpdated()
556{
557 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
558 mAudioPolicyServiceClient->onRoutingUpdated();
559 }
560}
561
Mathias Agopian65ab4712010-07-14 17:59:35 -0700562void AudioPolicyService::binderDied(const wp<IBinder>& who) {
Glenn Kasten411e4472012-11-02 10:00:06 -0700563 ALOGW("binderDied() %p, calling pid %d", who.unsafe_get(),
Eric Laurentde070132010-07-13 04:45:46 -0700564 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700565}
566
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000567static bool dumpTryLock(Mutex& mutex) ACQUIRE(mutex) NO_THREAD_SAFETY_ANALYSIS
Mathias Agopian65ab4712010-07-14 17:59:35 -0700568{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000569 return mutex.timedLock(kDumpLockTimeoutNs) == NO_ERROR;
570}
571
572static void dumpReleaseLock(Mutex& mutex, bool locked) RELEASE(mutex) NO_THREAD_SAFETY_ANALYSIS
573{
574 if (locked) mutex.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700575}
576
577status_t AudioPolicyService::dumpInternals(int fd)
578{
579 const size_t SIZE = 256;
580 char buffer[SIZE];
581 String8 result;
582
Eric Laurentdce54a12014-03-10 12:19:46 -0700583 snprintf(buffer, SIZE, "AudioPolicyManager: %p\n", mAudioPolicyManager);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700584 result.append(buffer);
585 snprintf(buffer, SIZE, "Command Thread: %p\n", mAudioCommandThread.get());
586 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700587
Hayden Gomes524159d2019-12-23 14:41:47 -0800588 snprintf(buffer, SIZE, "Supported System Usages:\n");
589 result.append(buffer);
590 for (std::vector<audio_usage_t>::iterator it = mSupportedSystemUsages.begin();
591 it != mSupportedSystemUsages.end(); ++it) {
592 snprintf(buffer, SIZE, "\t%d\n", *it);
593 result.append(buffer);
594 }
595
Mathias Agopian65ab4712010-07-14 17:59:35 -0700596 write(fd, result.string(), result.size());
Oscar Azucena829d90d2022-01-28 17:17:56 -0800597
598 mUidPolicy->dumpInternals(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700599 return NO_ERROR;
600}
601
Eric Laurente8c8b432018-10-17 10:08:02 -0700602void AudioPolicyService::updateUidStates()
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800603{
Eric Laurente8c8b432018-10-17 10:08:02 -0700604 Mutex::Autolock _l(mLock);
605 updateUidStates_l();
606}
607
608void AudioPolicyService::updateUidStates_l()
609{
Eric Laurent4eb58f12018-12-07 16:41:02 -0800610// Go over all active clients and allow capture (does not force silence) in the
611// following cases:
Evan Severson1f700cd2021-02-10 13:10:37 -0800612// The client is the assistant
613// AND an accessibility service is on TOP or a RTT call is active
Eric Laurent589171c2019-07-25 18:04:29 -0700614// AND the source is VOICE_RECOGNITION or HOTWORD
Evan Severson1f700cd2021-02-10 13:10:37 -0800615// OR uses VOICE_RECOGNITION AND is on TOP
616// OR uses HOTWORD
617// AND there is no active privacy sensitive capture or call
618// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
619// OR The client is an accessibility service
620// AND Is on TOP
621// AND the source is VOICE_RECOGNITION or HOTWORD
622// OR The assistant is not on TOP
Eric Laurent589171c2019-07-25 18:04:29 -0700623// AND there is no active privacy sensitive capture or call
624// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Evan Severson1f700cd2021-02-10 13:10:37 -0800625// AND is on TOP
626// AND the source is VOICE_RECOGNITION or HOTWORD
627// OR the client source is virtual (remote submix, call audio TX or RX...)
628// OR the client source is HOTWORD
629// AND is on TOP
630// OR all active clients are using HOTWORD source
631// AND no call is active
632// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
633// OR the client is the current InputMethodService
634// AND a RTT call is active AND the source is VOICE_RECOGNITION
635// OR Any client
636// AND The assistant is not on TOP
637// AND is on TOP or latest started
638// AND there is no active privacy sensitive capture or call
639// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4eb58f12018-12-07 16:41:02 -0800640
Eric Laurent4e947da2019-10-17 15:24:06 -0700641
Eric Laurent4eb58f12018-12-07 16:41:02 -0800642 sp<AudioRecordClient> topActive;
643 sp<AudioRecordClient> latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800644 sp<AudioRecordClient> topSensitiveActive;
Eric Laurentb809a752020-06-29 09:53:13 -0700645 sp<AudioRecordClient> latestSensitiveActiveOrComm;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700646
Eric Laurenta46bedb2018-12-07 18:01:26 -0800647 nsecs_t topStartNs = 0;
648 nsecs_t latestStartNs = 0;
Eric Laurentc21d5692020-02-25 10:24:36 -0800649 nsecs_t topSensitiveStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800650 nsecs_t latestSensitiveStartNs = 0;
651 bool isA11yOnTop = mUidPolicy->isA11yOnTop();
652 bool isAssistantOnTop = false;
653 bool isSensitiveActive = false;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700654 bool isInCall = mPhoneState == AUDIO_MODE_IN_CALL;
Eric Laurentc21d5692020-02-25 10:24:36 -0800655 bool isInCommunication = mPhoneState == AUDIO_MODE_IN_COMMUNICATION;
656 bool rttCallActive = (isInCall || isInCommunication)
Eric Laurent6ede98f2019-06-11 14:50:30 -0700657 && mUidPolicy->isRttEnabled();
Eric Laurent4e947da2019-10-17 15:24:06 -0700658 bool onlyHotwordActive = true;
Eric Laurentb809a752020-06-29 09:53:13 -0700659 bool isPhoneStateOwnerActive = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800660
Michael Groovercfd28302018-12-11 19:16:46 -0800661 // if Sensor Privacy is enabled then all recordings should be silenced.
662 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
663 silenceAllRecordings_l();
664 return;
665 }
666
Eric Laurente8c8b432018-10-17 10:08:02 -0700667 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
668 sp<AudioRecordClient> current = mAudioRecordClients[i];
Svet Ganov33761132021-05-13 22:51:08 +0000669 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
670 current->attributionSource.uid));
Evan Severson1f700cd2021-02-10 13:10:37 -0800671 if (!current->active) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700672 continue;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800673 }
Eric Laurent1ff16a72019-03-14 18:35:04 -0700674
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700675 app_state_t appState = apmStatFromAmState(mUidPolicy->getUidState(currentUid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700676 // clients which app is in IDLE state are not eligible for top active or
677 // latest active
678 if (appState == APP_STATE_IDLE) {
679 continue;
680 }
681
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700682 bool isAccessibility = mUidPolicy->isA11yUid(currentUid);
Eric Laurent14a88632020-07-16 12:28:30 -0700683 // Clients capturing for Accessibility services or virtual sources are not considered
Eric Laurentc21d5692020-02-25 10:24:36 -0800684 // for top or latest active to avoid masking regular clients started before
Eric Laurent14a88632020-07-16 12:28:30 -0700685 if (!isAccessibility && !isVirtualSource(current->attributes.source)) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700686 bool isAssistant = mUidPolicy->isAssistantUid(currentUid);
Eric Laurentc21d5692020-02-25 10:24:36 -0800687 bool isPrivacySensitive =
688 (current->attributes.flags & AUDIO_FLAG_CAPTURE_PRIVATE) != 0;
Eric Laurentb809a752020-06-29 09:53:13 -0700689
Eric Laurentc21d5692020-02-25 10:24:36 -0800690 if (appState == APP_STATE_TOP) {
691 if (isPrivacySensitive) {
692 if (current->startTimeNs > topSensitiveStartNs) {
693 topSensitiveActive = current;
694 topSensitiveStartNs = current->startTimeNs;
695 }
696 } else {
697 if (current->startTimeNs > topStartNs) {
698 topActive = current;
699 topStartNs = current->startTimeNs;
700 }
701 }
702 if (isAssistant) {
703 isAssistantOnTop = true;
704 }
Eric Laurenta46bedb2018-12-07 18:01:26 -0800705 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800706 // Clients capturing for HOTWORD are not considered
707 // for latest active to avoid masking regular clients started before
708 if (!(current->attributes.source == AUDIO_SOURCE_HOTWORD
709 || ((isA11yOnTop || rttCallActive) && isAssistant))) {
710 if (isPrivacySensitive) {
Eric Laurentb809a752020-06-29 09:53:13 -0700711 // if audio mode is IN_COMMUNICATION, make sure the audio mode owner
712 // is marked latest sensitive active even if another app qualifies.
713 if (current->startTimeNs > latestSensitiveStartNs
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700714 || (isInCommunication && currentUid == mPhoneStateOwnerUid)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700715 if (!isInCommunication || latestSensitiveActiveOrComm == nullptr
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700716 || VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000717 latestSensitiveActiveOrComm->attributionSource.uid))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700718 != mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700719 latestSensitiveActiveOrComm = current;
720 latestSensitiveStartNs = current->startTimeNs;
721 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800722 }
723 isSensitiveActive = true;
724 } else {
725 if (current->startTimeNs > latestStartNs) {
726 latestActive = current;
727 latestStartNs = current->startTimeNs;
728 }
729 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800730 }
731 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700732 if (current->attributes.source != AUDIO_SOURCE_HOTWORD) {
733 onlyHotwordActive = false;
734 }
Eric Laurentb0eff0f2021-11-09 16:05:49 +0100735 if (currentUid == mPhoneStateOwnerUid &&
736 !isVirtualSource(current->attributes.source)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700737 isPhoneStateOwnerActive = true;
738 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800739 }
740
Eric Laurent1ff16a72019-03-14 18:35:04 -0700741 // if no active client with UI on Top, consider latest active as top
742 if (topActive == nullptr) {
743 topActive = latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800744 topStartNs = latestStartNs;
745 }
746 if (topSensitiveActive == nullptr) {
Eric Laurentb809a752020-06-29 09:53:13 -0700747 topSensitiveActive = latestSensitiveActiveOrComm;
Eric Laurentc21d5692020-02-25 10:24:36 -0800748 topSensitiveStartNs = latestSensitiveStartNs;
Eric Laurentb809a752020-06-29 09:53:13 -0700749 } else if (latestSensitiveActiveOrComm != nullptr) {
750 // if audio mode is IN_COMMUNICATION, favor audio mode owner over an app with
751 // foreground UI in case both are capturing with privacy sensitive flag.
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700752 uid_t latestActiveUid = VALUE_OR_FATAL(
Svet Ganov33761132021-05-13 22:51:08 +0000753 aidl2legacy_int32_t_uid_t(latestSensitiveActiveOrComm->attributionSource.uid));
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700754 if (isInCommunication && latestActiveUid == mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700755 topSensitiveActive = latestSensitiveActiveOrComm;
756 topSensitiveStartNs = latestSensitiveStartNs;
757 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800758 }
759
760 // If both privacy sensitive and regular capture are active:
761 // if the regular capture is privileged
762 // allow concurrency
763 // else
764 // favor the privacy sensitive case
765 if (topActive != nullptr && topSensitiveActive != nullptr
Ricardo Correa57a37692020-03-23 17:27:25 -0700766 && !topActive->canCaptureOutput) {
Eric Laurentc21d5692020-02-25 10:24:36 -0800767 topActive = nullptr;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800768 }
769
770 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
771 sp<AudioRecordClient> current = mAudioRecordClients[i];
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700772 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000773 current->attributionSource.uid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700774 if (!current->active) {
775 continue;
776 }
777
Eric Laurent4eb58f12018-12-07 16:41:02 -0800778 audio_source_t source = current->attributes.source;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700779 bool isTopOrLatestActive = topActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +0000780 current->attributionSource.uid == topActive->attributionSource.uid;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700781 bool isTopOrLatestSensitive = topSensitiveActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +0000782 current->attributionSource.uid == topSensitiveActive->attributionSource.uid;
Eric Laurentc21d5692020-02-25 10:24:36 -0800783
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000784 auto canCaptureIfInCallOrCommunication = [&](const auto &recordClient) REQUIRES(mLock) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700785 uid_t recordUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000786 recordClient->attributionSource.uid));
Ricardo Correa57a37692020-03-23 17:27:25 -0700787 bool canCaptureCall = recordClient->canCaptureOutput;
Eric Laurentb809a752020-06-29 09:53:13 -0700788 bool canCaptureCommunication = recordClient->canCaptureOutput
789 || !isPhoneStateOwnerActive
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700790 || recordUid == mPhoneStateOwnerUid;
Eric Laurentb809a752020-06-29 09:53:13 -0700791 return !(isInCall && !canCaptureCall)
792 && !(isInCommunication && !canCaptureCommunication);
Eric Laurentc21d5692020-02-25 10:24:36 -0800793 };
Eric Laurent1ff16a72019-03-14 18:35:04 -0700794
795 // By default allow capture if:
796 // The assistant is not on TOP
Eric Laurenta171e352019-05-07 13:04:45 -0700797 // AND is on TOP or latest started
Eric Laurent1ff16a72019-03-14 18:35:04 -0700798 // AND there is no active privacy sensitive capture or call
799 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
800 bool allowCapture = !isAssistantOnTop
Eric Laurentc21d5692020-02-25 10:24:36 -0800801 && (isTopOrLatestActive || isTopOrLatestSensitive)
802 && !(isSensitiveActive
Ricardo Correa57a37692020-03-23 17:27:25 -0700803 && !(isTopOrLatestSensitive || current->canCaptureOutput))
Eric Laurentc21d5692020-02-25 10:24:36 -0800804 && canCaptureIfInCallOrCommunication(current);
Eric Laurent2dc962b2019-03-01 08:25:25 -0800805
Eric Laurented726cc2021-07-01 14:26:41 +0200806 if (!current->hasOp()) {
807 // Never allow capture if app op is denied
808 allowCapture = false;
809 } else if (isVirtualSource(source)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700810 // Allow capture for virtual (remote submix, call audio TX or RX...) sources
811 allowCapture = true;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700812 } else if (mUidPolicy->isAssistantUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700813 // For assistant allow capture if:
Eric Laurent6ede98f2019-06-11 14:50:30 -0700814 // An accessibility service is on TOP or a RTT call is active
Eric Laurent1ff16a72019-03-14 18:35:04 -0700815 // AND the source is VOICE_RECOGNITION or HOTWORD
Eric Laurenta171e352019-05-07 13:04:45 -0700816 // OR is on TOP AND uses VOICE_RECOGNITION
Eric Laurent1ff16a72019-03-14 18:35:04 -0700817 // OR uses HOTWORD
818 // AND there is no active privacy sensitive capture or call
819 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent6ede98f2019-06-11 14:50:30 -0700820 if (isA11yOnTop || rttCallActive) {
Eric Laurent4eb58f12018-12-07 16:41:02 -0800821 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700822 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800823 }
824 } else {
Eric Laurenta171e352019-05-07 13:04:45 -0700825 if (((isAssistantOnTop && source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
Eric Laurentc21d5692020-02-25 10:24:36 -0800826 source == AUDIO_SOURCE_HOTWORD)
Ricardo Correa57a37692020-03-23 17:27:25 -0700827 && !(isSensitiveActive && !current->canCaptureOutput)
Eric Laurentc21d5692020-02-25 10:24:36 -0800828 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700829 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800830 }
831 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700832 } else if (mUidPolicy->isA11yUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700833 // For accessibility service allow capture if:
Eric Laurent47670c92019-08-28 16:59:05 -0700834 // The assistant is not on TOP
835 // AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -0700836 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent47670c92019-08-28 16:59:05 -0700837 // OR
838 // Is on TOP AND the source is VOICE_RECOGNITION or HOTWORD
839 if (!isAssistantOnTop
Ricardo Correa57a37692020-03-23 17:27:25 -0700840 && !(isSensitiveActive && !current->canCaptureOutput)
Eric Laurentc21d5692020-02-25 10:24:36 -0800841 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent47670c92019-08-28 16:59:05 -0700842 allowCapture = true;
843 }
Eric Laurent589171c2019-07-25 18:04:29 -0700844 if (isA11yOnTop) {
845 if (source == AUDIO_SOURCE_VOICE_RECOGNITION || source == AUDIO_SOURCE_HOTWORD) {
846 allowCapture = true;
847 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800848 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700849 } else if (source == AUDIO_SOURCE_HOTWORD) {
850 // For HOTWORD source allow capture when not on TOP if:
851 // All active clients are using HOTWORD source
852 // AND no call is active
853 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurentc21d5692020-02-25 10:24:36 -0800854 if (onlyHotwordActive
855 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent4e947da2019-10-17 15:24:06 -0700856 allowCapture = true;
857 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700858 } else if (mUidPolicy->isCurrentImeUid(currentUid)) {
Kohsuke Yatoha623a132020-03-24 20:10:26 -0700859 // For current InputMethodService allow capture if:
860 // A RTT call is active AND the source is VOICE_RECOGNITION
861 if (rttCallActive && source == AUDIO_SOURCE_VOICE_RECOGNITION) {
862 allowCapture = true;
863 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800864 }
Eric Laurent8c7ef892021-06-10 13:32:16 +0200865 setAppState_l(current,
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700866 allowCapture ? apmStatFromAmState(mUidPolicy->getUidState(currentUid)) :
Eric Laurent1ff16a72019-03-14 18:35:04 -0700867 APP_STATE_IDLE);
Eric Laurente8c8b432018-10-17 10:08:02 -0700868 }
869}
870
Michael Groovercfd28302018-12-11 19:16:46 -0800871void AudioPolicyService::silenceAllRecordings_l() {
872 for (size_t i = 0; i < mAudioRecordClients.size(); i++) {
873 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -0700874 if (!isVirtualSource(current->attributes.source)) {
Eric Laurent8c7ef892021-06-10 13:32:16 +0200875 setAppState_l(current, APP_STATE_IDLE);
Eric Laurent1ff16a72019-03-14 18:35:04 -0700876 }
Michael Groovercfd28302018-12-11 19:16:46 -0800877 }
878}
879
Eric Laurente8c8b432018-10-17 10:08:02 -0700880/* static */
881app_state_t AudioPolicyService::apmStatFromAmState(int amState) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700882
883 if (amState == ActivityManager::PROCESS_STATE_UNKNOWN) {
Eric Laurente8c8b432018-10-17 10:08:02 -0700884 return APP_STATE_IDLE;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700885 } else if (amState <= ActivityManager::PROCESS_STATE_TOP) {
886 // include persistent services
887 return APP_STATE_TOP;
Eric Laurente8c8b432018-10-17 10:08:02 -0700888 }
889 return APP_STATE_FOREGROUND;
890}
891
Eric Laurent4eb58f12018-12-07 16:41:02 -0800892/* static */
Eric Laurent2dc962b2019-03-01 08:25:25 -0800893bool AudioPolicyService::isVirtualSource(audio_source_t source)
Eric Laurent4eb58f12018-12-07 16:41:02 -0800894{
895 switch (source) {
896 case AUDIO_SOURCE_VOICE_UPLINK:
897 case AUDIO_SOURCE_VOICE_DOWNLINK:
898 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent2dc962b2019-03-01 08:25:25 -0800899 case AUDIO_SOURCE_REMOTE_SUBMIX:
900 case AUDIO_SOURCE_FM_TUNER:
Eric Laurent68eb2122020-04-30 17:40:57 -0700901 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent4eb58f12018-12-07 16:41:02 -0800902 return true;
903 default:
904 break;
905 }
906 return false;
907}
908
Eric Laurented726cc2021-07-01 14:26:41 +0200909/* static */
910bool AudioPolicyService::isAppOpSource(audio_source_t source)
911{
912 switch (source) {
913 case AUDIO_SOURCE_FM_TUNER:
914 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent637bd202021-09-22 11:17:11 +0200915 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurented726cc2021-07-01 14:26:41 +0200916 return false;
917 default:
918 break;
919 }
920 return true;
921}
922
Eric Laurent8c7ef892021-06-10 13:32:16 +0200923void AudioPolicyService::setAppState_l(sp<AudioRecordClient> client, app_state_t state)
Eric Laurente8c8b432018-10-17 10:08:02 -0700924{
925 AutoCallerClear acc;
926
927 if (mAudioPolicyManager) {
Eric Laurent8c7ef892021-06-10 13:32:16 +0200928 mAudioPolicyManager->setAppState(client->portId, state);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700929 }
930 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
931 if (af) {
Eric Laurentf32108e2018-10-04 17:22:04 -0700932 bool silenced = state == APP_STATE_IDLE;
Eric Laurent8c7ef892021-06-10 13:32:16 +0200933 if (client->silenced != silenced) {
934 if (client->active) {
935 if (silenced) {
936 finishRecording(client->attributionSource, client->attributes.source);
937 } else {
938 std::stringstream msg;
939 msg << "Audio recording un-silenced on session " << client->session;
940 if (!startRecording(client->attributionSource, String16(msg.str().c_str()),
941 client->attributes.source)) {
942 silenced = true;
943 }
944 }
945 }
946 af->setRecordSilenced(client->portId, silenced);
947 client->silenced = silenced;
948 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700949 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800950}
951
Glenn Kasten0f11b512014-01-31 16:18:54 -0800952status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700953{
Glenn Kasten44deb052012-02-05 18:09:08 -0800954 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700955 dumpPermissionDenial(fd);
956 } else {
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000957 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700958 if (!locked) {
959 String8 result(kDeadlockedString);
960 write(fd, result.string(), result.size());
961 }
962
963 dumpInternals(fd);
Glenn Kasten9d1f02d2012-02-08 17:47:58 -0800964 if (mAudioCommandThread != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700965 mAudioCommandThread->dump(fd);
966 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700967
Eric Laurentdce54a12014-03-10 12:19:46 -0700968 if (mAudioPolicyManager) {
969 mAudioPolicyManager->dump(fd);
970 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700971
Kevin Rocard8be94972019-02-22 13:26:25 -0800972 mPackageManager.dump(fd);
973
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000974 dumpReleaseLock(mLock, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700975 }
976 return NO_ERROR;
977}
978
979status_t AudioPolicyService::dumpPermissionDenial(int fd)
980{
981 const size_t SIZE = 256;
982 char buffer[SIZE];
983 String8 result;
984 snprintf(buffer, SIZE, "Permission Denial: "
985 "can't dump AudioPolicyService from pid=%d, uid=%d\n",
986 IPCThreadState::self()->getCallingPid(),
987 IPCThreadState::self()->getCallingUid());
988 result.append(buffer);
989 write(fd, result.string(), result.size());
990 return NO_ERROR;
991}
992
993status_t AudioPolicyService::onTransact(
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800994 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800995 // make sure transactions reserved to AudioFlinger do not come from other processes
996 switch (code) {
997 case TRANSACTION_startOutput:
998 case TRANSACTION_stopOutput:
999 case TRANSACTION_releaseOutput:
1000 case TRANSACTION_getInputForAttr:
1001 case TRANSACTION_startInput:
1002 case TRANSACTION_stopInput:
1003 case TRANSACTION_releaseInput:
1004 case TRANSACTION_getOutputForEffect:
1005 case TRANSACTION_registerEffect:
1006 case TRANSACTION_unregisterEffect:
1007 case TRANSACTION_setEffectEnabled:
1008 case TRANSACTION_getStrategyForStream:
1009 case TRANSACTION_getOutputForAttr:
1010 case TRANSACTION_moveEffectsToIo:
1011 ALOGW("%s: transaction %d received from PID %d",
1012 __func__, code, IPCThreadState::self()->getCallingPid());
1013 return INVALID_OPERATION;
1014 default:
1015 break;
1016 }
1017
1018 // make sure the following transactions come from system components
1019 switch (code) {
1020 case TRANSACTION_setDeviceConnectionState:
1021 case TRANSACTION_handleDeviceConfigChange:
1022 case TRANSACTION_setPhoneState:
1023//FIXME: Allow setForceUse calls from system apps until a better use case routing API is available
1024// case TRANSACTION_setForceUse:
1025 case TRANSACTION_initStreamVolume:
1026 case TRANSACTION_setStreamVolumeIndex:
1027 case TRANSACTION_setVolumeIndexForAttributes:
1028 case TRANSACTION_getStreamVolumeIndex:
1029 case TRANSACTION_getVolumeIndexForAttributes:
1030 case TRANSACTION_getMinVolumeIndexForAttributes:
1031 case TRANSACTION_getMaxVolumeIndexForAttributes:
1032 case TRANSACTION_isStreamActive:
1033 case TRANSACTION_isStreamActiveRemotely:
1034 case TRANSACTION_isSourceActive:
1035 case TRANSACTION_getDevicesForStream:
1036 case TRANSACTION_registerPolicyMixes:
1037 case TRANSACTION_setMasterMono:
1038 case TRANSACTION_getSurroundFormats:
Kriti Dang6537def2021-03-02 13:46:59 +01001039 case TRANSACTION_getReportedSurroundFormats:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001040 case TRANSACTION_setSurroundFormatEnabled:
Oscar Azucena829d90d2022-01-28 17:17:56 -08001041 case TRANSACTION_setAssistantServicesUids:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001042 case TRANSACTION_setA11yServicesUids:
1043 case TRANSACTION_setUidDeviceAffinities:
1044 case TRANSACTION_removeUidDeviceAffinities:
1045 case TRANSACTION_setUserIdDeviceAffinities:
1046 case TRANSACTION_removeUserIdDeviceAffinities:
Pattydd807582021-11-04 21:01:03 +08001047 case TRANSACTION_getHwOffloadFormatsSupportedForBluetoothMedia:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001048 case TRANSACTION_listAudioVolumeGroups:
1049 case TRANSACTION_getVolumeGroupFromAudioAttributes:
1050 case TRANSACTION_acquireSoundTriggerSession:
1051 case TRANSACTION_releaseSoundTriggerSession:
1052 case TRANSACTION_setRttEnabled:
1053 case TRANSACTION_isCallScreenModeSupported:
1054 case TRANSACTION_setDevicesRoleForStrategy:
1055 case TRANSACTION_setSupportedSystemUsages:
1056 case TRANSACTION_removeDevicesRoleForStrategy:
1057 case TRANSACTION_getDevicesForRoleAndStrategy:
1058 case TRANSACTION_getDevicesForAttributes:
1059 case TRANSACTION_setAllowedCapturePolicy:
1060 case TRANSACTION_onNewAudioModulesAvailable:
1061 case TRANSACTION_setCurrentImeUid:
1062 case TRANSACTION_registerSoundTriggerCaptureStateListener:
1063 case TRANSACTION_setDevicesRoleForCapturePreset:
1064 case TRANSACTION_addDevicesRoleForCapturePreset:
1065 case TRANSACTION_removeDevicesRoleForCapturePreset:
1066 case TRANSACTION_clearDevicesRoleForCapturePreset:
Eric Laurent81dd0f52021-07-05 11:54:40 +02001067 case TRANSACTION_getDevicesForRoleAndCapturePreset:
1068 case TRANSACTION_getSpatializer: {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08001069 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
1070 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
1071 __func__, code, IPCThreadState::self()->getCallingPid(),
1072 IPCThreadState::self()->getCallingUid());
1073 return INVALID_OPERATION;
1074 }
1075 } break;
1076 default:
1077 break;
1078 }
1079
1080 std::string tag("IAudioPolicyService command " + std::to_string(code));
1081 TimeCheck check(tag.c_str());
1082
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001083 switch (code) {
1084 case SHELL_COMMAND_TRANSACTION: {
1085 int in = data.readFileDescriptor();
1086 int out = data.readFileDescriptor();
1087 int err = data.readFileDescriptor();
1088 int argc = data.readInt32();
1089 Vector<String16> args;
1090 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
1091 args.add(data.readString16());
1092 }
1093 sp<IBinder> unusedCallback;
1094 sp<IResultReceiver> resultReceiver;
1095 status_t status;
1096 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
1097 return status;
1098 }
1099 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
1100 return status;
1101 }
1102 status = shellCommand(in, out, err, args);
1103 if (resultReceiver != nullptr) {
1104 resultReceiver->send(status);
1105 }
1106 return NO_ERROR;
1107 }
1108 }
1109
Mathias Agopian65ab4712010-07-14 17:59:35 -07001110 return BnAudioPolicyService::onTransact(code, data, reply, flags);
1111}
1112
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001113// ------------------- Shell command implementation -------------------
1114
1115// NOTE: This is a remote API - make sure all args are validated
1116status_t AudioPolicyService::shellCommand(int in, int out, int err, Vector<String16>& args) {
1117 if (!checkCallingPermission(sManageAudioPolicyPermission, nullptr, nullptr)) {
1118 return PERMISSION_DENIED;
1119 }
1120 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
1121 return BAD_VALUE;
1122 }
jovanakbe066e12019-09-02 11:54:39 -07001123 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001124 return handleSetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001125 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001126 return handleResetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001127 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001128 return handleGetUidState(args, out, err);
Eric Laurent269acb42021-04-23 16:53:22 +02001129 } else if (args.size() >= 1 && args[0] == String16("purge_permission-cache")) {
1130 purgePermissionCache();
1131 return NO_ERROR;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001132 } else if (args.size() == 1 && args[0] == String16("help")) {
1133 printHelp(out);
1134 return NO_ERROR;
1135 }
1136 printHelp(err);
1137 return BAD_VALUE;
1138}
1139
jovanakbe066e12019-09-02 11:54:39 -07001140static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1141 if (userId < 0) {
1142 ALOGE("Invalid user: %d", userId);
1143 dprintf(err, "Invalid user: %d\n", userId);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001144 return BAD_VALUE;
1145 }
jovanakbe066e12019-09-02 11:54:39 -07001146
1147 PermissionController pc;
1148 uid = pc.getPackageUid(packageName, 0);
1149 if (uid <= 0) {
1150 ALOGE("Unknown package: '%s'", String8(packageName).string());
1151 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1152 return BAD_VALUE;
1153 }
1154
1155 uid = multiuser_get_uid(userId, uid);
1156 return NO_ERROR;
1157}
1158
1159status_t AudioPolicyService::handleSetUidState(Vector<String16>& args, int err) {
1160 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
1161 if (!(args.size() == 3 || args.size() == 5)) {
1162 printHelp(err);
1163 return BAD_VALUE;
1164 }
1165
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001166 bool active = false;
1167 if (args[2] == String16("active")) {
1168 active = true;
1169 } else if ((args[2] != String16("idle"))) {
1170 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
1171 return BAD_VALUE;
1172 }
jovanakbe066e12019-09-02 11:54:39 -07001173
1174 int userId = 0;
1175 if (args.size() >= 5 && args[3] == String16("--user")) {
1176 userId = atoi(String8(args[4]));
1177 }
1178
1179 uid_t uid;
1180 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1181 return BAD_VALUE;
1182 }
1183
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001184 sp<UidPolicy> uidPolicy;
1185 {
1186 Mutex::Autolock _l(mLock);
1187 uidPolicy = mUidPolicy;
1188 }
1189 if (uidPolicy) {
1190 uidPolicy->addOverrideUid(uid, active);
1191 return NO_ERROR;
1192 }
1193 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001194}
1195
1196status_t AudioPolicyService::handleResetUidState(Vector<String16>& args, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001197 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1198 if (!(args.size() == 2 || args.size() == 4)) {
1199 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001200 return BAD_VALUE;
1201 }
jovanakbe066e12019-09-02 11:54:39 -07001202
1203 int userId = 0;
1204 if (args.size() >= 4 && args[2] == String16("--user")) {
1205 userId = atoi(String8(args[3]));
1206 }
1207
1208 uid_t uid;
1209 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1210 return BAD_VALUE;
1211 }
1212
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001213 sp<UidPolicy> uidPolicy;
1214 {
1215 Mutex::Autolock _l(mLock);
1216 uidPolicy = mUidPolicy;
1217 }
1218 if (uidPolicy) {
1219 uidPolicy->removeOverrideUid(uid);
1220 return NO_ERROR;
1221 }
1222 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001223}
1224
1225status_t AudioPolicyService::handleGetUidState(Vector<String16>& args, int out, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001226 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1227 if (!(args.size() == 2 || args.size() == 4)) {
1228 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001229 return BAD_VALUE;
1230 }
jovanakbe066e12019-09-02 11:54:39 -07001231
1232 int userId = 0;
1233 if (args.size() >= 4 && args[2] == String16("--user")) {
1234 userId = atoi(String8(args[3]));
1235 }
1236
1237 uid_t uid;
1238 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1239 return BAD_VALUE;
1240 }
1241
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001242 sp<UidPolicy> uidPolicy;
1243 {
1244 Mutex::Autolock _l(mLock);
1245 uidPolicy = mUidPolicy;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001246 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001247 if (uidPolicy) {
1248 return dprintf(out, uidPolicy->isUidActive(uid) ? "active\n" : "idle\n");
1249 }
1250 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001251}
1252
1253status_t AudioPolicyService::printHelp(int out) {
1254 return dprintf(out, "Audio policy service commands:\n"
jovanakbe066e12019-09-02 11:54:39 -07001255 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
1256 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
1257 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001258 " help print this message\n");
1259}
1260
1261// ----------- AudioPolicyService::UidPolicy implementation ----------
1262
1263void AudioPolicyService::UidPolicy::registerSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001264 status_t res = mAm.linkToDeath(this);
1265 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001266 | ActivityManager::UID_OBSERVER_IDLE
Eric Laurente8c8b432018-10-17 10:08:02 -07001267 | ActivityManager::UID_OBSERVER_ACTIVE
1268 | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001269 ActivityManager::PROCESS_STATE_UNKNOWN,
1270 String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001271 if (!res) {
1272 Mutex::Autolock _l(mLock);
1273 mObserverRegistered = true;
1274 } else {
1275 ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001276
Steven Moreland2f348142019-07-02 15:59:07 -07001277 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001278 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001279}
1280
1281void AudioPolicyService::UidPolicy::unregisterSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001282 mAm.unlinkToDeath(this);
1283 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001284 Mutex::Autolock _l(mLock);
1285 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001286}
1287
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001288void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
1289 Mutex::Autolock _l(mLock);
1290 mCachedUids.clear();
1291 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001292}
1293
Eric Laurente8c8b432018-10-17 10:08:02 -07001294void AudioPolicyService::UidPolicy::checkRegistered() {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001295 bool needToReregister = false;
1296 {
1297 Mutex::Autolock _l(mLock);
1298 needToReregister = !mObserverRegistered;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001299 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001300 if (needToReregister) {
1301 // Looks like ActivityManager has died previously, attempt to re-register.
1302 registerSelf();
1303 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001304}
1305
1306bool AudioPolicyService::UidPolicy::isUidActive(uid_t uid) {
1307 if (isServiceUid(uid)) return true;
1308 checkRegistered();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001309 {
1310 Mutex::Autolock _l(mLock);
1311 auto overrideIter = mOverrideUids.find(uid);
1312 if (overrideIter != mOverrideUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001313 return overrideIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001314 }
1315 // In an absense of the ActivityManager, assume everything to be active.
1316 if (!mObserverRegistered) return true;
1317 auto cacheIter = mCachedUids.find(uid);
Mikhail Naganoveba668a2018-04-05 08:13:15 -07001318 if (cacheIter != mCachedUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001319 return cacheIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001320 }
1321 }
1322 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001323 bool active = am.isUidActive(uid, String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001324 {
1325 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001326 mCachedUids.insert(std::pair<uid_t,
1327 std::pair<bool, int>>(uid, std::pair<bool, int>(active,
1328 ActivityManager::PROCESS_STATE_UNKNOWN)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001329 }
1330 return active;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001331}
1332
Eric Laurente8c8b432018-10-17 10:08:02 -07001333int AudioPolicyService::UidPolicy::getUidState(uid_t uid) {
1334 if (isServiceUid(uid)) {
1335 return ActivityManager::PROCESS_STATE_TOP;
1336 }
1337 checkRegistered();
1338 {
1339 Mutex::Autolock _l(mLock);
1340 auto overrideIter = mOverrideUids.find(uid);
1341 if (overrideIter != mOverrideUids.end()) {
1342 if (overrideIter->second.first) {
1343 if (overrideIter->second.second != ActivityManager::PROCESS_STATE_UNKNOWN) {
1344 return overrideIter->second.second;
1345 } else {
1346 auto cacheIter = mCachedUids.find(uid);
1347 if (cacheIter != mCachedUids.end()) {
1348 return cacheIter->second.second;
1349 }
1350 }
1351 }
1352 return ActivityManager::PROCESS_STATE_UNKNOWN;
1353 }
1354 // In an absense of the ActivityManager, assume everything to be active.
1355 if (!mObserverRegistered) {
1356 return ActivityManager::PROCESS_STATE_TOP;
1357 }
1358 auto cacheIter = mCachedUids.find(uid);
1359 if (cacheIter != mCachedUids.end()) {
1360 if (cacheIter->second.first) {
1361 return cacheIter->second.second;
1362 } else {
1363 return ActivityManager::PROCESS_STATE_UNKNOWN;
1364 }
1365 }
1366 }
1367 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001368 bool active = am.isUidActive(uid, String16("audioserver"));
Eric Laurente8c8b432018-10-17 10:08:02 -07001369 int state = ActivityManager::PROCESS_STATE_UNKNOWN;
1370 if (active) {
1371 state = am.getUidProcessState(uid, String16("audioserver"));
1372 }
1373 {
1374 Mutex::Autolock _l(mLock);
1375 mCachedUids.insert(std::pair<uid_t,
1376 std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
1377 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001378
Eric Laurente8c8b432018-10-17 10:08:02 -07001379 return state;
1380}
1381
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001382void AudioPolicyService::UidPolicy::onUidActive(uid_t uid) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001383 updateUid(&mCachedUids, uid, true, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001384}
1385
1386void AudioPolicyService::UidPolicy::onUidGone(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001387 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, false);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001388}
1389
1390void AudioPolicyService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001391 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001392}
1393
Eric Laurente8c8b432018-10-17 10:08:02 -07001394void AudioPolicyService::UidPolicy::onUidStateChanged(uid_t uid,
1395 int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07001396 int64_t procStateSeq __unused,
1397 int32_t capability __unused) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001398 if (procState != ActivityManager::PROCESS_STATE_UNKNOWN) {
1399 updateUid(&mCachedUids, uid, true, procState, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001400 }
1401}
1402
1403void AudioPolicyService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001404 updateUid(&mOverrideUids, uid, active, ActivityManager::PROCESS_STATE_UNKNOWN, insert);
1405}
1406
1407void AudioPolicyService::UidPolicy::notifyService() {
1408 sp<AudioPolicyService> service = mService.promote();
1409 if (service != nullptr) {
1410 service->updateUidStates();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001411 }
1412}
1413
Eric Laurente8c8b432018-10-17 10:08:02 -07001414void AudioPolicyService::UidPolicy::updateUid(std::unordered_map<uid_t,
1415 std::pair<bool, int>> *uids,
1416 uid_t uid,
1417 bool active,
1418 int state,
1419 bool insert) {
1420 if (isServiceUid(uid)) {
1421 return;
1422 }
1423 bool wasActive = isUidActive(uid);
1424 int previousState = getUidState(uid);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001425 {
1426 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001427 updateUidLocked(uids, uid, active, state, insert);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001428 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001429 if (wasActive != isUidActive(uid) || state != previousState) {
1430 notifyService();
1431 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001432}
1433
Eric Laurente8c8b432018-10-17 10:08:02 -07001434void AudioPolicyService::UidPolicy::updateUidLocked(std::unordered_map<uid_t,
1435 std::pair<bool, int>> *uids,
1436 uid_t uid,
1437 bool active,
1438 int state,
1439 bool insert) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001440 auto it = uids->find(uid);
1441 if (it != uids->end()) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001442 if (insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001443 if (state == ActivityManager::PROCESS_STATE_UNKNOWN) {
1444 it->second.first = active;
1445 }
1446 if (it->second.first) {
1447 it->second.second = state;
1448 } else {
1449 it->second.second = ActivityManager::PROCESS_STATE_UNKNOWN;
1450 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001451 } else {
1452 uids->erase(it);
1453 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001454 } else if (insert && (state == ActivityManager::PROCESS_STATE_UNKNOWN)) {
1455 uids->insert(std::pair<uid_t, std::pair<bool, int>>(uid,
1456 std::pair<bool, int>(active, state)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001457 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001458}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001459
Eric Laurent4eb58f12018-12-07 16:41:02 -08001460bool AudioPolicyService::UidPolicy::isA11yOnTop() {
1461 for (const auto &uid : mCachedUids) {
Eric Laurent47670c92019-08-28 16:59:05 -07001462 if (!isA11yUid(uid.first)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001463 continue;
1464 }
Amith Yamasanibcbb3002019-01-23 13:53:33 -08001465 if (uid.second.second >= ActivityManager::PROCESS_STATE_TOP
1466 && uid.second.second <= ActivityManager::PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001467 return true;
1468 }
1469 }
1470 return false;
1471}
1472
Eric Laurentb78763e2018-10-17 10:08:02 -07001473bool AudioPolicyService::UidPolicy::isA11yUid(uid_t uid)
1474{
1475 std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid);
1476 return it != mA11yUids.end();
1477}
1478
Oscar Azucena829d90d2022-01-28 17:17:56 -08001479void AudioPolicyService::UidPolicy::setAssistantUids(const std::vector<uid_t>& uids) {
1480 mAssistantUids.clear();
1481 mAssistantUids = uids;
1482}
1483
1484bool AudioPolicyService::UidPolicy::isAssistantUid(uid_t uid)
1485{
1486 std::vector<uid_t>::iterator it = find(mAssistantUids.begin(), mAssistantUids.end(), uid);
1487 return it != mAssistantUids.end();
1488}
1489
1490void AudioPolicyService::UidPolicy::dumpInternals(int fd) {
1491 const size_t SIZE = 256;
1492 char buffer[SIZE];
1493 String8 result;
1494 auto appendUidsToResult = [&](const char* title, const std::vector<uid_t> &uids) {
1495 snprintf(buffer, SIZE, "\t%s: \n", title);
1496 result.append(buffer);
1497 int counter = 0;
1498 if (uids.empty()) {
1499 snprintf(buffer, SIZE, "\t\tNo UIDs present.\n");
1500 result.append(buffer);
1501 return;
1502 }
1503 for (const auto &uid : uids) {
1504 snprintf(buffer, SIZE, "\t\tUID[%d]=%d\n", counter++, uid);
1505 result.append(buffer);
1506 }
1507 };
1508
1509 snprintf(buffer, SIZE, "UID Policy:\n");
1510 result.append(buffer);
1511 snprintf(buffer, SIZE, "\tmObserverRegistered=%s\n",(mObserverRegistered ? "True":"False"));
1512 result.append(buffer);
1513
1514 appendUidsToResult("Assistants UIDs", mAssistantUids);
1515
1516 appendUidsToResult("Accessibility UIDs", mA11yUids);
1517
1518 snprintf(buffer, SIZE, "\tInput Method Service UID=%d\n", mCurrentImeUid);
1519 result.append(buffer);
1520
1521 snprintf(buffer, SIZE, "\tIs RTT Enabled: %s\n", (mRttEnabled ? "True":"False"));
1522 result.append(buffer);
1523
1524 write(fd, result.string(), result.size());
1525}
1526
Michael Groovercfd28302018-12-11 19:16:46 -08001527// ----------- AudioPolicyService::SensorPrivacyService implementation ----------
1528void AudioPolicyService::SensorPrivacyPolicy::registerSelf() {
1529 SensorPrivacyManager spm;
1530 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1531 spm.addSensorPrivacyListener(this);
1532}
1533
Evan Severson241d9592021-01-08 12:16:02 -08001534void AudioPolicyService::SensorPrivacyPolicy::registerSelfForMicrophoneOnly(int userId) {
1535 SensorPrivacyManager spm;
1536 mSensorPrivacyEnabled = spm.isIndividualSensorPrivacyEnabled(userId,
1537 SensorPrivacyManager::INDIVIDUAL_SENSOR_MICROPHONE);
1538 spm.addIndividualSensorPrivacyListener(userId,
1539 SensorPrivacyManager::INDIVIDUAL_SENSOR_MICROPHONE, this);
1540}
1541
Michael Groovercfd28302018-12-11 19:16:46 -08001542void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
1543 SensorPrivacyManager spm;
1544 spm.removeSensorPrivacyListener(this);
1545}
1546
1547bool AudioPolicyService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1548 return mSensorPrivacyEnabled;
1549}
1550
1551binder::Status AudioPolicyService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
1552 mSensorPrivacyEnabled = enabled;
1553 sp<AudioPolicyService> service = mService.promote();
1554 if (service != nullptr) {
1555 service->updateUidStates();
1556 }
1557 return binder::Status::ok();
1558}
1559
Eric Laurented726cc2021-07-01 14:26:41 +02001560// ----------- AudioPolicyService::OpRecordAudioMonitor implementation ----------
1561
1562// static
1563sp<AudioPolicyService::OpRecordAudioMonitor>
1564AudioPolicyService::OpRecordAudioMonitor::createIfNeeded(
1565 const AttributionSourceState& attributionSource, const audio_attributes_t& attr,
1566 wp<AudioCommandThread> commandThread)
1567{
Eric Laurent987ce102021-07-05 12:11:51 +02001568 if (isAudioServerOrRootUid(attributionSource.uid)) {
1569 ALOGV("not silencing record for audio or root source %s",
Eric Laurented726cc2021-07-01 14:26:41 +02001570 attributionSource.toString().c_str());
1571 return nullptr;
1572 }
1573
1574 if (!AudioPolicyService::isAppOpSource(attr.source)) {
1575 ALOGD("not monitoring app op for uid %d and source %d",
1576 attributionSource.uid, attr.source);
1577 return nullptr;
1578 }
1579
1580 if (!attributionSource.packageName.has_value()
1581 || attributionSource.packageName.value().size() == 0) {
1582 return nullptr;
1583 }
1584 return new OpRecordAudioMonitor(attributionSource, getOpForSource(attr.source), commandThread);
1585}
1586
1587AudioPolicyService::OpRecordAudioMonitor::OpRecordAudioMonitor(
1588 const AttributionSourceState& attributionSource, int32_t appOp,
1589 wp<AudioCommandThread> commandThread) :
1590 mHasOp(true), mAttributionSource(attributionSource), mAppOp(appOp),
1591 mCommandThread(commandThread)
1592{
1593}
1594
1595AudioPolicyService::OpRecordAudioMonitor::~OpRecordAudioMonitor()
1596{
1597 if (mOpCallback != 0) {
1598 mAppOpsManager.stopWatchingMode(mOpCallback);
1599 }
1600 mOpCallback.clear();
1601}
1602
1603void AudioPolicyService::OpRecordAudioMonitor::onFirstRef()
1604{
1605 checkOp();
1606 mOpCallback = new RecordAudioOpCallback(this);
1607 ALOGV("start watching op %d for %s", mAppOp, mAttributionSource.toString().c_str());
1608 // TODO: We need to always watch AppOpsManager::OP_RECORD_AUDIO too
1609 // since it controls the mic permission for legacy apps.
1610 mAppOpsManager.startWatchingMode(mAppOp, VALUE_OR_FATAL(aidl2legacy_string_view_String16(
1611 mAttributionSource.packageName.value_or(""))),
1612 mOpCallback);
1613}
1614
1615bool AudioPolicyService::OpRecordAudioMonitor::hasOp() const {
1616 return mHasOp.load();
1617}
1618
1619// Called by RecordAudioOpCallback when the app op corresponding to this OpRecordAudioMonitor
1620// is updated in AppOp callback and in onFirstRef()
1621// Note this method is never called (and never to be) for audio server / root track
1622// due to the UID in createIfNeeded(). As a result for those record track, it's:
1623// - not called from constructor,
1624// - not called from RecordAudioOpCallback because the callback is not installed in this case
1625void AudioPolicyService::OpRecordAudioMonitor::checkOp(bool updateUidStates)
1626{
1627 // TODO: We need to always check AppOpsManager::OP_RECORD_AUDIO too
1628 // since it controls the mic permission for legacy apps.
1629 const int32_t mode = mAppOpsManager.checkOp(mAppOp,
1630 mAttributionSource.uid, VALUE_OR_FATAL(aidl2legacy_string_view_String16(
1631 mAttributionSource.packageName.value_or(""))));
1632 const bool hasIt = (mode == AppOpsManager::MODE_ALLOWED);
1633 // verbose logging only log when appOp changed
1634 ALOGI_IF(hasIt != mHasOp.load(),
1635 "App op %d missing, %ssilencing record %s",
1636 mAppOp, hasIt ? "un" : "", mAttributionSource.toString().c_str());
1637 mHasOp.store(hasIt);
1638
1639 if (updateUidStates) {
1640 sp<AudioCommandThread> commandThread = mCommandThread.promote();
1641 if (commandThread != nullptr) {
1642 commandThread->updateUidStatesCommand();
1643 }
1644 }
1645}
1646
1647AudioPolicyService::OpRecordAudioMonitor::RecordAudioOpCallback::RecordAudioOpCallback(
1648 const wp<OpRecordAudioMonitor>& monitor) : mMonitor(monitor)
1649{ }
1650
1651void AudioPolicyService::OpRecordAudioMonitor::RecordAudioOpCallback::opChanged(int32_t op,
1652 const String16& packageName __unused) {
1653 sp<OpRecordAudioMonitor> monitor = mMonitor.promote();
1654 if (monitor != NULL) {
1655 if (op != monitor->getOp()) {
1656 return;
1657 }
1658 monitor->checkOp(true);
1659 }
1660}
1661
1662
Mathias Agopian65ab4712010-07-14 17:59:35 -07001663// ----------- AudioPolicyService::AudioCommandThread implementation ----------
1664
Eric Laurentbfb1b832013-01-07 09:53:42 -08001665AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
1666 const wp<AudioPolicyService>& service)
1667 : Thread(false), mName(name), mService(service)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001668{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001669}
1670
1671
1672AudioPolicyService::AudioCommandThread::~AudioCommandThread()
1673{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001674 if (!mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001675 release_wake_lock(mName.string());
1676 }
1677 mAudioCommands.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001678}
1679
1680void AudioPolicyService::AudioCommandThread::onFirstRef()
1681{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001682 run(mName.string(), ANDROID_PRIORITY_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001683}
1684
1685bool AudioPolicyService::AudioCommandThread::threadLoop()
1686{
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001687 nsecs_t waitTime = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001688
1689 mLock.lock();
1690 while (!exitPending())
1691 {
Eric Laurent59a89232014-06-08 14:14:17 -07001692 sp<AudioPolicyService> svc;
1693 while (!mAudioCommands.isEmpty() && !exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001694 nsecs_t curTime = systemTime();
1695 // commands are sorted by increasing time stamp: execute them from index 0 and up
1696 if (mAudioCommands[0]->mTime <= curTime) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001697 sp<AudioCommand> command = mAudioCommands[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001698 mAudioCommands.removeAt(0);
Eric Laurent0ede8922014-05-09 18:04:42 -07001699 mLastCommand = command;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001700
1701 switch (command->mCommand) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001702 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001703 VolumeData *data = (VolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001704 ALOGV("AudioCommandThread() processing set volume stream %d, \
Eric Laurentde070132010-07-13 04:45:46 -07001705 volume %f, output %d", data->mStream, data->mVolume, data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001706 mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07001707 command->mStatus = AudioSystem::setStreamVolume(data->mStream,
1708 data->mVolume,
1709 data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001710 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001711 }break;
1712 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001713 ParametersData *data = (ParametersData *)command->mParam.get();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001714 ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
1715 data->mKeyValuePairs.string(), data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001716 mLock.unlock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001717 command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
Andy Hungfe726a62018-09-27 15:17:25 -07001718 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001719 }break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001720 case SET_VOICE_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001721 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001722 ALOGV("AudioCommandThread() processing set voice volume volume %f",
Eric Laurentde070132010-07-13 04:45:46 -07001723 data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001724 mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001725 command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001726 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001727 }break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001728 case STOP_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001729 StopOutputData *data = (StopOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001730 ALOGV("AudioCommandThread() processing stop output portId %d",
1731 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001732 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001733 if (svc == 0) {
1734 break;
1735 }
1736 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001737 svc->doStopOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001738 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001739 }break;
1740 case RELEASE_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001741 ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001742 ALOGV("AudioCommandThread() processing release output portId %d",
1743 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001744 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001745 if (svc == 0) {
1746 break;
1747 }
1748 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001749 svc->doReleaseOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001750 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001751 }break;
Eric Laurent951f4552014-05-20 10:48:17 -07001752 case CREATE_AUDIO_PATCH: {
1753 CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
1754 ALOGV("AudioCommandThread() processing create audio patch");
1755 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1756 if (af == 0) {
1757 command->mStatus = PERMISSION_DENIED;
1758 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001759 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001760 command->mStatus = af->createAudioPatch(&data->mPatch, &data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001761 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001762 }
1763 } break;
1764 case RELEASE_AUDIO_PATCH: {
1765 ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
1766 ALOGV("AudioCommandThread() processing release audio patch");
1767 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1768 if (af == 0) {
1769 command->mStatus = PERMISSION_DENIED;
1770 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001771 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001772 command->mStatus = af->releaseAudioPatch(data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001773 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001774 }
1775 } break;
Eric Laurentb52c1522014-05-20 11:27:36 -07001776 case UPDATE_AUDIOPORT_LIST: {
1777 ALOGV("AudioCommandThread() processing update audio port list");
Eric Laurent59a89232014-06-08 14:14:17 -07001778 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001779 if (svc == 0) {
1780 break;
1781 }
1782 mLock.unlock();
1783 svc->doOnAudioPortListUpdate();
1784 mLock.lock();
1785 }break;
1786 case UPDATE_AUDIOPATCH_LIST: {
1787 ALOGV("AudioCommandThread() processing update audio patch list");
Eric Laurent59a89232014-06-08 14:14:17 -07001788 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001789 if (svc == 0) {
1790 break;
1791 }
1792 mLock.unlock();
1793 svc->doOnAudioPatchListUpdate();
1794 mLock.lock();
1795 }break;
François Gaffiecfe17322018-11-07 13:41:29 +01001796 case CHANGED_AUDIOVOLUMEGROUP: {
1797 AudioVolumeGroupData *data =
1798 static_cast<AudioVolumeGroupData *>(command->mParam.get());
1799 ALOGV("AudioCommandThread() processing update audio volume group");
1800 svc = mService.promote();
1801 if (svc == 0) {
1802 break;
1803 }
1804 mLock.unlock();
1805 svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
1806 mLock.lock();
1807 }break;
Eric Laurente1715a42014-05-20 11:30:42 -07001808 case SET_AUDIOPORT_CONFIG: {
1809 SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
1810 ALOGV("AudioCommandThread() processing set port config");
1811 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1812 if (af == 0) {
1813 command->mStatus = PERMISSION_DENIED;
1814 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001815 mLock.unlock();
Eric Laurente1715a42014-05-20 11:30:42 -07001816 command->mStatus = af->setAudioPortConfig(&data->mConfig);
Andy Hungfe726a62018-09-27 15:17:25 -07001817 mLock.lock();
Eric Laurente1715a42014-05-20 11:30:42 -07001818 }
1819 } break;
Jean-Michel Trivide801052015-04-14 19:10:14 -07001820 case DYN_POLICY_MIX_STATE_UPDATE: {
1821 DynPolicyMixStateUpdateData *data =
1822 (DynPolicyMixStateUpdateData *)command->mParam.get();
Jean-Michel Trivide801052015-04-14 19:10:14 -07001823 ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
1824 data->mRegId.string(), data->mState);
1825 svc = mService.promote();
1826 if (svc == 0) {
1827 break;
1828 }
1829 mLock.unlock();
1830 svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
1831 mLock.lock();
1832 } break;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001833 case RECORDING_CONFIGURATION_UPDATE: {
1834 RecordingConfigurationUpdateData *data =
1835 (RecordingConfigurationUpdateData *)command->mParam.get();
1836 ALOGV("AudioCommandThread() processing recording configuration update");
1837 svc = mService.promote();
1838 if (svc == 0) {
1839 break;
1840 }
1841 mLock.unlock();
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001842 svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -08001843 &data->mClientConfig, data->mClientEffects,
1844 &data->mDeviceConfig, data->mEffects,
1845 data->mPatchHandle, data->mSource);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001846 mLock.lock();
1847 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001848 case SET_EFFECT_SUSPENDED: {
1849 SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
1850 ALOGV("AudioCommandThread() processing set effect suspended");
1851 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1852 if (af != 0) {
1853 mLock.unlock();
1854 af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
1855 mLock.lock();
1856 }
1857 } break;
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001858 case AUDIO_MODULES_UPDATE: {
1859 ALOGV("AudioCommandThread() processing audio modules update");
1860 svc = mService.promote();
1861 if (svc == 0) {
1862 break;
1863 }
1864 mLock.unlock();
1865 svc->doOnNewAudioModulesAvailable();
1866 mLock.lock();
1867 } break;
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07001868 case ROUTING_UPDATED: {
1869 ALOGV("AudioCommandThread() processing routing update");
1870 svc = mService.promote();
1871 if (svc == 0) {
1872 break;
1873 }
1874 mLock.unlock();
1875 svc->doOnRoutingUpdated();
1876 mLock.lock();
1877 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001878
Eric Laurented726cc2021-07-01 14:26:41 +02001879 case UPDATE_UID_STATES: {
1880 ALOGV("AudioCommandThread() processing updateUID states");
1881 svc = mService.promote();
1882 if (svc == 0) {
1883 break;
1884 }
1885 mLock.unlock();
1886 svc->updateUidStates();
1887 mLock.lock();
1888 } break;
1889
Eric Laurent81dd0f52021-07-05 11:54:40 +02001890 case CHECK_SPATIALIZER: {
1891 ALOGV("AudioCommandThread() processing updateUID states");
1892 svc = mService.promote();
1893 if (svc == 0) {
1894 break;
1895 }
1896 mLock.unlock();
1897 svc->doOnCheckSpatializer();
1898 mLock.lock();
1899 } break;
1900
Mathias Agopian65ab4712010-07-14 17:59:35 -07001901 default:
Steve Block5ff1dd52012-01-05 23:22:43 +00001902 ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001903 }
Eric Laurent0ede8922014-05-09 18:04:42 -07001904 {
1905 Mutex::Autolock _l(command->mLock);
1906 if (command->mWaitStatus) {
1907 command->mWaitStatus = false;
1908 command->mCond.signal();
1909 }
1910 }
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001911 waitTime = -1;
Zach Janga754b4f2015-10-27 01:29:34 +00001912 // release mLock before releasing strong reference on the service as
1913 // AudioPolicyService destructor calls AudioCommandThread::exit() which
1914 // acquires mLock.
1915 mLock.unlock();
1916 svc.clear();
1917 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001918 } else {
1919 waitTime = mAudioCommands[0]->mTime - curTime;
1920 break;
1921 }
1922 }
Zach Janga754b4f2015-10-27 01:29:34 +00001923
1924 // release delayed commands wake lock if the queue is empty
1925 if (mAudioCommands.isEmpty()) {
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07001926 release_wake_lock(mName.string());
Zach Janga754b4f2015-10-27 01:29:34 +00001927 }
1928
1929 // At this stage we have either an empty command queue or the first command in the queue
1930 // has a finite delay. So unless we are exiting it is safe to wait.
1931 if (!exitPending()) {
Eric Laurent59a89232014-06-08 14:14:17 -07001932 ALOGV("AudioCommandThread() going to sleep");
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001933 if (waitTime == -1) {
1934 mWaitWorkCV.wait(mLock);
1935 } else {
1936 mWaitWorkCV.waitRelative(mLock, waitTime);
1937 }
Eric Laurent59a89232014-06-08 14:14:17 -07001938 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001939 }
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07001940 // release delayed commands wake lock before quitting
1941 if (!mAudioCommands.isEmpty()) {
1942 release_wake_lock(mName.string());
1943 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001944 mLock.unlock();
1945 return false;
1946}
1947
1948status_t AudioPolicyService::AudioCommandThread::dump(int fd)
1949{
1950 const size_t SIZE = 256;
1951 char buffer[SIZE];
1952 String8 result;
1953
1954 snprintf(buffer, SIZE, "AudioCommandThread %p Dump\n", this);
1955 result.append(buffer);
1956 write(fd, result.string(), result.size());
1957
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001958 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001959 if (!locked) {
1960 String8 result2(kCmdDeadlockedString);
1961 write(fd, result2.string(), result2.size());
1962 }
1963
1964 snprintf(buffer, SIZE, "- Commands:\n");
1965 result = String8(buffer);
1966 result.append(" Command Time Wait pParam\n");
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001967 for (size_t i = 0; i < mAudioCommands.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001968 mAudioCommands[i]->dump(buffer, SIZE);
1969 result.append(buffer);
1970 }
1971 result.append(" Last Command\n");
Eric Laurent0ede8922014-05-09 18:04:42 -07001972 if (mLastCommand != 0) {
1973 mLastCommand->dump(buffer, SIZE);
1974 result.append(buffer);
1975 } else {
1976 result.append(" none\n");
1977 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001978
1979 write(fd, result.string(), result.size());
1980
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001981 dumpReleaseLock(mLock, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001982
1983 return NO_ERROR;
1984}
1985
Glenn Kastenfff6d712012-01-12 16:38:12 -08001986status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
Eric Laurentde070132010-07-13 04:45:46 -07001987 float volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001988 audio_io_handle_t output,
Eric Laurentde070132010-07-13 04:45:46 -07001989 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001990{
Eric Laurent0ede8922014-05-09 18:04:42 -07001991 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001992 command->mCommand = SET_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07001993 sp<VolumeData> data = new VolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001994 data->mStream = stream;
1995 data->mVolume = volume;
1996 data->mIO = output;
1997 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07001998 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01001999 ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
Eric Laurentde070132010-07-13 04:45:46 -07002000 stream, volume, output);
Eric Laurent0ede8922014-05-09 18:04:42 -07002001 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002002}
2003
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002004status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
Dima Zavinfce7a472011-04-19 22:30:36 -07002005 const char *keyValuePairs,
Eric Laurentde070132010-07-13 04:45:46 -07002006 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002007{
Eric Laurent0ede8922014-05-09 18:04:42 -07002008 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002009 command->mCommand = SET_PARAMETERS;
Eric Laurent0ede8922014-05-09 18:04:42 -07002010 sp<ParametersData> data = new ParametersData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002011 data->mIO = ioHandle;
Dima Zavinfce7a472011-04-19 22:30:36 -07002012 data->mKeyValuePairs = String8(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002013 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002014 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002015 ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
Dima Zavinfce7a472011-04-19 22:30:36 -07002016 keyValuePairs, ioHandle, delayMs);
Eric Laurent0ede8922014-05-09 18:04:42 -07002017 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002018}
2019
2020status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
2021{
Eric Laurent0ede8922014-05-09 18:04:42 -07002022 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002023 command->mCommand = SET_VOICE_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07002024 sp<VoiceVolumeData> data = new VoiceVolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002025 data->mVolume = volume;
2026 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07002027 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01002028 ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
Eric Laurent0ede8922014-05-09 18:04:42 -07002029 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002030}
2031
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002032void AudioPolicyService::AudioCommandThread::setEffectSuspendedCommand(int effectId,
2033 audio_session_t sessionId,
2034 bool suspended)
2035{
2036 sp<AudioCommand> command = new AudioCommand();
2037 command->mCommand = SET_EFFECT_SUSPENDED;
2038 sp<SetEffectSuspendedData> data = new SetEffectSuspendedData();
2039 data->mEffectId = effectId;
2040 data->mSessionId = sessionId;
2041 data->mSuspended = suspended;
2042 command->mParam = data;
2043 ALOGV("AudioCommandThread() adding set suspended effectId %d sessionId %d suspended %d",
2044 effectId, sessionId, suspended);
2045 sendCommand(command);
2046}
2047
2048
Eric Laurentd7fe0862018-07-14 16:48:01 -07002049void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002050{
Eric Laurent0ede8922014-05-09 18:04:42 -07002051 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002052 command->mCommand = STOP_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002053 sp<StopOutputData> data = new StopOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002054 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002055 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002056 ALOGV("AudioCommandThread() adding stop output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002057 sendCommand(command);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002058}
2059
Eric Laurentd7fe0862018-07-14 16:48:01 -07002060void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002061{
Eric Laurent0ede8922014-05-09 18:04:42 -07002062 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002063 command->mCommand = RELEASE_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07002064 sp<ReleaseOutputData> data = new ReleaseOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002065 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01002066 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07002067 ALOGV("AudioCommandThread() adding release output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07002068 sendCommand(command);
2069}
2070
Eric Laurent951f4552014-05-20 10:48:17 -07002071status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
2072 const struct audio_patch *patch,
2073 audio_patch_handle_t *handle,
2074 int delayMs)
2075{
2076 status_t status = NO_ERROR;
2077
2078 sp<AudioCommand> command = new AudioCommand();
2079 command->mCommand = CREATE_AUDIO_PATCH;
2080 CreateAudioPatchData *data = new CreateAudioPatchData();
2081 data->mPatch = *patch;
2082 data->mHandle = *handle;
2083 command->mParam = data;
2084 command->mWaitStatus = true;
2085 ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
2086 status = sendCommand(command, delayMs);
2087 if (status == NO_ERROR) {
2088 *handle = data->mHandle;
2089 }
2090 return status;
2091}
2092
2093status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
2094 int delayMs)
2095{
2096 sp<AudioCommand> command = new AudioCommand();
2097 command->mCommand = RELEASE_AUDIO_PATCH;
2098 ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
2099 data->mHandle = handle;
2100 command->mParam = data;
2101 command->mWaitStatus = true;
2102 ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
2103 return sendCommand(command, delayMs);
2104}
2105
Eric Laurentb52c1522014-05-20 11:27:36 -07002106void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
2107{
2108 sp<AudioCommand> command = new AudioCommand();
2109 command->mCommand = UPDATE_AUDIOPORT_LIST;
2110 ALOGV("AudioCommandThread() adding update audio port list");
2111 sendCommand(command);
2112}
2113
Eric Laurented726cc2021-07-01 14:26:41 +02002114void AudioPolicyService::AudioCommandThread::updateUidStatesCommand()
2115{
2116 sp<AudioCommand> command = new AudioCommand();
2117 command->mCommand = UPDATE_UID_STATES;
2118 ALOGV("AudioCommandThread() adding update UID states");
2119 sendCommand(command);
2120}
2121
Eric Laurentb52c1522014-05-20 11:27:36 -07002122void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
2123{
2124 sp<AudioCommand>command = new AudioCommand();
2125 command->mCommand = UPDATE_AUDIOPATCH_LIST;
2126 ALOGV("AudioCommandThread() adding update audio patch list");
2127 sendCommand(command);
2128}
2129
François Gaffiecfe17322018-11-07 13:41:29 +01002130void AudioPolicyService::AudioCommandThread::changeAudioVolumeGroupCommand(volume_group_t group,
2131 int flags)
2132{
2133 sp<AudioCommand>command = new AudioCommand();
2134 command->mCommand = CHANGED_AUDIOVOLUMEGROUP;
2135 AudioVolumeGroupData *data= new AudioVolumeGroupData();
2136 data->mGroup = group;
2137 data->mFlags = flags;
2138 command->mParam = data;
2139 ALOGV("AudioCommandThread() adding audio volume group changed");
2140 sendCommand(command);
2141}
2142
Eric Laurente1715a42014-05-20 11:30:42 -07002143status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
2144 const struct audio_port_config *config, int delayMs)
2145{
2146 sp<AudioCommand> command = new AudioCommand();
2147 command->mCommand = SET_AUDIOPORT_CONFIG;
2148 SetAudioPortConfigData *data = new SetAudioPortConfigData();
2149 data->mConfig = *config;
2150 command->mParam = data;
2151 command->mWaitStatus = true;
2152 ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
2153 return sendCommand(command, delayMs);
2154}
2155
Jean-Michel Trivide801052015-04-14 19:10:14 -07002156void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002157 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -07002158{
2159 sp<AudioCommand> command = new AudioCommand();
2160 command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
2161 DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
2162 data->mRegId = regId;
2163 data->mState = state;
2164 command->mParam = data;
2165 ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
2166 regId.string(), state);
2167 sendCommand(command);
2168}
2169
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002170void AudioPolicyService::AudioCommandThread::recordingConfigurationUpdateCommand(
Eric Laurenta9f86652018-11-28 17:23:11 -08002171 int event,
2172 const record_client_info_t *clientInfo,
2173 const audio_config_base_t *clientConfig,
2174 std::vector<effect_descriptor_t> clientEffects,
2175 const audio_config_base_t *deviceConfig,
2176 std::vector<effect_descriptor_t> effects,
2177 audio_patch_handle_t patchHandle,
2178 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002179{
2180 sp<AudioCommand>command = new AudioCommand();
2181 command->mCommand = RECORDING_CONFIGURATION_UPDATE;
2182 RecordingConfigurationUpdateData *data = new RecordingConfigurationUpdateData();
2183 data->mEvent = event;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002184 data->mClientInfo = *clientInfo;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002185 data->mClientConfig = *clientConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002186 data->mClientEffects = clientEffects;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08002187 data->mDeviceConfig = *deviceConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08002188 data->mEffects = effects;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002189 data->mPatchHandle = patchHandle;
Eric Laurenta9f86652018-11-28 17:23:11 -08002190 data->mSource = source;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002191 command->mParam = data;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08002192 ALOGV("AudioCommandThread() adding recording configuration update event %d, source %d uid %u",
2193 event, clientInfo->source, clientInfo->uid);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002194 sendCommand(command);
2195}
2196
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002197void AudioPolicyService::AudioCommandThread::audioModulesUpdateCommand()
2198{
2199 sp<AudioCommand> command = new AudioCommand();
2200 command->mCommand = AUDIO_MODULES_UPDATE;
2201 sendCommand(command);
2202}
2203
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002204void AudioPolicyService::AudioCommandThread::routingChangedCommand()
2205{
2206 sp<AudioCommand>command = new AudioCommand();
2207 command->mCommand = ROUTING_UPDATED;
2208 ALOGV("AudioCommandThread() adding routing update");
2209 sendCommand(command);
2210}
2211
Eric Laurent81dd0f52021-07-05 11:54:40 +02002212void AudioPolicyService::AudioCommandThread::checkSpatializerCommand()
2213{
2214 sp<AudioCommand>command = new AudioCommand();
2215 command->mCommand = CHECK_SPATIALIZER;
2216 ALOGV("AudioCommandThread() adding check spatializer");
2217 sendCommand(command);
2218}
2219
Eric Laurent0ede8922014-05-09 18:04:42 -07002220status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
2221{
2222 {
2223 Mutex::Autolock _l(mLock);
2224 insertCommand_l(command, delayMs);
2225 mWaitWorkCV.signal();
2226 }
2227 Mutex::Autolock _l(command->mLock);
2228 while (command->mWaitStatus) {
2229 nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
2230 if (command->mCond.waitRelative(command->mLock, timeOutNs) != NO_ERROR) {
2231 command->mStatus = TIMED_OUT;
2232 command->mWaitStatus = false;
2233 }
2234 }
2235 return command->mStatus;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002236}
2237
Mathias Agopian65ab4712010-07-14 17:59:35 -07002238// insertCommand_l() must be called with mLock held
Eric Laurent0ede8922014-05-09 18:04:42 -07002239void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002240{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002241 ssize_t i; // not size_t because i will count down to -1
Eric Laurent0ede8922014-05-09 18:04:42 -07002242 Vector < sp<AudioCommand> > removedCommands;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002243 command->mTime = systemTime() + milliseconds(delayMs);
2244
2245 // acquire wake lock to make sure delayed commands are processed
Eric Laurentbfb1b832013-01-07 09:53:42 -08002246 if (mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002247 acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.string());
2248 }
2249
2250 // check same pending commands with later time stamps and eliminate them
Ivan Lozano5ff158f2017-10-30 09:06:24 -07002251 for (i = (ssize_t)mAudioCommands.size()-1; i >= 0; i--) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002252 sp<AudioCommand> command2 = mAudioCommands[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07002253 // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
2254 if (command2->mTime <= command->mTime) break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002255
2256 // create audio patch or release audio patch commands are equivalent
2257 // with regard to filtering
2258 if ((command->mCommand == CREATE_AUDIO_PATCH) ||
2259 (command->mCommand == RELEASE_AUDIO_PATCH)) {
2260 if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
2261 (command2->mCommand != RELEASE_AUDIO_PATCH)) {
2262 continue;
2263 }
2264 } else if (command2->mCommand != command->mCommand) continue;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002265
2266 switch (command->mCommand) {
2267 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002268 ParametersData *data = (ParametersData *)command->mParam.get();
2269 ParametersData *data2 = (ParametersData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002270 if (data->mIO != data2->mIO) break;
Steve Block3856b092011-10-20 11:56:00 +01002271 ALOGV("Comparing parameter command %s to new command %s",
Eric Laurentde070132010-07-13 04:45:46 -07002272 data2->mKeyValuePairs.string(), data->mKeyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002273 AudioParameter param = AudioParameter(data->mKeyValuePairs);
2274 AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
2275 for (size_t j = 0; j < param.size(); j++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002276 String8 key;
2277 String8 value;
2278 param.getAt(j, key, value);
2279 for (size_t k = 0; k < param2.size(); k++) {
2280 String8 key2;
2281 String8 value2;
2282 param2.getAt(k, key2, value2);
2283 if (key2 == key) {
2284 param2.remove(key2);
2285 ALOGV("Filtering out parameter %s", key2.string());
2286 break;
2287 }
2288 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002289 }
2290 // if all keys have been filtered out, remove the command.
2291 // otherwise, update the key value pairs
2292 if (param2.size() == 0) {
2293 removedCommands.add(command2);
2294 } else {
2295 data2->mKeyValuePairs = param2.toString();
2296 }
Eric Laurent21e54562013-09-23 12:08:05 -07002297 command->mTime = command2->mTime;
2298 // force delayMs to non 0 so that code below does not request to wait for
2299 // command status as the command is now delayed
2300 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002301 } break;
2302
2303 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002304 VolumeData *data = (VolumeData *)command->mParam.get();
2305 VolumeData *data2 = (VolumeData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002306 if (data->mIO != data2->mIO) break;
2307 if (data->mStream != data2->mStream) break;
Steve Block3856b092011-10-20 11:56:00 +01002308 ALOGV("Filtering out volume command on output %d for stream %d",
Eric Laurentde070132010-07-13 04:45:46 -07002309 data->mIO, data->mStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002310 removedCommands.add(command2);
Eric Laurent21e54562013-09-23 12:08:05 -07002311 command->mTime = command2->mTime;
2312 // force delayMs to non 0 so that code below does not request to wait for
2313 // command status as the command is now delayed
2314 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002315 } break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002316
Eric Laurentbaf35fe2016-07-27 15:36:53 -07002317 case SET_VOICE_VOLUME: {
2318 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
2319 VoiceVolumeData *data2 = (VoiceVolumeData *)command2->mParam.get();
2320 ALOGV("Filtering out voice volume command value %f replaced by %f",
2321 data2->mVolume, data->mVolume);
2322 removedCommands.add(command2);
2323 command->mTime = command2->mTime;
2324 // force delayMs to non 0 so that code below does not request to wait for
2325 // command status as the command is now delayed
2326 delayMs = 1;
2327 } break;
2328
Eric Laurente45b48a2014-09-04 16:40:57 -07002329 case CREATE_AUDIO_PATCH:
2330 case RELEASE_AUDIO_PATCH: {
2331 audio_patch_handle_t handle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002332 struct audio_patch patch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002333 if (command->mCommand == CREATE_AUDIO_PATCH) {
2334 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002335 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002336 } else {
2337 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
Mikhail Naganov7be71d22018-05-23 16:51:46 -07002338 memset(&patch, 0, sizeof(patch));
Eric Laurente45b48a2014-09-04 16:40:57 -07002339 }
2340 audio_patch_handle_t handle2;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002341 struct audio_patch patch2;
Eric Laurente45b48a2014-09-04 16:40:57 -07002342 if (command2->mCommand == CREATE_AUDIO_PATCH) {
2343 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002344 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002345 } else {
2346 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
Glenn Kastenf60b6b62015-07-06 10:53:26 -07002347 memset(&patch2, 0, sizeof(patch2));
Eric Laurente45b48a2014-09-04 16:40:57 -07002348 }
2349 if (handle != handle2) break;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002350 /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
2351 same output. */
2352 if( (command->mCommand == CREATE_AUDIO_PATCH) &&
2353 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
2354 bool isOutputDiff = false;
2355 if (patch.num_sources == patch2.num_sources) {
2356 for (unsigned count = 0; count < patch.num_sources; count++) {
2357 if (patch.sources[count].id != patch2.sources[count].id) {
2358 isOutputDiff = true;
2359 break;
2360 }
2361 }
2362 if (isOutputDiff)
2363 break;
2364 }
2365 }
Eric Laurente45b48a2014-09-04 16:40:57 -07002366 ALOGV("Filtering out %s audio patch command for handle %d",
2367 (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
2368 removedCommands.add(command2);
2369 command->mTime = command2->mTime;
2370 // force delayMs to non 0 so that code below does not request to wait for
2371 // command status as the command is now delayed
2372 delayMs = 1;
2373 } break;
2374
Jean-Michel Trivide801052015-04-14 19:10:14 -07002375 case DYN_POLICY_MIX_STATE_UPDATE: {
2376
2377 } break;
2378
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002379 case RECORDING_CONFIGURATION_UPDATE: {
2380
2381 } break;
2382
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002383 case ROUTING_UPDATED: {
2384
2385 } break;
2386
Mathias Agopian65ab4712010-07-14 17:59:35 -07002387 default:
2388 break;
2389 }
2390 }
2391
2392 // remove filtered commands
2393 for (size_t j = 0; j < removedCommands.size(); j++) {
2394 // removed commands always have time stamps greater than current command
2395 for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002396 if (mAudioCommands[k].get() == removedCommands[j].get()) {
Steve Block3856b092011-10-20 11:56:00 +01002397 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002398 mAudioCommands.removeAt(k);
2399 break;
2400 }
2401 }
2402 }
2403 removedCommands.clear();
2404
Eric Laurentaa79bef2015-01-15 14:33:51 -08002405 // Disable wait for status if delay is not 0.
2406 // Except for create audio patch command because the returned patch handle
2407 // is needed by audio policy manager
2408 if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
Eric Laurentcec4abb2012-07-03 12:23:02 -07002409 command->mWaitStatus = false;
2410 }
Eric Laurentcec4abb2012-07-03 12:23:02 -07002411
Mathias Agopian65ab4712010-07-14 17:59:35 -07002412 // insert command at the right place according to its time stamp
Eric Laurent1e693b52014-07-09 15:03:28 -07002413 ALOGV("inserting command: %d at index %zd, num commands %zu",
2414 command->mCommand, i+1, mAudioCommands.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002415 mAudioCommands.insertAt(command, i + 1);
2416}
2417
2418void AudioPolicyService::AudioCommandThread::exit()
2419{
Steve Block3856b092011-10-20 11:56:00 +01002420 ALOGV("AudioCommandThread::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002421 {
2422 AutoMutex _l(mLock);
2423 requestExit();
2424 mWaitWorkCV.signal();
2425 }
Zach Janga754b4f2015-10-27 01:29:34 +00002426 // Note that we can call it from the thread loop if all other references have been released
2427 // but it will safely return WOULD_BLOCK in this case
Mathias Agopian65ab4712010-07-14 17:59:35 -07002428 requestExitAndWait();
2429}
2430
2431void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
2432{
2433 snprintf(buffer, size, " %02d %06d.%03d %01u %p\n",
2434 mCommand,
2435 (int)ns2s(mTime),
2436 (int)ns2ms(mTime)%1000,
2437 mWaitStatus,
Eric Laurent0ede8922014-05-09 18:04:42 -07002438 mParam.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002439}
2440
Dima Zavinfce7a472011-04-19 22:30:36 -07002441/******* helpers for the service_ops callbacks defined below *********/
2442void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
2443 const char *keyValuePairs,
2444 int delayMs)
2445{
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002446 mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
Dima Zavinfce7a472011-04-19 22:30:36 -07002447 delayMs);
2448}
2449
2450int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
2451 float volume,
2452 audio_io_handle_t output,
2453 int delayMs)
2454{
Glenn Kastenfff6d712012-01-12 16:38:12 -08002455 return (int)mAudioCommandThread->volumeCommand(stream, volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002456 output, delayMs);
Dima Zavinfce7a472011-04-19 22:30:36 -07002457}
2458
Dima Zavinfce7a472011-04-19 22:30:36 -07002459int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
2460{
2461 return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
2462}
2463
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002464void AudioPolicyService::setEffectSuspended(int effectId,
2465 audio_session_t sessionId,
2466 bool suspended)
2467{
2468 mAudioCommandThread->setEffectSuspendedCommand(effectId, sessionId, suspended);
2469}
2470
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002471Status AudioPolicyService::onNewAudioModulesAvailable()
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002472{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07002473 mOutputCommandThread->audioModulesUpdateCommand();
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002474 return Status::ok();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002475}
2476
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002477
Dima Zavinfce7a472011-04-19 22:30:36 -07002478extern "C" {
Eric Laurent2d388ec2014-03-07 13:25:54 -08002479audio_module_handle_t aps_load_hw_module(void *service __unused,
2480 const char *name);
2481audio_io_handle_t aps_open_output(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002482 audio_devices_t *pDevices,
2483 uint32_t *pSamplingRate,
2484 audio_format_t *pFormat,
2485 audio_channel_mask_t *pChannelMask,
2486 uint32_t *pLatencyMs,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002487 audio_output_flags_t flags);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002488
Eric Laurent2d388ec2014-03-07 13:25:54 -08002489audio_io_handle_t aps_open_output_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002490 audio_module_handle_t module,
2491 audio_devices_t *pDevices,
2492 uint32_t *pSamplingRate,
2493 audio_format_t *pFormat,
2494 audio_channel_mask_t *pChannelMask,
2495 uint32_t *pLatencyMs,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002496 audio_output_flags_t flags,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002497 const audio_offload_info_t *offloadInfo);
2498audio_io_handle_t aps_open_dup_output(void *service __unused,
Dima Zavinfce7a472011-04-19 22:30:36 -07002499 audio_io_handle_t output1,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002500 audio_io_handle_t output2);
2501int aps_close_output(void *service __unused, audio_io_handle_t output);
2502int aps_suspend_output(void *service __unused, audio_io_handle_t output);
2503int aps_restore_output(void *service __unused, audio_io_handle_t output);
2504audio_io_handle_t aps_open_input(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002505 audio_devices_t *pDevices,
2506 uint32_t *pSamplingRate,
2507 audio_format_t *pFormat,
2508 audio_channel_mask_t *pChannelMask,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002509 audio_in_acoustics_t acoustics __unused);
2510audio_io_handle_t aps_open_input_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002511 audio_module_handle_t module,
2512 audio_devices_t *pDevices,
2513 uint32_t *pSamplingRate,
2514 audio_format_t *pFormat,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002515 audio_channel_mask_t *pChannelMask);
2516int aps_close_input(void *service __unused, audio_io_handle_t input);
2517int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
Glenn Kastend848eb42016-03-08 13:42:11 -08002518int aps_move_effects(void *service __unused, audio_session_t session,
Dima Zavinfce7a472011-04-19 22:30:36 -07002519 audio_io_handle_t src_output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002520 audio_io_handle_t dst_output);
2521char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
2522 const char *keys);
2523void aps_set_parameters(void *service, audio_io_handle_t io_handle,
2524 const char *kv_pairs, int delay_ms);
2525int aps_set_stream_volume(void *service, audio_stream_type_t stream,
Dima Zavinfce7a472011-04-19 22:30:36 -07002526 float volume, audio_io_handle_t output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002527 int delay_ms);
Eric Laurent2d388ec2014-03-07 13:25:54 -08002528int aps_set_voice_volume(void *service, float volume, int delay_ms);
2529};
Dima Zavinfce7a472011-04-19 22:30:36 -07002530
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08002531} // namespace android