blob: 201273e85679b16f25b97a7c265f3c06322e7191 [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 }
bryant_liuba2b4392014-06-11 16:49:30 +0800130 // load audio processing modules
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000131 sp<AudioPolicyEffects> audioPolicyEffects = new AudioPolicyEffects();
132 sp<UidPolicy> uidPolicy = new UidPolicy(this);
133 sp<SensorPrivacyPolicy> sensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700134 {
135 Mutex::Autolock _l(mLock);
136 mAudioPolicyEffects = audioPolicyEffects;
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000137 mUidPolicy = uidPolicy;
138 mSensorPrivacyPolicy = sensorPrivacyPolicy;
Eric Laurent8b1e80b2014-10-07 09:08:47 -0700139 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000140 uidPolicy->registerSelf();
141 sensorPrivacyPolicy->registerSelf();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700142}
143
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530144void AudioPolicyService::unloadAudioPolicyManager()
145{
146 ALOGV("%s ", __func__);
147 if (mLibraryHandle != nullptr) {
148 dlclose(mLibraryHandle);
149 }
150 mLibraryHandle = nullptr;
151 mCreateAudioPolicyManager = nullptr;
152 mDestroyAudioPolicyManager = nullptr;
153}
154
Mathias Agopian65ab4712010-07-14 17:59:35 -0700155AudioPolicyService::~AudioPolicyService()
156{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700157 mAudioCommandThread->exit();
Eric Laurent657ff612014-05-07 11:58:24 -0700158 mOutputCommandThread->exit();
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700159
Jaideep Sharmaba9053b2021-01-25 21:24:26 +0530160 mDestroyAudioPolicyManager(mAudioPolicyManager);
161 unloadAudioPolicyManager();
162
Eric Laurentdce54a12014-03-10 12:19:46 -0700163 delete mAudioPolicyClient;
Eric Laurentb52c1522014-05-20 11:27:36 -0700164
165 mNotificationClients.clear();
bryant_liuba2b4392014-06-11 16:49:30 +0800166 mAudioPolicyEffects.clear();
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800167
168 mUidPolicy->unregisterSelf();
Michael Groovercfd28302018-12-11 19:16:46 -0800169 mSensorPrivacyPolicy->unregisterSelf();
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000170
171 mUidPolicy.clear();
Michael Groovercfd28302018-12-11 19:16:46 -0800172 mSensorPrivacyPolicy.clear();
Eric Laurentb52c1522014-05-20 11:27:36 -0700173}
174
175// A notification client is always registered by AudioSystem when the client process
176// connects to AudioPolicyService.
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800177Status AudioPolicyService::registerClient(const sp<media::IAudioPolicyServiceClient>& client)
Eric Laurentb52c1522014-05-20 11:27:36 -0700178{
Eric Laurent12590252015-08-21 18:40:20 -0700179 if (client == 0) {
180 ALOGW("%s got NULL client", __FUNCTION__);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800181 return Status::ok();
Eric Laurent12590252015-08-21 18:40:20 -0700182 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800183 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700184
185 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800186 pid_t pid = IPCThreadState::self()->getCallingPid();
187 int64_t token = ((int64_t)uid<<32) | pid;
188
189 if (mNotificationClients.indexOfKey(token) < 0) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700190 sp<NotificationClient> notificationClient = new NotificationClient(this,
191 client,
luochaojiang908c7d72018-06-21 14:58:04 +0800192 uid,
193 pid);
194 ALOGV("registerClient() client %p, uid %d pid %d", client.get(), uid, pid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700195
luochaojiang908c7d72018-06-21 14:58:04 +0800196 mNotificationClients.add(token, notificationClient);
Eric Laurentb52c1522014-05-20 11:27:36 -0700197
Marco Nelissenf8880202014-11-14 07:58:25 -0800198 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurentb52c1522014-05-20 11:27:36 -0700199 binder->linkToDeath(notificationClient);
200 }
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800201 return Status::ok();
Eric Laurentb52c1522014-05-20 11:27:36 -0700202}
203
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800204Status AudioPolicyService::setAudioPortCallbacksEnabled(bool enabled)
Eric Laurente8726fe2015-06-26 09:39:24 -0700205{
206 Mutex::Autolock _l(mNotificationClientsLock);
207
208 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800209 pid_t pid = IPCThreadState::self()->getCallingPid();
210 int64_t token = ((int64_t)uid<<32) | pid;
211
212 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800213 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700214 }
luochaojiang908c7d72018-06-21 14:58:04 +0800215 mNotificationClients.valueFor(token)->setAudioPortCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800216 return Status::ok();
Eric Laurente8726fe2015-06-26 09:39:24 -0700217}
218
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800219Status AudioPolicyService::setAudioVolumeGroupCallbacksEnabled(bool enabled)
François Gaffiecfe17322018-11-07 13:41:29 +0100220{
221 Mutex::Autolock _l(mNotificationClientsLock);
222
223 uid_t uid = IPCThreadState::self()->getCallingUid();
224 pid_t pid = IPCThreadState::self()->getCallingPid();
225 int64_t token = ((int64_t)uid<<32) | pid;
226
227 if (mNotificationClients.indexOfKey(token) < 0) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800228 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100229 }
230 mNotificationClients.valueFor(token)->setAudioVolumeGroupCallbacksEnabled(enabled);
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800231 return Status::ok();
François Gaffiecfe17322018-11-07 13:41:29 +0100232}
233
Eric Laurentb52c1522014-05-20 11:27:36 -0700234// removeNotificationClient() is called when the client process dies.
luochaojiang908c7d72018-06-21 14:58:04 +0800235void AudioPolicyService::removeNotificationClient(uid_t uid, pid_t pid)
Eric Laurentb52c1522014-05-20 11:27:36 -0700236{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000237 bool hasSameUid = false;
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800238 {
239 Mutex::Autolock _l(mNotificationClientsLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800240 int64_t token = ((int64_t)uid<<32) | pid;
241 mNotificationClients.removeItem(token);
luochaojiang908c7d72018-06-21 14:58:04 +0800242 for (size_t i = 0; i < mNotificationClients.size(); i++) {
243 if (mNotificationClients.valueAt(i)->uid() == uid) {
244 hasSameUid = true;
245 break;
246 }
247 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000248 }
249 {
250 Mutex::Autolock _l(mLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800251 if (mAudioPolicyManager && !hasSameUid) {
Eric Laurent10b71232018-04-13 18:14:44 -0700252 // called from binder death notification: no need to clear caller identity
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700253 mAudioPolicyManager->releaseResourcesForUid(uid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700254 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800255 }
Eric Laurentb52c1522014-05-20 11:27:36 -0700256}
257
258void AudioPolicyService::onAudioPortListUpdate()
259{
260 mOutputCommandThread->updateAudioPortListCommand();
261}
262
263void AudioPolicyService::doOnAudioPortListUpdate()
264{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800265 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700266 for (size_t i = 0; i < mNotificationClients.size(); i++) {
267 mNotificationClients.valueAt(i)->onAudioPortListUpdate();
268 }
269}
270
271void AudioPolicyService::onAudioPatchListUpdate()
272{
273 mOutputCommandThread->updateAudioPatchListCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700274}
275
Eric Laurentb52c1522014-05-20 11:27:36 -0700276void AudioPolicyService::doOnAudioPatchListUpdate()
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)->onAudioPatchListUpdate();
281 }
282}
283
François Gaffiecfe17322018-11-07 13:41:29 +0100284void AudioPolicyService::onAudioVolumeGroupChanged(volume_group_t group, int flags)
285{
286 mOutputCommandThread->changeAudioVolumeGroupCommand(group, flags);
287}
288
289void AudioPolicyService::doOnAudioVolumeGroupChanged(volume_group_t group, int flags)
290{
291 Mutex::Autolock _l(mNotificationClientsLock);
292 for (size_t i = 0; i < mNotificationClients.size(); i++) {
293 mNotificationClients.valueAt(i)->onAudioVolumeGroupChanged(group, flags);
294 }
295}
296
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700297void AudioPolicyService::onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700298{
299 ALOGV("AudioPolicyService::onDynamicPolicyMixStateUpdate(%s, %d)",
300 regId.string(), state);
301 mOutputCommandThread->dynamicPolicyMixStateUpdateCommand(regId, state);
302}
303
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700304void AudioPolicyService::doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700305{
306 Mutex::Autolock _l(mNotificationClientsLock);
307 for (size_t i = 0; i < mNotificationClients.size(); i++) {
308 mNotificationClients.valueAt(i)->onDynamicPolicyMixStateUpdate(regId, state);
309 }
310}
311
Eric Laurenta9f86652018-11-28 17:23:11 -0800312void AudioPolicyService::onRecordingConfigurationUpdate(
313 int event,
314 const record_client_info_t *clientInfo,
315 const audio_config_base_t *clientConfig,
316 std::vector<effect_descriptor_t> clientEffects,
317 const audio_config_base_t *deviceConfig,
318 std::vector<effect_descriptor_t> effects,
319 audio_patch_handle_t patchHandle,
320 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800321{
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800322 mOutputCommandThread->recordingConfigurationUpdateCommand(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800323 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800324}
325
Eric Laurenta9f86652018-11-28 17:23:11 -0800326void AudioPolicyService::doOnRecordingConfigurationUpdate(
327 int event,
328 const record_client_info_t *clientInfo,
329 const audio_config_base_t *clientConfig,
330 std::vector<effect_descriptor_t> clientEffects,
331 const audio_config_base_t *deviceConfig,
332 std::vector<effect_descriptor_t> effects,
333 audio_patch_handle_t patchHandle,
334 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800335{
336 Mutex::Autolock _l(mNotificationClientsLock);
337 for (size_t i = 0; i < mNotificationClients.size(); i++) {
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800338 mNotificationClients.valueAt(i)->onRecordingConfigurationUpdate(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800339 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800340 }
341}
342
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700343void AudioPolicyService::onRoutingUpdated()
344{
345 mOutputCommandThread->routingChangedCommand();
346}
347
348void AudioPolicyService::doOnRoutingUpdated()
349{
350 Mutex::Autolock _l(mNotificationClientsLock);
351 for (size_t i = 0; i < mNotificationClients.size(); i++) {
352 mNotificationClients.valueAt(i)->onRoutingUpdated();
353 }
354}
355
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800356status_t AudioPolicyService::clientCreateAudioPatch(const struct audio_patch *patch,
357 audio_patch_handle_t *handle,
358 int delayMs)
359{
360 return mAudioCommandThread->createAudioPatchCommand(patch, handle, delayMs);
361}
362
363status_t AudioPolicyService::clientReleaseAudioPatch(audio_patch_handle_t handle,
364 int delayMs)
365{
366 return mAudioCommandThread->releaseAudioPatchCommand(handle, delayMs);
367}
368
Eric Laurente1715a42014-05-20 11:30:42 -0700369status_t AudioPolicyService::clientSetAudioPortConfig(const struct audio_port_config *config,
370 int delayMs)
371{
372 return mAudioCommandThread->setAudioPortConfigCommand(config, delayMs);
373}
374
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800375AudioPolicyService::NotificationClient::NotificationClient(
376 const sp<AudioPolicyService>& service,
377 const sp<media::IAudioPolicyServiceClient>& client,
378 uid_t uid,
379 pid_t pid)
luochaojiang908c7d72018-06-21 14:58:04 +0800380 : mService(service), mUid(uid), mPid(pid), mAudioPolicyServiceClient(client),
François Gaffiecfe17322018-11-07 13:41:29 +0100381 mAudioPortCallbacksEnabled(false), mAudioVolumeGroupCallbacksEnabled(false)
Eric Laurentb52c1522014-05-20 11:27:36 -0700382{
383}
384
385AudioPolicyService::NotificationClient::~NotificationClient()
386{
387}
388
389void AudioPolicyService::NotificationClient::binderDied(const wp<IBinder>& who __unused)
390{
391 sp<NotificationClient> keep(this);
392 sp<AudioPolicyService> service = mService.promote();
393 if (service != 0) {
luochaojiang908c7d72018-06-21 14:58:04 +0800394 service->removeNotificationClient(mUid, mPid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700395 }
396}
397
398void AudioPolicyService::NotificationClient::onAudioPortListUpdate()
399{
Eric Laurente8726fe2015-06-26 09:39:24 -0700400 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700401 mAudioPolicyServiceClient->onAudioPortListUpdate();
402 }
403}
404
405void AudioPolicyService::NotificationClient::onAudioPatchListUpdate()
406{
Eric Laurente8726fe2015-06-26 09:39:24 -0700407 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700408 mAudioPolicyServiceClient->onAudioPatchListUpdate();
409 }
410}
Eric Laurent57dae992011-07-24 13:36:09 -0700411
François Gaffiecfe17322018-11-07 13:41:29 +0100412void AudioPolicyService::NotificationClient::onAudioVolumeGroupChanged(volume_group_t group,
413 int flags)
414{
415 if (mAudioPolicyServiceClient != 0 && mAudioVolumeGroupCallbacksEnabled) {
416 mAudioPolicyServiceClient->onAudioVolumeGroupChanged(group, flags);
417 }
418}
419
420
Jean-Michel Trivide801052015-04-14 19:10:14 -0700421void AudioPolicyService::NotificationClient::onDynamicPolicyMixStateUpdate(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700422 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700423{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700424 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800425 mAudioPolicyServiceClient->onDynamicPolicyMixStateUpdate(
426 legacy2aidl_String8_string(regId).value(), state);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800427 }
428}
429
430void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate(
Eric Laurenta9f86652018-11-28 17:23:11 -0800431 int event,
432 const record_client_info_t *clientInfo,
433 const audio_config_base_t *clientConfig,
434 std::vector<effect_descriptor_t> clientEffects,
435 const audio_config_base_t *deviceConfig,
436 std::vector<effect_descriptor_t> effects,
437 audio_patch_handle_t patchHandle,
438 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800439{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700440 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Ytai Ben-Tsvi7e7a79d2020-12-15 16:48:16 -0800441 status_t status = [&]() -> status_t {
442 int32_t eventAidl = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(event));
443 media::RecordClientInfo clientInfoAidl = VALUE_OR_RETURN_STATUS(
444 legacy2aidl_record_client_info_t_RecordClientInfo(*clientInfo));
445 media::AudioConfigBase clientConfigAidl = VALUE_OR_RETURN_STATUS(
446 legacy2aidl_audio_config_base_t_AudioConfigBase(*clientConfig));
447 std::vector<media::EffectDescriptor> clientEffectsAidl = VALUE_OR_RETURN_STATUS(
448 convertContainer<std::vector<media::EffectDescriptor>>(
449 clientEffects,
450 legacy2aidl_effect_descriptor_t_EffectDescriptor));
451 media::AudioConfigBase deviceConfigAidl = VALUE_OR_RETURN_STATUS(
452 legacy2aidl_audio_config_base_t_AudioConfigBase(*deviceConfig));
453 std::vector<media::EffectDescriptor> effectsAidl = VALUE_OR_RETURN_STATUS(
454 convertContainer<std::vector<media::EffectDescriptor>>(
455 effects,
456 legacy2aidl_effect_descriptor_t_EffectDescriptor));
457 int32_t patchHandleAidl = VALUE_OR_RETURN_STATUS(
458 legacy2aidl_audio_patch_handle_t_int32_t(patchHandle));
459 media::AudioSourceType sourceAidl = VALUE_OR_RETURN_STATUS(
460 legacy2aidl_audio_source_t_AudioSourceType(source));
461 return aidl_utils::statusTFromBinderStatus(
462 mAudioPolicyServiceClient->onRecordingConfigurationUpdate(eventAidl,
463 clientInfoAidl,
464 clientConfigAidl,
465 clientEffectsAidl,
466 deviceConfigAidl,
467 effectsAidl,
468 patchHandleAidl,
469 sourceAidl));
470 }();
471 ALOGW_IF(status != OK, "onRecordingConfigurationUpdate() failed: %d", status);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700472 }
473}
474
Eric Laurente8726fe2015-06-26 09:39:24 -0700475void AudioPolicyService::NotificationClient::setAudioPortCallbacksEnabled(bool enabled)
476{
477 mAudioPortCallbacksEnabled = enabled;
478}
479
François Gaffiecfe17322018-11-07 13:41:29 +0100480void AudioPolicyService::NotificationClient::setAudioVolumeGroupCallbacksEnabled(bool enabled)
481{
482 mAudioVolumeGroupCallbacksEnabled = enabled;
483}
Eric Laurente8726fe2015-06-26 09:39:24 -0700484
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -0700485void AudioPolicyService::NotificationClient::onRoutingUpdated()
486{
487 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
488 mAudioPolicyServiceClient->onRoutingUpdated();
489 }
490}
491
Mathias Agopian65ab4712010-07-14 17:59:35 -0700492void AudioPolicyService::binderDied(const wp<IBinder>& who) {
Glenn Kasten411e4472012-11-02 10:00:06 -0700493 ALOGW("binderDied() %p, calling pid %d", who.unsafe_get(),
Eric Laurentde070132010-07-13 04:45:46 -0700494 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700495}
496
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000497static bool dumpTryLock(Mutex& mutex) ACQUIRE(mutex) NO_THREAD_SAFETY_ANALYSIS
Mathias Agopian65ab4712010-07-14 17:59:35 -0700498{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000499 return mutex.timedLock(kDumpLockTimeoutNs) == NO_ERROR;
500}
501
502static void dumpReleaseLock(Mutex& mutex, bool locked) RELEASE(mutex) NO_THREAD_SAFETY_ANALYSIS
503{
504 if (locked) mutex.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700505}
506
507status_t AudioPolicyService::dumpInternals(int fd)
508{
509 const size_t SIZE = 256;
510 char buffer[SIZE];
511 String8 result;
512
Eric Laurentdce54a12014-03-10 12:19:46 -0700513 snprintf(buffer, SIZE, "AudioPolicyManager: %p\n", mAudioPolicyManager);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700514 result.append(buffer);
515 snprintf(buffer, SIZE, "Command Thread: %p\n", mAudioCommandThread.get());
516 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700517
Hayden Gomes524159d2019-12-23 14:41:47 -0800518 snprintf(buffer, SIZE, "Supported System Usages:\n");
519 result.append(buffer);
520 for (std::vector<audio_usage_t>::iterator it = mSupportedSystemUsages.begin();
521 it != mSupportedSystemUsages.end(); ++it) {
522 snprintf(buffer, SIZE, "\t%d\n", *it);
523 result.append(buffer);
524 }
525
Mathias Agopian65ab4712010-07-14 17:59:35 -0700526 write(fd, result.string(), result.size());
527 return NO_ERROR;
528}
529
Eric Laurente8c8b432018-10-17 10:08:02 -0700530void AudioPolicyService::updateUidStates()
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800531{
Eric Laurente8c8b432018-10-17 10:08:02 -0700532 Mutex::Autolock _l(mLock);
533 updateUidStates_l();
534}
535
536void AudioPolicyService::updateUidStates_l()
537{
Eric Laurent4eb58f12018-12-07 16:41:02 -0800538// Go over all active clients and allow capture (does not force silence) in the
539// following cases:
Evan Severson1f700cd2021-02-10 13:10:37 -0800540// The client is the assistant
541// AND an accessibility service is on TOP or a RTT call is active
Eric Laurent589171c2019-07-25 18:04:29 -0700542// AND the source is VOICE_RECOGNITION or HOTWORD
Evan Severson1f700cd2021-02-10 13:10:37 -0800543// OR uses VOICE_RECOGNITION AND is on TOP
544// OR uses HOTWORD
545// AND there is no active privacy sensitive capture or call
546// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
547// OR The client is an accessibility service
548// AND Is on TOP
549// AND the source is VOICE_RECOGNITION or HOTWORD
550// OR The assistant is not on TOP
Eric Laurent589171c2019-07-25 18:04:29 -0700551// AND there is no active privacy sensitive capture or call
552// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Evan Severson1f700cd2021-02-10 13:10:37 -0800553// AND is on TOP
554// AND the source is VOICE_RECOGNITION or HOTWORD
555// OR the client source is virtual (remote submix, call audio TX or RX...)
556// OR the client source is HOTWORD
557// AND is on TOP
558// OR all active clients are using HOTWORD source
559// AND no call is active
560// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
561// OR the client is the current InputMethodService
562// AND a RTT call is active AND the source is VOICE_RECOGNITION
563// OR Any client
564// AND The assistant is not on TOP
565// AND is on TOP or latest started
566// AND there is no active privacy sensitive capture or call
567// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4eb58f12018-12-07 16:41:02 -0800568
Eric Laurent4e947da2019-10-17 15:24:06 -0700569
Eric Laurent4eb58f12018-12-07 16:41:02 -0800570 sp<AudioRecordClient> topActive;
571 sp<AudioRecordClient> latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800572 sp<AudioRecordClient> topSensitiveActive;
Eric Laurentb809a752020-06-29 09:53:13 -0700573 sp<AudioRecordClient> latestSensitiveActiveOrComm;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700574
Eric Laurenta46bedb2018-12-07 18:01:26 -0800575 nsecs_t topStartNs = 0;
576 nsecs_t latestStartNs = 0;
Eric Laurentc21d5692020-02-25 10:24:36 -0800577 nsecs_t topSensitiveStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800578 nsecs_t latestSensitiveStartNs = 0;
579 bool isA11yOnTop = mUidPolicy->isA11yOnTop();
580 bool isAssistantOnTop = false;
581 bool isSensitiveActive = false;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700582 bool isInCall = mPhoneState == AUDIO_MODE_IN_CALL;
Eric Laurentc21d5692020-02-25 10:24:36 -0800583 bool isInCommunication = mPhoneState == AUDIO_MODE_IN_COMMUNICATION;
584 bool rttCallActive = (isInCall || isInCommunication)
Eric Laurent6ede98f2019-06-11 14:50:30 -0700585 && mUidPolicy->isRttEnabled();
Eric Laurent4e947da2019-10-17 15:24:06 -0700586 bool onlyHotwordActive = true;
Eric Laurentb809a752020-06-29 09:53:13 -0700587 bool isPhoneStateOwnerActive = false;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800588
Michael Groovercfd28302018-12-11 19:16:46 -0800589 // if Sensor Privacy is enabled then all recordings should be silenced.
590 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
591 silenceAllRecordings_l();
592 return;
593 }
594
Eric Laurente8c8b432018-10-17 10:08:02 -0700595 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
596 sp<AudioRecordClient> current = mAudioRecordClients[i];
Svet Ganov33761132021-05-13 22:51:08 +0000597 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
598 current->attributionSource.uid));
Evan Severson1f700cd2021-02-10 13:10:37 -0800599 if (!current->active) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700600 continue;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800601 }
Eric Laurent1ff16a72019-03-14 18:35:04 -0700602
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700603 app_state_t appState = apmStatFromAmState(mUidPolicy->getUidState(currentUid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700604 // clients which app is in IDLE state are not eligible for top active or
605 // latest active
606 if (appState == APP_STATE_IDLE) {
607 continue;
608 }
609
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700610 bool isAccessibility = mUidPolicy->isA11yUid(currentUid);
Eric Laurent14a88632020-07-16 12:28:30 -0700611 // Clients capturing for Accessibility services or virtual sources are not considered
Eric Laurentc21d5692020-02-25 10:24:36 -0800612 // for top or latest active to avoid masking regular clients started before
Eric Laurent14a88632020-07-16 12:28:30 -0700613 if (!isAccessibility && !isVirtualSource(current->attributes.source)) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700614 bool isAssistant = mUidPolicy->isAssistantUid(currentUid);
Eric Laurentc21d5692020-02-25 10:24:36 -0800615 bool isPrivacySensitive =
616 (current->attributes.flags & AUDIO_FLAG_CAPTURE_PRIVATE) != 0;
Eric Laurentb809a752020-06-29 09:53:13 -0700617
Eric Laurentc21d5692020-02-25 10:24:36 -0800618 if (appState == APP_STATE_TOP) {
619 if (isPrivacySensitive) {
620 if (current->startTimeNs > topSensitiveStartNs) {
621 topSensitiveActive = current;
622 topSensitiveStartNs = current->startTimeNs;
623 }
624 } else {
625 if (current->startTimeNs > topStartNs) {
626 topActive = current;
627 topStartNs = current->startTimeNs;
628 }
629 }
630 if (isAssistant) {
631 isAssistantOnTop = true;
632 }
Eric Laurenta46bedb2018-12-07 18:01:26 -0800633 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800634 // Clients capturing for HOTWORD are not considered
635 // for latest active to avoid masking regular clients started before
636 if (!(current->attributes.source == AUDIO_SOURCE_HOTWORD
637 || ((isA11yOnTop || rttCallActive) && isAssistant))) {
638 if (isPrivacySensitive) {
Eric Laurentb809a752020-06-29 09:53:13 -0700639 // if audio mode is IN_COMMUNICATION, make sure the audio mode owner
640 // is marked latest sensitive active even if another app qualifies.
641 if (current->startTimeNs > latestSensitiveStartNs
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700642 || (isInCommunication && currentUid == mPhoneStateOwnerUid)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700643 if (!isInCommunication || latestSensitiveActiveOrComm == nullptr
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700644 || VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000645 latestSensitiveActiveOrComm->attributionSource.uid))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700646 != mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700647 latestSensitiveActiveOrComm = current;
648 latestSensitiveStartNs = current->startTimeNs;
649 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800650 }
651 isSensitiveActive = true;
652 } else {
653 if (current->startTimeNs > latestStartNs) {
654 latestActive = current;
655 latestStartNs = current->startTimeNs;
656 }
657 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800658 }
659 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700660 if (current->attributes.source != AUDIO_SOURCE_HOTWORD) {
661 onlyHotwordActive = false;
662 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700663 if (currentUid == mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700664 isPhoneStateOwnerActive = true;
665 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800666 }
667
Eric Laurent1ff16a72019-03-14 18:35:04 -0700668 // if no active client with UI on Top, consider latest active as top
669 if (topActive == nullptr) {
670 topActive = latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800671 topStartNs = latestStartNs;
672 }
673 if (topSensitiveActive == nullptr) {
Eric Laurentb809a752020-06-29 09:53:13 -0700674 topSensitiveActive = latestSensitiveActiveOrComm;
Eric Laurentc21d5692020-02-25 10:24:36 -0800675 topSensitiveStartNs = latestSensitiveStartNs;
Eric Laurentb809a752020-06-29 09:53:13 -0700676 } else if (latestSensitiveActiveOrComm != nullptr) {
677 // if audio mode is IN_COMMUNICATION, favor audio mode owner over an app with
678 // foreground UI in case both are capturing with privacy sensitive flag.
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700679 uid_t latestActiveUid = VALUE_OR_FATAL(
Svet Ganov33761132021-05-13 22:51:08 +0000680 aidl2legacy_int32_t_uid_t(latestSensitiveActiveOrComm->attributionSource.uid));
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700681 if (isInCommunication && latestActiveUid == mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700682 topSensitiveActive = latestSensitiveActiveOrComm;
683 topSensitiveStartNs = latestSensitiveStartNs;
684 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800685 }
686
687 // If both privacy sensitive and regular capture are active:
688 // if the regular capture is privileged
689 // allow concurrency
690 // else
691 // favor the privacy sensitive case
692 if (topActive != nullptr && topSensitiveActive != nullptr
Ricardo Correa57a37692020-03-23 17:27:25 -0700693 && !topActive->canCaptureOutput) {
Eric Laurentc21d5692020-02-25 10:24:36 -0800694 topActive = nullptr;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800695 }
696
697 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
698 sp<AudioRecordClient> current = mAudioRecordClients[i];
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700699 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000700 current->attributionSource.uid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700701 if (!current->active) {
702 continue;
703 }
704
Eric Laurent4eb58f12018-12-07 16:41:02 -0800705 audio_source_t source = current->attributes.source;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700706 bool isTopOrLatestActive = topActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +0000707 current->attributionSource.uid == topActive->attributionSource.uid;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700708 bool isTopOrLatestSensitive = topSensitiveActive == nullptr ? false :
Svet Ganov33761132021-05-13 22:51:08 +0000709 current->attributionSource.uid == topSensitiveActive->attributionSource.uid;
Eric Laurentc21d5692020-02-25 10:24:36 -0800710
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000711 auto canCaptureIfInCallOrCommunication = [&](const auto &recordClient) REQUIRES(mLock) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700712 uid_t recordUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
Svet Ganov33761132021-05-13 22:51:08 +0000713 recordClient->attributionSource.uid));
Ricardo Correa57a37692020-03-23 17:27:25 -0700714 bool canCaptureCall = recordClient->canCaptureOutput;
Eric Laurentb809a752020-06-29 09:53:13 -0700715 bool canCaptureCommunication = recordClient->canCaptureOutput
716 || !isPhoneStateOwnerActive
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700717 || recordUid == mPhoneStateOwnerUid;
Eric Laurentb809a752020-06-29 09:53:13 -0700718 return !(isInCall && !canCaptureCall)
719 && !(isInCommunication && !canCaptureCommunication);
Eric Laurentc21d5692020-02-25 10:24:36 -0800720 };
Eric Laurent1ff16a72019-03-14 18:35:04 -0700721
722 // By default allow capture if:
723 // The assistant is not on TOP
Eric Laurenta171e352019-05-07 13:04:45 -0700724 // AND is on TOP or latest started
Eric Laurent1ff16a72019-03-14 18:35:04 -0700725 // AND there is no active privacy sensitive capture or call
726 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
727 bool allowCapture = !isAssistantOnTop
Eric Laurentc21d5692020-02-25 10:24:36 -0800728 && (isTopOrLatestActive || isTopOrLatestSensitive)
729 && !(isSensitiveActive
Ricardo Correa57a37692020-03-23 17:27:25 -0700730 && !(isTopOrLatestSensitive || current->canCaptureOutput))
Eric Laurentc21d5692020-02-25 10:24:36 -0800731 && canCaptureIfInCallOrCommunication(current);
Eric Laurent2dc962b2019-03-01 08:25:25 -0800732
733 if (isVirtualSource(source)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700734 // Allow capture for virtual (remote submix, call audio TX or RX...) sources
735 allowCapture = true;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700736 } else if (mUidPolicy->isAssistantUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700737 // For assistant allow capture if:
Eric Laurent6ede98f2019-06-11 14:50:30 -0700738 // An accessibility service is on TOP or a RTT call is active
Eric Laurent1ff16a72019-03-14 18:35:04 -0700739 // AND the source is VOICE_RECOGNITION or HOTWORD
Eric Laurenta171e352019-05-07 13:04:45 -0700740 // OR is on TOP AND uses VOICE_RECOGNITION
Eric Laurent1ff16a72019-03-14 18:35:04 -0700741 // OR uses HOTWORD
742 // AND there is no active privacy sensitive capture or call
743 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent6ede98f2019-06-11 14:50:30 -0700744 if (isA11yOnTop || rttCallActive) {
Eric Laurent4eb58f12018-12-07 16:41:02 -0800745 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700746 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800747 }
748 } else {
Eric Laurenta171e352019-05-07 13:04:45 -0700749 if (((isAssistantOnTop && source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
Eric Laurentc21d5692020-02-25 10:24:36 -0800750 source == AUDIO_SOURCE_HOTWORD)
Ricardo Correa57a37692020-03-23 17:27:25 -0700751 && !(isSensitiveActive && !current->canCaptureOutput)
Eric Laurentc21d5692020-02-25 10:24:36 -0800752 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700753 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800754 }
755 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700756 } else if (mUidPolicy->isA11yUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700757 // For accessibility service allow capture if:
Eric Laurent47670c92019-08-28 16:59:05 -0700758 // The assistant is not on TOP
759 // AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -0700760 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent47670c92019-08-28 16:59:05 -0700761 // OR
762 // Is on TOP AND the source is VOICE_RECOGNITION or HOTWORD
763 if (!isAssistantOnTop
Ricardo Correa57a37692020-03-23 17:27:25 -0700764 && !(isSensitiveActive && !current->canCaptureOutput)
Eric Laurentc21d5692020-02-25 10:24:36 -0800765 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent47670c92019-08-28 16:59:05 -0700766 allowCapture = true;
767 }
Eric Laurent589171c2019-07-25 18:04:29 -0700768 if (isA11yOnTop) {
769 if (source == AUDIO_SOURCE_VOICE_RECOGNITION || source == AUDIO_SOURCE_HOTWORD) {
770 allowCapture = true;
771 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800772 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700773 } else if (source == AUDIO_SOURCE_HOTWORD) {
774 // For HOTWORD source allow capture when not on TOP if:
775 // All active clients are using HOTWORD source
776 // AND no call is active
777 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurentc21d5692020-02-25 10:24:36 -0800778 if (onlyHotwordActive
779 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent4e947da2019-10-17 15:24:06 -0700780 allowCapture = true;
781 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700782 } else if (mUidPolicy->isCurrentImeUid(currentUid)) {
Kohsuke Yatoha623a132020-03-24 20:10:26 -0700783 // For current InputMethodService allow capture if:
784 // A RTT call is active AND the source is VOICE_RECOGNITION
785 if (rttCallActive && source == AUDIO_SOURCE_VOICE_RECOGNITION) {
786 allowCapture = true;
787 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800788 }
Eric Laurent8c7ef892021-06-10 13:32:16 +0200789 setAppState_l(current,
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700790 allowCapture ? apmStatFromAmState(mUidPolicy->getUidState(currentUid)) :
Eric Laurent1ff16a72019-03-14 18:35:04 -0700791 APP_STATE_IDLE);
Eric Laurente8c8b432018-10-17 10:08:02 -0700792 }
793}
794
Michael Groovercfd28302018-12-11 19:16:46 -0800795void AudioPolicyService::silenceAllRecordings_l() {
796 for (size_t i = 0; i < mAudioRecordClients.size(); i++) {
797 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -0700798 if (!isVirtualSource(current->attributes.source)) {
Eric Laurent8c7ef892021-06-10 13:32:16 +0200799 setAppState_l(current, APP_STATE_IDLE);
Eric Laurent1ff16a72019-03-14 18:35:04 -0700800 }
Michael Groovercfd28302018-12-11 19:16:46 -0800801 }
802}
803
Eric Laurente8c8b432018-10-17 10:08:02 -0700804/* static */
805app_state_t AudioPolicyService::apmStatFromAmState(int amState) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700806
807 if (amState == ActivityManager::PROCESS_STATE_UNKNOWN) {
Eric Laurente8c8b432018-10-17 10:08:02 -0700808 return APP_STATE_IDLE;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700809 } else if (amState <= ActivityManager::PROCESS_STATE_TOP) {
810 // include persistent services
811 return APP_STATE_TOP;
Eric Laurente8c8b432018-10-17 10:08:02 -0700812 }
813 return APP_STATE_FOREGROUND;
814}
815
Eric Laurent4eb58f12018-12-07 16:41:02 -0800816/* static */
Eric Laurent2dc962b2019-03-01 08:25:25 -0800817bool AudioPolicyService::isVirtualSource(audio_source_t source)
Eric Laurent4eb58f12018-12-07 16:41:02 -0800818{
819 switch (source) {
820 case AUDIO_SOURCE_VOICE_UPLINK:
821 case AUDIO_SOURCE_VOICE_DOWNLINK:
822 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent2dc962b2019-03-01 08:25:25 -0800823 case AUDIO_SOURCE_REMOTE_SUBMIX:
824 case AUDIO_SOURCE_FM_TUNER:
Eric Laurent68eb2122020-04-30 17:40:57 -0700825 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent4eb58f12018-12-07 16:41:02 -0800826 return true;
827 default:
828 break;
829 }
830 return false;
831}
832
Eric Laurent8c7ef892021-06-10 13:32:16 +0200833void AudioPolicyService::setAppState_l(sp<AudioRecordClient> client, app_state_t state)
Eric Laurente8c8b432018-10-17 10:08:02 -0700834{
835 AutoCallerClear acc;
836
837 if (mAudioPolicyManager) {
Eric Laurent8c7ef892021-06-10 13:32:16 +0200838 mAudioPolicyManager->setAppState(client->portId, state);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700839 }
840 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
841 if (af) {
Eric Laurentf32108e2018-10-04 17:22:04 -0700842 bool silenced = state == APP_STATE_IDLE;
Eric Laurent8c7ef892021-06-10 13:32:16 +0200843 if (client->silenced != silenced) {
844 if (client->active) {
845 if (silenced) {
846 finishRecording(client->attributionSource, client->attributes.source);
847 } else {
848 std::stringstream msg;
849 msg << "Audio recording un-silenced on session " << client->session;
850 if (!startRecording(client->attributionSource, String16(msg.str().c_str()),
851 client->attributes.source)) {
852 silenced = true;
853 }
854 }
855 }
856 af->setRecordSilenced(client->portId, silenced);
857 client->silenced = silenced;
858 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700859 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800860}
861
Glenn Kasten0f11b512014-01-31 16:18:54 -0800862status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700863{
Glenn Kasten44deb052012-02-05 18:09:08 -0800864 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700865 dumpPermissionDenial(fd);
866 } else {
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000867 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700868 if (!locked) {
869 String8 result(kDeadlockedString);
870 write(fd, result.string(), result.size());
871 }
872
873 dumpInternals(fd);
Glenn Kasten9d1f02d2012-02-08 17:47:58 -0800874 if (mAudioCommandThread != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700875 mAudioCommandThread->dump(fd);
876 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700877
Eric Laurentdce54a12014-03-10 12:19:46 -0700878 if (mAudioPolicyManager) {
879 mAudioPolicyManager->dump(fd);
880 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700881
Kevin Rocard8be94972019-02-22 13:26:25 -0800882 mPackageManager.dump(fd);
883
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000884 dumpReleaseLock(mLock, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700885 }
886 return NO_ERROR;
887}
888
889status_t AudioPolicyService::dumpPermissionDenial(int fd)
890{
891 const size_t SIZE = 256;
892 char buffer[SIZE];
893 String8 result;
894 snprintf(buffer, SIZE, "Permission Denial: "
895 "can't dump AudioPolicyService from pid=%d, uid=%d\n",
896 IPCThreadState::self()->getCallingPid(),
897 IPCThreadState::self()->getCallingUid());
898 result.append(buffer);
899 write(fd, result.string(), result.size());
900 return NO_ERROR;
901}
902
903status_t AudioPolicyService::onTransact(
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800904 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800905 // make sure transactions reserved to AudioFlinger do not come from other processes
906 switch (code) {
907 case TRANSACTION_startOutput:
908 case TRANSACTION_stopOutput:
909 case TRANSACTION_releaseOutput:
910 case TRANSACTION_getInputForAttr:
911 case TRANSACTION_startInput:
912 case TRANSACTION_stopInput:
913 case TRANSACTION_releaseInput:
914 case TRANSACTION_getOutputForEffect:
915 case TRANSACTION_registerEffect:
916 case TRANSACTION_unregisterEffect:
917 case TRANSACTION_setEffectEnabled:
918 case TRANSACTION_getStrategyForStream:
919 case TRANSACTION_getOutputForAttr:
920 case TRANSACTION_moveEffectsToIo:
921 ALOGW("%s: transaction %d received from PID %d",
922 __func__, code, IPCThreadState::self()->getCallingPid());
923 return INVALID_OPERATION;
924 default:
925 break;
926 }
927
928 // make sure the following transactions come from system components
929 switch (code) {
930 case TRANSACTION_setDeviceConnectionState:
931 case TRANSACTION_handleDeviceConfigChange:
932 case TRANSACTION_setPhoneState:
933//FIXME: Allow setForceUse calls from system apps until a better use case routing API is available
934// case TRANSACTION_setForceUse:
935 case TRANSACTION_initStreamVolume:
936 case TRANSACTION_setStreamVolumeIndex:
937 case TRANSACTION_setVolumeIndexForAttributes:
938 case TRANSACTION_getStreamVolumeIndex:
939 case TRANSACTION_getVolumeIndexForAttributes:
940 case TRANSACTION_getMinVolumeIndexForAttributes:
941 case TRANSACTION_getMaxVolumeIndexForAttributes:
942 case TRANSACTION_isStreamActive:
943 case TRANSACTION_isStreamActiveRemotely:
944 case TRANSACTION_isSourceActive:
945 case TRANSACTION_getDevicesForStream:
946 case TRANSACTION_registerPolicyMixes:
947 case TRANSACTION_setMasterMono:
948 case TRANSACTION_getSurroundFormats:
Kriti Dang6537def2021-03-02 13:46:59 +0100949 case TRANSACTION_getReportedSurroundFormats:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800950 case TRANSACTION_setSurroundFormatEnabled:
951 case TRANSACTION_setAssistantUid:
952 case TRANSACTION_setA11yServicesUids:
953 case TRANSACTION_setUidDeviceAffinities:
954 case TRANSACTION_removeUidDeviceAffinities:
955 case TRANSACTION_setUserIdDeviceAffinities:
956 case TRANSACTION_removeUserIdDeviceAffinities:
957 case TRANSACTION_getHwOffloadEncodingFormatsSupportedForA2DP:
958 case TRANSACTION_listAudioVolumeGroups:
959 case TRANSACTION_getVolumeGroupFromAudioAttributes:
960 case TRANSACTION_acquireSoundTriggerSession:
961 case TRANSACTION_releaseSoundTriggerSession:
962 case TRANSACTION_setRttEnabled:
963 case TRANSACTION_isCallScreenModeSupported:
964 case TRANSACTION_setDevicesRoleForStrategy:
965 case TRANSACTION_setSupportedSystemUsages:
966 case TRANSACTION_removeDevicesRoleForStrategy:
967 case TRANSACTION_getDevicesForRoleAndStrategy:
968 case TRANSACTION_getDevicesForAttributes:
969 case TRANSACTION_setAllowedCapturePolicy:
970 case TRANSACTION_onNewAudioModulesAvailable:
971 case TRANSACTION_setCurrentImeUid:
972 case TRANSACTION_registerSoundTriggerCaptureStateListener:
973 case TRANSACTION_setDevicesRoleForCapturePreset:
974 case TRANSACTION_addDevicesRoleForCapturePreset:
975 case TRANSACTION_removeDevicesRoleForCapturePreset:
976 case TRANSACTION_clearDevicesRoleForCapturePreset:
977 case TRANSACTION_getDevicesForRoleAndCapturePreset: {
978 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
979 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
980 __func__, code, IPCThreadState::self()->getCallingPid(),
981 IPCThreadState::self()->getCallingUid());
982 return INVALID_OPERATION;
983 }
984 } break;
985 default:
986 break;
987 }
988
989 std::string tag("IAudioPolicyService command " + std::to_string(code));
990 TimeCheck check(tag.c_str());
991
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800992 switch (code) {
993 case SHELL_COMMAND_TRANSACTION: {
994 int in = data.readFileDescriptor();
995 int out = data.readFileDescriptor();
996 int err = data.readFileDescriptor();
997 int argc = data.readInt32();
998 Vector<String16> args;
999 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
1000 args.add(data.readString16());
1001 }
1002 sp<IBinder> unusedCallback;
1003 sp<IResultReceiver> resultReceiver;
1004 status_t status;
1005 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
1006 return status;
1007 }
1008 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
1009 return status;
1010 }
1011 status = shellCommand(in, out, err, args);
1012 if (resultReceiver != nullptr) {
1013 resultReceiver->send(status);
1014 }
1015 return NO_ERROR;
1016 }
1017 }
1018
Mathias Agopian65ab4712010-07-14 17:59:35 -07001019 return BnAudioPolicyService::onTransact(code, data, reply, flags);
1020}
1021
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001022// ------------------- Shell command implementation -------------------
1023
1024// NOTE: This is a remote API - make sure all args are validated
1025status_t AudioPolicyService::shellCommand(int in, int out, int err, Vector<String16>& args) {
1026 if (!checkCallingPermission(sManageAudioPolicyPermission, nullptr, nullptr)) {
1027 return PERMISSION_DENIED;
1028 }
1029 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
1030 return BAD_VALUE;
1031 }
jovanakbe066e12019-09-02 11:54:39 -07001032 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001033 return handleSetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001034 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001035 return handleResetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001036 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001037 return handleGetUidState(args, out, err);
Eric Laurent269acb42021-04-23 16:53:22 +02001038 } else if (args.size() >= 1 && args[0] == String16("purge_permission-cache")) {
1039 purgePermissionCache();
1040 return NO_ERROR;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001041 } else if (args.size() == 1 && args[0] == String16("help")) {
1042 printHelp(out);
1043 return NO_ERROR;
1044 }
1045 printHelp(err);
1046 return BAD_VALUE;
1047}
1048
jovanakbe066e12019-09-02 11:54:39 -07001049static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1050 if (userId < 0) {
1051 ALOGE("Invalid user: %d", userId);
1052 dprintf(err, "Invalid user: %d\n", userId);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001053 return BAD_VALUE;
1054 }
jovanakbe066e12019-09-02 11:54:39 -07001055
1056 PermissionController pc;
1057 uid = pc.getPackageUid(packageName, 0);
1058 if (uid <= 0) {
1059 ALOGE("Unknown package: '%s'", String8(packageName).string());
1060 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1061 return BAD_VALUE;
1062 }
1063
1064 uid = multiuser_get_uid(userId, uid);
1065 return NO_ERROR;
1066}
1067
1068status_t AudioPolicyService::handleSetUidState(Vector<String16>& args, int err) {
1069 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
1070 if (!(args.size() == 3 || args.size() == 5)) {
1071 printHelp(err);
1072 return BAD_VALUE;
1073 }
1074
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001075 bool active = false;
1076 if (args[2] == String16("active")) {
1077 active = true;
1078 } else if ((args[2] != String16("idle"))) {
1079 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
1080 return BAD_VALUE;
1081 }
jovanakbe066e12019-09-02 11:54:39 -07001082
1083 int userId = 0;
1084 if (args.size() >= 5 && args[3] == String16("--user")) {
1085 userId = atoi(String8(args[4]));
1086 }
1087
1088 uid_t uid;
1089 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1090 return BAD_VALUE;
1091 }
1092
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001093 sp<UidPolicy> uidPolicy;
1094 {
1095 Mutex::Autolock _l(mLock);
1096 uidPolicy = mUidPolicy;
1097 }
1098 if (uidPolicy) {
1099 uidPolicy->addOverrideUid(uid, active);
1100 return NO_ERROR;
1101 }
1102 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001103}
1104
1105status_t AudioPolicyService::handleResetUidState(Vector<String16>& args, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001106 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1107 if (!(args.size() == 2 || args.size() == 4)) {
1108 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001109 return BAD_VALUE;
1110 }
jovanakbe066e12019-09-02 11:54:39 -07001111
1112 int userId = 0;
1113 if (args.size() >= 4 && args[2] == String16("--user")) {
1114 userId = atoi(String8(args[3]));
1115 }
1116
1117 uid_t uid;
1118 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1119 return BAD_VALUE;
1120 }
1121
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001122 sp<UidPolicy> uidPolicy;
1123 {
1124 Mutex::Autolock _l(mLock);
1125 uidPolicy = mUidPolicy;
1126 }
1127 if (uidPolicy) {
1128 uidPolicy->removeOverrideUid(uid);
1129 return NO_ERROR;
1130 }
1131 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001132}
1133
1134status_t AudioPolicyService::handleGetUidState(Vector<String16>& args, int out, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001135 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1136 if (!(args.size() == 2 || args.size() == 4)) {
1137 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001138 return BAD_VALUE;
1139 }
jovanakbe066e12019-09-02 11:54:39 -07001140
1141 int userId = 0;
1142 if (args.size() >= 4 && args[2] == String16("--user")) {
1143 userId = atoi(String8(args[3]));
1144 }
1145
1146 uid_t uid;
1147 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1148 return BAD_VALUE;
1149 }
1150
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001151 sp<UidPolicy> uidPolicy;
1152 {
1153 Mutex::Autolock _l(mLock);
1154 uidPolicy = mUidPolicy;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001155 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001156 if (uidPolicy) {
1157 return dprintf(out, uidPolicy->isUidActive(uid) ? "active\n" : "idle\n");
1158 }
1159 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001160}
1161
1162status_t AudioPolicyService::printHelp(int out) {
1163 return dprintf(out, "Audio policy service commands:\n"
jovanakbe066e12019-09-02 11:54:39 -07001164 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
1165 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
1166 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001167 " help print this message\n");
1168}
1169
1170// ----------- AudioPolicyService::UidPolicy implementation ----------
1171
1172void AudioPolicyService::UidPolicy::registerSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001173 status_t res = mAm.linkToDeath(this);
1174 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001175 | ActivityManager::UID_OBSERVER_IDLE
Eric Laurente8c8b432018-10-17 10:08:02 -07001176 | ActivityManager::UID_OBSERVER_ACTIVE
1177 | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001178 ActivityManager::PROCESS_STATE_UNKNOWN,
1179 String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001180 if (!res) {
1181 Mutex::Autolock _l(mLock);
1182 mObserverRegistered = true;
1183 } else {
1184 ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001185
Steven Moreland2f348142019-07-02 15:59:07 -07001186 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001187 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001188}
1189
1190void AudioPolicyService::UidPolicy::unregisterSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001191 mAm.unlinkToDeath(this);
1192 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001193 Mutex::Autolock _l(mLock);
1194 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001195}
1196
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001197void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
1198 Mutex::Autolock _l(mLock);
1199 mCachedUids.clear();
1200 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001201}
1202
Eric Laurente8c8b432018-10-17 10:08:02 -07001203void AudioPolicyService::UidPolicy::checkRegistered() {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001204 bool needToReregister = false;
1205 {
1206 Mutex::Autolock _l(mLock);
1207 needToReregister = !mObserverRegistered;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001208 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001209 if (needToReregister) {
1210 // Looks like ActivityManager has died previously, attempt to re-register.
1211 registerSelf();
1212 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001213}
1214
1215bool AudioPolicyService::UidPolicy::isUidActive(uid_t uid) {
1216 if (isServiceUid(uid)) return true;
1217 checkRegistered();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001218 {
1219 Mutex::Autolock _l(mLock);
1220 auto overrideIter = mOverrideUids.find(uid);
1221 if (overrideIter != mOverrideUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001222 return overrideIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001223 }
1224 // In an absense of the ActivityManager, assume everything to be active.
1225 if (!mObserverRegistered) return true;
1226 auto cacheIter = mCachedUids.find(uid);
Mikhail Naganoveba668a2018-04-05 08:13:15 -07001227 if (cacheIter != mCachedUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001228 return cacheIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001229 }
1230 }
1231 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001232 bool active = am.isUidActive(uid, String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001233 {
1234 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001235 mCachedUids.insert(std::pair<uid_t,
1236 std::pair<bool, int>>(uid, std::pair<bool, int>(active,
1237 ActivityManager::PROCESS_STATE_UNKNOWN)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001238 }
1239 return active;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001240}
1241
Eric Laurente8c8b432018-10-17 10:08:02 -07001242int AudioPolicyService::UidPolicy::getUidState(uid_t uid) {
1243 if (isServiceUid(uid)) {
1244 return ActivityManager::PROCESS_STATE_TOP;
1245 }
1246 checkRegistered();
1247 {
1248 Mutex::Autolock _l(mLock);
1249 auto overrideIter = mOverrideUids.find(uid);
1250 if (overrideIter != mOverrideUids.end()) {
1251 if (overrideIter->second.first) {
1252 if (overrideIter->second.second != ActivityManager::PROCESS_STATE_UNKNOWN) {
1253 return overrideIter->second.second;
1254 } else {
1255 auto cacheIter = mCachedUids.find(uid);
1256 if (cacheIter != mCachedUids.end()) {
1257 return cacheIter->second.second;
1258 }
1259 }
1260 }
1261 return ActivityManager::PROCESS_STATE_UNKNOWN;
1262 }
1263 // In an absense of the ActivityManager, assume everything to be active.
1264 if (!mObserverRegistered) {
1265 return ActivityManager::PROCESS_STATE_TOP;
1266 }
1267 auto cacheIter = mCachedUids.find(uid);
1268 if (cacheIter != mCachedUids.end()) {
1269 if (cacheIter->second.first) {
1270 return cacheIter->second.second;
1271 } else {
1272 return ActivityManager::PROCESS_STATE_UNKNOWN;
1273 }
1274 }
1275 }
1276 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001277 bool active = am.isUidActive(uid, String16("audioserver"));
Eric Laurente8c8b432018-10-17 10:08:02 -07001278 int state = ActivityManager::PROCESS_STATE_UNKNOWN;
1279 if (active) {
1280 state = am.getUidProcessState(uid, String16("audioserver"));
1281 }
1282 {
1283 Mutex::Autolock _l(mLock);
1284 mCachedUids.insert(std::pair<uid_t,
1285 std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
1286 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001287
Eric Laurente8c8b432018-10-17 10:08:02 -07001288 return state;
1289}
1290
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001291void AudioPolicyService::UidPolicy::onUidActive(uid_t uid) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001292 updateUid(&mCachedUids, uid, true, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001293}
1294
1295void AudioPolicyService::UidPolicy::onUidGone(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001296 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, false);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001297}
1298
1299void AudioPolicyService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001300 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001301}
1302
Eric Laurente8c8b432018-10-17 10:08:02 -07001303void AudioPolicyService::UidPolicy::onUidStateChanged(uid_t uid,
1304 int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07001305 int64_t procStateSeq __unused,
1306 int32_t capability __unused) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001307 if (procState != ActivityManager::PROCESS_STATE_UNKNOWN) {
1308 updateUid(&mCachedUids, uid, true, procState, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001309 }
1310}
1311
1312void AudioPolicyService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001313 updateUid(&mOverrideUids, uid, active, ActivityManager::PROCESS_STATE_UNKNOWN, insert);
1314}
1315
1316void AudioPolicyService::UidPolicy::notifyService() {
1317 sp<AudioPolicyService> service = mService.promote();
1318 if (service != nullptr) {
1319 service->updateUidStates();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001320 }
1321}
1322
Eric Laurente8c8b432018-10-17 10:08:02 -07001323void AudioPolicyService::UidPolicy::updateUid(std::unordered_map<uid_t,
1324 std::pair<bool, int>> *uids,
1325 uid_t uid,
1326 bool active,
1327 int state,
1328 bool insert) {
1329 if (isServiceUid(uid)) {
1330 return;
1331 }
1332 bool wasActive = isUidActive(uid);
1333 int previousState = getUidState(uid);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001334 {
1335 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001336 updateUidLocked(uids, uid, active, state, insert);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001337 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001338 if (wasActive != isUidActive(uid) || state != previousState) {
1339 notifyService();
1340 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001341}
1342
Eric Laurente8c8b432018-10-17 10:08:02 -07001343void AudioPolicyService::UidPolicy::updateUidLocked(std::unordered_map<uid_t,
1344 std::pair<bool, int>> *uids,
1345 uid_t uid,
1346 bool active,
1347 int state,
1348 bool insert) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001349 auto it = uids->find(uid);
1350 if (it != uids->end()) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001351 if (insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001352 if (state == ActivityManager::PROCESS_STATE_UNKNOWN) {
1353 it->second.first = active;
1354 }
1355 if (it->second.first) {
1356 it->second.second = state;
1357 } else {
1358 it->second.second = ActivityManager::PROCESS_STATE_UNKNOWN;
1359 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001360 } else {
1361 uids->erase(it);
1362 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001363 } else if (insert && (state == ActivityManager::PROCESS_STATE_UNKNOWN)) {
1364 uids->insert(std::pair<uid_t, std::pair<bool, int>>(uid,
1365 std::pair<bool, int>(active, state)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001366 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001367}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001368
Eric Laurent4eb58f12018-12-07 16:41:02 -08001369bool AudioPolicyService::UidPolicy::isA11yOnTop() {
1370 for (const auto &uid : mCachedUids) {
Eric Laurent47670c92019-08-28 16:59:05 -07001371 if (!isA11yUid(uid.first)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001372 continue;
1373 }
Amith Yamasanibcbb3002019-01-23 13:53:33 -08001374 if (uid.second.second >= ActivityManager::PROCESS_STATE_TOP
1375 && uid.second.second <= ActivityManager::PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001376 return true;
1377 }
1378 }
1379 return false;
1380}
1381
Eric Laurentb78763e2018-10-17 10:08:02 -07001382bool AudioPolicyService::UidPolicy::isA11yUid(uid_t uid)
1383{
1384 std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid);
1385 return it != mA11yUids.end();
1386}
1387
Michael Groovercfd28302018-12-11 19:16:46 -08001388// ----------- AudioPolicyService::SensorPrivacyService implementation ----------
1389void AudioPolicyService::SensorPrivacyPolicy::registerSelf() {
1390 SensorPrivacyManager spm;
1391 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1392 spm.addSensorPrivacyListener(this);
1393}
1394
Evan Severson241d9592021-01-08 12:16:02 -08001395void AudioPolicyService::SensorPrivacyPolicy::registerSelfForMicrophoneOnly(int userId) {
1396 SensorPrivacyManager spm;
1397 mSensorPrivacyEnabled = spm.isIndividualSensorPrivacyEnabled(userId,
1398 SensorPrivacyManager::INDIVIDUAL_SENSOR_MICROPHONE);
1399 spm.addIndividualSensorPrivacyListener(userId,
1400 SensorPrivacyManager::INDIVIDUAL_SENSOR_MICROPHONE, this);
1401}
1402
Michael Groovercfd28302018-12-11 19:16:46 -08001403void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
1404 SensorPrivacyManager spm;
1405 spm.removeSensorPrivacyListener(this);
1406}
1407
1408bool AudioPolicyService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1409 return mSensorPrivacyEnabled;
1410}
1411
1412binder::Status AudioPolicyService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
1413 mSensorPrivacyEnabled = enabled;
1414 sp<AudioPolicyService> service = mService.promote();
1415 if (service != nullptr) {
1416 service->updateUidStates();
1417 }
1418 return binder::Status::ok();
1419}
1420
Mathias Agopian65ab4712010-07-14 17:59:35 -07001421// ----------- AudioPolicyService::AudioCommandThread implementation ----------
1422
Eric Laurentbfb1b832013-01-07 09:53:42 -08001423AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
1424 const wp<AudioPolicyService>& service)
1425 : Thread(false), mName(name), mService(service)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001426{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001427}
1428
1429
1430AudioPolicyService::AudioCommandThread::~AudioCommandThread()
1431{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001432 if (!mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001433 release_wake_lock(mName.string());
1434 }
1435 mAudioCommands.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001436}
1437
1438void AudioPolicyService::AudioCommandThread::onFirstRef()
1439{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001440 run(mName.string(), ANDROID_PRIORITY_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001441}
1442
1443bool AudioPolicyService::AudioCommandThread::threadLoop()
1444{
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001445 nsecs_t waitTime = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001446
1447 mLock.lock();
1448 while (!exitPending())
1449 {
Eric Laurent59a89232014-06-08 14:14:17 -07001450 sp<AudioPolicyService> svc;
1451 while (!mAudioCommands.isEmpty() && !exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001452 nsecs_t curTime = systemTime();
1453 // commands are sorted by increasing time stamp: execute them from index 0 and up
1454 if (mAudioCommands[0]->mTime <= curTime) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001455 sp<AudioCommand> command = mAudioCommands[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001456 mAudioCommands.removeAt(0);
Eric Laurent0ede8922014-05-09 18:04:42 -07001457 mLastCommand = command;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001458
1459 switch (command->mCommand) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001460 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001461 VolumeData *data = (VolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001462 ALOGV("AudioCommandThread() processing set volume stream %d, \
Eric Laurentde070132010-07-13 04:45:46 -07001463 volume %f, output %d", data->mStream, data->mVolume, data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001464 mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07001465 command->mStatus = AudioSystem::setStreamVolume(data->mStream,
1466 data->mVolume,
1467 data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001468 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001469 }break;
1470 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001471 ParametersData *data = (ParametersData *)command->mParam.get();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001472 ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
1473 data->mKeyValuePairs.string(), data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001474 mLock.unlock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001475 command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
Andy Hungfe726a62018-09-27 15:17:25 -07001476 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001477 }break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001478 case SET_VOICE_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001479 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001480 ALOGV("AudioCommandThread() processing set voice volume volume %f",
Eric Laurentde070132010-07-13 04:45:46 -07001481 data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001482 mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001483 command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001484 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001485 }break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001486 case STOP_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001487 StopOutputData *data = (StopOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001488 ALOGV("AudioCommandThread() processing stop output portId %d",
1489 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001490 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001491 if (svc == 0) {
1492 break;
1493 }
1494 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001495 svc->doStopOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001496 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001497 }break;
1498 case RELEASE_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001499 ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001500 ALOGV("AudioCommandThread() processing release output portId %d",
1501 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001502 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001503 if (svc == 0) {
1504 break;
1505 }
1506 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001507 svc->doReleaseOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001508 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001509 }break;
Eric Laurent951f4552014-05-20 10:48:17 -07001510 case CREATE_AUDIO_PATCH: {
1511 CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
1512 ALOGV("AudioCommandThread() processing create audio patch");
1513 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1514 if (af == 0) {
1515 command->mStatus = PERMISSION_DENIED;
1516 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001517 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001518 command->mStatus = af->createAudioPatch(&data->mPatch, &data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001519 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001520 }
1521 } break;
1522 case RELEASE_AUDIO_PATCH: {
1523 ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
1524 ALOGV("AudioCommandThread() processing release audio patch");
1525 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1526 if (af == 0) {
1527 command->mStatus = PERMISSION_DENIED;
1528 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001529 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001530 command->mStatus = af->releaseAudioPatch(data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001531 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001532 }
1533 } break;
Eric Laurentb52c1522014-05-20 11:27:36 -07001534 case UPDATE_AUDIOPORT_LIST: {
1535 ALOGV("AudioCommandThread() processing update audio port list");
Eric Laurent59a89232014-06-08 14:14:17 -07001536 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001537 if (svc == 0) {
1538 break;
1539 }
1540 mLock.unlock();
1541 svc->doOnAudioPortListUpdate();
1542 mLock.lock();
1543 }break;
1544 case UPDATE_AUDIOPATCH_LIST: {
1545 ALOGV("AudioCommandThread() processing update audio patch list");
Eric Laurent59a89232014-06-08 14:14:17 -07001546 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001547 if (svc == 0) {
1548 break;
1549 }
1550 mLock.unlock();
1551 svc->doOnAudioPatchListUpdate();
1552 mLock.lock();
1553 }break;
François Gaffiecfe17322018-11-07 13:41:29 +01001554 case CHANGED_AUDIOVOLUMEGROUP: {
1555 AudioVolumeGroupData *data =
1556 static_cast<AudioVolumeGroupData *>(command->mParam.get());
1557 ALOGV("AudioCommandThread() processing update audio volume group");
1558 svc = mService.promote();
1559 if (svc == 0) {
1560 break;
1561 }
1562 mLock.unlock();
1563 svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
1564 mLock.lock();
1565 }break;
Eric Laurente1715a42014-05-20 11:30:42 -07001566 case SET_AUDIOPORT_CONFIG: {
1567 SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
1568 ALOGV("AudioCommandThread() processing set port config");
1569 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1570 if (af == 0) {
1571 command->mStatus = PERMISSION_DENIED;
1572 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001573 mLock.unlock();
Eric Laurente1715a42014-05-20 11:30:42 -07001574 command->mStatus = af->setAudioPortConfig(&data->mConfig);
Andy Hungfe726a62018-09-27 15:17:25 -07001575 mLock.lock();
Eric Laurente1715a42014-05-20 11:30:42 -07001576 }
1577 } break;
Jean-Michel Trivide801052015-04-14 19:10:14 -07001578 case DYN_POLICY_MIX_STATE_UPDATE: {
1579 DynPolicyMixStateUpdateData *data =
1580 (DynPolicyMixStateUpdateData *)command->mParam.get();
Jean-Michel Trivide801052015-04-14 19:10:14 -07001581 ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
1582 data->mRegId.string(), data->mState);
1583 svc = mService.promote();
1584 if (svc == 0) {
1585 break;
1586 }
1587 mLock.unlock();
1588 svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
1589 mLock.lock();
1590 } break;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001591 case RECORDING_CONFIGURATION_UPDATE: {
1592 RecordingConfigurationUpdateData *data =
1593 (RecordingConfigurationUpdateData *)command->mParam.get();
1594 ALOGV("AudioCommandThread() processing recording configuration update");
1595 svc = mService.promote();
1596 if (svc == 0) {
1597 break;
1598 }
1599 mLock.unlock();
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001600 svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -08001601 &data->mClientConfig, data->mClientEffects,
1602 &data->mDeviceConfig, data->mEffects,
1603 data->mPatchHandle, data->mSource);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001604 mLock.lock();
1605 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001606 case SET_EFFECT_SUSPENDED: {
1607 SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
1608 ALOGV("AudioCommandThread() processing set effect suspended");
1609 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1610 if (af != 0) {
1611 mLock.unlock();
1612 af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
1613 mLock.lock();
1614 }
1615 } break;
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001616 case AUDIO_MODULES_UPDATE: {
1617 ALOGV("AudioCommandThread() processing audio modules update");
1618 svc = mService.promote();
1619 if (svc == 0) {
1620 break;
1621 }
1622 mLock.unlock();
1623 svc->doOnNewAudioModulesAvailable();
1624 mLock.lock();
1625 } break;
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07001626 case ROUTING_UPDATED: {
1627 ALOGV("AudioCommandThread() processing routing update");
1628 svc = mService.promote();
1629 if (svc == 0) {
1630 break;
1631 }
1632 mLock.unlock();
1633 svc->doOnRoutingUpdated();
1634 mLock.lock();
1635 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001636
Mathias Agopian65ab4712010-07-14 17:59:35 -07001637 default:
Steve Block5ff1dd52012-01-05 23:22:43 +00001638 ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001639 }
Eric Laurent0ede8922014-05-09 18:04:42 -07001640 {
1641 Mutex::Autolock _l(command->mLock);
1642 if (command->mWaitStatus) {
1643 command->mWaitStatus = false;
1644 command->mCond.signal();
1645 }
1646 }
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001647 waitTime = -1;
Zach Janga754b4f2015-10-27 01:29:34 +00001648 // release mLock before releasing strong reference on the service as
1649 // AudioPolicyService destructor calls AudioCommandThread::exit() which
1650 // acquires mLock.
1651 mLock.unlock();
1652 svc.clear();
1653 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001654 } else {
1655 waitTime = mAudioCommands[0]->mTime - curTime;
1656 break;
1657 }
1658 }
Zach Janga754b4f2015-10-27 01:29:34 +00001659
1660 // release delayed commands wake lock if the queue is empty
1661 if (mAudioCommands.isEmpty()) {
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07001662 release_wake_lock(mName.string());
Zach Janga754b4f2015-10-27 01:29:34 +00001663 }
1664
1665 // At this stage we have either an empty command queue or the first command in the queue
1666 // has a finite delay. So unless we are exiting it is safe to wait.
1667 if (!exitPending()) {
Eric Laurent59a89232014-06-08 14:14:17 -07001668 ALOGV("AudioCommandThread() going to sleep");
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001669 if (waitTime == -1) {
1670 mWaitWorkCV.wait(mLock);
1671 } else {
1672 mWaitWorkCV.waitRelative(mLock, waitTime);
1673 }
Eric Laurent59a89232014-06-08 14:14:17 -07001674 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001675 }
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07001676 // release delayed commands wake lock before quitting
1677 if (!mAudioCommands.isEmpty()) {
1678 release_wake_lock(mName.string());
1679 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001680 mLock.unlock();
1681 return false;
1682}
1683
1684status_t AudioPolicyService::AudioCommandThread::dump(int fd)
1685{
1686 const size_t SIZE = 256;
1687 char buffer[SIZE];
1688 String8 result;
1689
1690 snprintf(buffer, SIZE, "AudioCommandThread %p Dump\n", this);
1691 result.append(buffer);
1692 write(fd, result.string(), result.size());
1693
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001694 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001695 if (!locked) {
1696 String8 result2(kCmdDeadlockedString);
1697 write(fd, result2.string(), result2.size());
1698 }
1699
1700 snprintf(buffer, SIZE, "- Commands:\n");
1701 result = String8(buffer);
1702 result.append(" Command Time Wait pParam\n");
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001703 for (size_t i = 0; i < mAudioCommands.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001704 mAudioCommands[i]->dump(buffer, SIZE);
1705 result.append(buffer);
1706 }
1707 result.append(" Last Command\n");
Eric Laurent0ede8922014-05-09 18:04:42 -07001708 if (mLastCommand != 0) {
1709 mLastCommand->dump(buffer, SIZE);
1710 result.append(buffer);
1711 } else {
1712 result.append(" none\n");
1713 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001714
1715 write(fd, result.string(), result.size());
1716
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001717 dumpReleaseLock(mLock, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001718
1719 return NO_ERROR;
1720}
1721
Glenn Kastenfff6d712012-01-12 16:38:12 -08001722status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
Eric Laurentde070132010-07-13 04:45:46 -07001723 float volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001724 audio_io_handle_t output,
Eric Laurentde070132010-07-13 04:45:46 -07001725 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001726{
Eric Laurent0ede8922014-05-09 18:04:42 -07001727 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001728 command->mCommand = SET_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07001729 sp<VolumeData> data = new VolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001730 data->mStream = stream;
1731 data->mVolume = volume;
1732 data->mIO = output;
1733 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07001734 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01001735 ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
Eric Laurentde070132010-07-13 04:45:46 -07001736 stream, volume, output);
Eric Laurent0ede8922014-05-09 18:04:42 -07001737 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001738}
1739
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001740status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
Dima Zavinfce7a472011-04-19 22:30:36 -07001741 const char *keyValuePairs,
Eric Laurentde070132010-07-13 04:45:46 -07001742 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001743{
Eric Laurent0ede8922014-05-09 18:04:42 -07001744 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001745 command->mCommand = SET_PARAMETERS;
Eric Laurent0ede8922014-05-09 18:04:42 -07001746 sp<ParametersData> data = new ParametersData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001747 data->mIO = ioHandle;
Dima Zavinfce7a472011-04-19 22:30:36 -07001748 data->mKeyValuePairs = String8(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001749 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07001750 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01001751 ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
Dima Zavinfce7a472011-04-19 22:30:36 -07001752 keyValuePairs, ioHandle, delayMs);
Eric Laurent0ede8922014-05-09 18:04:42 -07001753 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001754}
1755
1756status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
1757{
Eric Laurent0ede8922014-05-09 18:04:42 -07001758 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001759 command->mCommand = SET_VOICE_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07001760 sp<VoiceVolumeData> data = new VoiceVolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001761 data->mVolume = volume;
1762 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07001763 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01001764 ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
Eric Laurent0ede8922014-05-09 18:04:42 -07001765 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001766}
1767
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001768void AudioPolicyService::AudioCommandThread::setEffectSuspendedCommand(int effectId,
1769 audio_session_t sessionId,
1770 bool suspended)
1771{
1772 sp<AudioCommand> command = new AudioCommand();
1773 command->mCommand = SET_EFFECT_SUSPENDED;
1774 sp<SetEffectSuspendedData> data = new SetEffectSuspendedData();
1775 data->mEffectId = effectId;
1776 data->mSessionId = sessionId;
1777 data->mSuspended = suspended;
1778 command->mParam = data;
1779 ALOGV("AudioCommandThread() adding set suspended effectId %d sessionId %d suspended %d",
1780 effectId, sessionId, suspended);
1781 sendCommand(command);
1782}
1783
1784
Eric Laurentd7fe0862018-07-14 16:48:01 -07001785void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001786{
Eric Laurent0ede8922014-05-09 18:04:42 -07001787 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001788 command->mCommand = STOP_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07001789 sp<StopOutputData> data = new StopOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001790 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01001791 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07001792 ALOGV("AudioCommandThread() adding stop output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07001793 sendCommand(command);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001794}
1795
Eric Laurentd7fe0862018-07-14 16:48:01 -07001796void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001797{
Eric Laurent0ede8922014-05-09 18:04:42 -07001798 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001799 command->mCommand = RELEASE_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07001800 sp<ReleaseOutputData> data = new ReleaseOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001801 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01001802 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07001803 ALOGV("AudioCommandThread() adding release output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07001804 sendCommand(command);
1805}
1806
Eric Laurent951f4552014-05-20 10:48:17 -07001807status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
1808 const struct audio_patch *patch,
1809 audio_patch_handle_t *handle,
1810 int delayMs)
1811{
1812 status_t status = NO_ERROR;
1813
1814 sp<AudioCommand> command = new AudioCommand();
1815 command->mCommand = CREATE_AUDIO_PATCH;
1816 CreateAudioPatchData *data = new CreateAudioPatchData();
1817 data->mPatch = *patch;
1818 data->mHandle = *handle;
1819 command->mParam = data;
1820 command->mWaitStatus = true;
1821 ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
1822 status = sendCommand(command, delayMs);
1823 if (status == NO_ERROR) {
1824 *handle = data->mHandle;
1825 }
1826 return status;
1827}
1828
1829status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
1830 int delayMs)
1831{
1832 sp<AudioCommand> command = new AudioCommand();
1833 command->mCommand = RELEASE_AUDIO_PATCH;
1834 ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
1835 data->mHandle = handle;
1836 command->mParam = data;
1837 command->mWaitStatus = true;
1838 ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
1839 return sendCommand(command, delayMs);
1840}
1841
Eric Laurentb52c1522014-05-20 11:27:36 -07001842void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
1843{
1844 sp<AudioCommand> command = new AudioCommand();
1845 command->mCommand = UPDATE_AUDIOPORT_LIST;
1846 ALOGV("AudioCommandThread() adding update audio port list");
1847 sendCommand(command);
1848}
1849
1850void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
1851{
1852 sp<AudioCommand>command = new AudioCommand();
1853 command->mCommand = UPDATE_AUDIOPATCH_LIST;
1854 ALOGV("AudioCommandThread() adding update audio patch list");
1855 sendCommand(command);
1856}
1857
François Gaffiecfe17322018-11-07 13:41:29 +01001858void AudioPolicyService::AudioCommandThread::changeAudioVolumeGroupCommand(volume_group_t group,
1859 int flags)
1860{
1861 sp<AudioCommand>command = new AudioCommand();
1862 command->mCommand = CHANGED_AUDIOVOLUMEGROUP;
1863 AudioVolumeGroupData *data= new AudioVolumeGroupData();
1864 data->mGroup = group;
1865 data->mFlags = flags;
1866 command->mParam = data;
1867 ALOGV("AudioCommandThread() adding audio volume group changed");
1868 sendCommand(command);
1869}
1870
Eric Laurente1715a42014-05-20 11:30:42 -07001871status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
1872 const struct audio_port_config *config, int delayMs)
1873{
1874 sp<AudioCommand> command = new AudioCommand();
1875 command->mCommand = SET_AUDIOPORT_CONFIG;
1876 SetAudioPortConfigData *data = new SetAudioPortConfigData();
1877 data->mConfig = *config;
1878 command->mParam = data;
1879 command->mWaitStatus = true;
1880 ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
1881 return sendCommand(command, delayMs);
1882}
1883
Jean-Michel Trivide801052015-04-14 19:10:14 -07001884void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001885 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -07001886{
1887 sp<AudioCommand> command = new AudioCommand();
1888 command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
1889 DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
1890 data->mRegId = regId;
1891 data->mState = state;
1892 command->mParam = data;
1893 ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
1894 regId.string(), state);
1895 sendCommand(command);
1896}
1897
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001898void AudioPolicyService::AudioCommandThread::recordingConfigurationUpdateCommand(
Eric Laurenta9f86652018-11-28 17:23:11 -08001899 int event,
1900 const record_client_info_t *clientInfo,
1901 const audio_config_base_t *clientConfig,
1902 std::vector<effect_descriptor_t> clientEffects,
1903 const audio_config_base_t *deviceConfig,
1904 std::vector<effect_descriptor_t> effects,
1905 audio_patch_handle_t patchHandle,
1906 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001907{
1908 sp<AudioCommand>command = new AudioCommand();
1909 command->mCommand = RECORDING_CONFIGURATION_UPDATE;
1910 RecordingConfigurationUpdateData *data = new RecordingConfigurationUpdateData();
1911 data->mEvent = event;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001912 data->mClientInfo = *clientInfo;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08001913 data->mClientConfig = *clientConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08001914 data->mClientEffects = clientEffects;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08001915 data->mDeviceConfig = *deviceConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08001916 data->mEffects = effects;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08001917 data->mPatchHandle = patchHandle;
Eric Laurenta9f86652018-11-28 17:23:11 -08001918 data->mSource = source;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001919 command->mParam = data;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001920 ALOGV("AudioCommandThread() adding recording configuration update event %d, source %d uid %u",
1921 event, clientInfo->source, clientInfo->uid);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001922 sendCommand(command);
1923}
1924
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001925void AudioPolicyService::AudioCommandThread::audioModulesUpdateCommand()
1926{
1927 sp<AudioCommand> command = new AudioCommand();
1928 command->mCommand = AUDIO_MODULES_UPDATE;
1929 sendCommand(command);
1930}
1931
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07001932void AudioPolicyService::AudioCommandThread::routingChangedCommand()
1933{
1934 sp<AudioCommand>command = new AudioCommand();
1935 command->mCommand = ROUTING_UPDATED;
1936 ALOGV("AudioCommandThread() adding routing update");
1937 sendCommand(command);
1938}
1939
Eric Laurent0ede8922014-05-09 18:04:42 -07001940status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
1941{
1942 {
1943 Mutex::Autolock _l(mLock);
1944 insertCommand_l(command, delayMs);
1945 mWaitWorkCV.signal();
1946 }
1947 Mutex::Autolock _l(command->mLock);
1948 while (command->mWaitStatus) {
1949 nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
1950 if (command->mCond.waitRelative(command->mLock, timeOutNs) != NO_ERROR) {
1951 command->mStatus = TIMED_OUT;
1952 command->mWaitStatus = false;
1953 }
1954 }
1955 return command->mStatus;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001956}
1957
Mathias Agopian65ab4712010-07-14 17:59:35 -07001958// insertCommand_l() must be called with mLock held
Eric Laurent0ede8922014-05-09 18:04:42 -07001959void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001960{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001961 ssize_t i; // not size_t because i will count down to -1
Eric Laurent0ede8922014-05-09 18:04:42 -07001962 Vector < sp<AudioCommand> > removedCommands;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001963 command->mTime = systemTime() + milliseconds(delayMs);
1964
1965 // acquire wake lock to make sure delayed commands are processed
Eric Laurentbfb1b832013-01-07 09:53:42 -08001966 if (mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001967 acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.string());
1968 }
1969
1970 // check same pending commands with later time stamps and eliminate them
Ivan Lozano5ff158f2017-10-30 09:06:24 -07001971 for (i = (ssize_t)mAudioCommands.size()-1; i >= 0; i--) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001972 sp<AudioCommand> command2 = mAudioCommands[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001973 // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
1974 if (command2->mTime <= command->mTime) break;
Eric Laurente45b48a2014-09-04 16:40:57 -07001975
1976 // create audio patch or release audio patch commands are equivalent
1977 // with regard to filtering
1978 if ((command->mCommand == CREATE_AUDIO_PATCH) ||
1979 (command->mCommand == RELEASE_AUDIO_PATCH)) {
1980 if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
1981 (command2->mCommand != RELEASE_AUDIO_PATCH)) {
1982 continue;
1983 }
1984 } else if (command2->mCommand != command->mCommand) continue;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001985
1986 switch (command->mCommand) {
1987 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001988 ParametersData *data = (ParametersData *)command->mParam.get();
1989 ParametersData *data2 = (ParametersData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001990 if (data->mIO != data2->mIO) break;
Steve Block3856b092011-10-20 11:56:00 +01001991 ALOGV("Comparing parameter command %s to new command %s",
Eric Laurentde070132010-07-13 04:45:46 -07001992 data2->mKeyValuePairs.string(), data->mKeyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001993 AudioParameter param = AudioParameter(data->mKeyValuePairs);
1994 AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
1995 for (size_t j = 0; j < param.size(); j++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001996 String8 key;
1997 String8 value;
1998 param.getAt(j, key, value);
1999 for (size_t k = 0; k < param2.size(); k++) {
2000 String8 key2;
2001 String8 value2;
2002 param2.getAt(k, key2, value2);
2003 if (key2 == key) {
2004 param2.remove(key2);
2005 ALOGV("Filtering out parameter %s", key2.string());
2006 break;
2007 }
2008 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002009 }
2010 // if all keys have been filtered out, remove the command.
2011 // otherwise, update the key value pairs
2012 if (param2.size() == 0) {
2013 removedCommands.add(command2);
2014 } else {
2015 data2->mKeyValuePairs = param2.toString();
2016 }
Eric Laurent21e54562013-09-23 12:08:05 -07002017 command->mTime = command2->mTime;
2018 // force delayMs to non 0 so that code below does not request to wait for
2019 // command status as the command is now delayed
2020 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002021 } break;
2022
2023 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002024 VolumeData *data = (VolumeData *)command->mParam.get();
2025 VolumeData *data2 = (VolumeData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002026 if (data->mIO != data2->mIO) break;
2027 if (data->mStream != data2->mStream) break;
Steve Block3856b092011-10-20 11:56:00 +01002028 ALOGV("Filtering out volume command on output %d for stream %d",
Eric Laurentde070132010-07-13 04:45:46 -07002029 data->mIO, data->mStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002030 removedCommands.add(command2);
Eric Laurent21e54562013-09-23 12:08:05 -07002031 command->mTime = command2->mTime;
2032 // force delayMs to non 0 so that code below does not request to wait for
2033 // command status as the command is now delayed
2034 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002035 } break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002036
Eric Laurentbaf35fe2016-07-27 15:36:53 -07002037 case SET_VOICE_VOLUME: {
2038 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
2039 VoiceVolumeData *data2 = (VoiceVolumeData *)command2->mParam.get();
2040 ALOGV("Filtering out voice volume command value %f replaced by %f",
2041 data2->mVolume, data->mVolume);
2042 removedCommands.add(command2);
2043 command->mTime = command2->mTime;
2044 // force delayMs to non 0 so that code below does not request to wait for
2045 // command status as the command is now delayed
2046 delayMs = 1;
2047 } break;
2048
Eric Laurente45b48a2014-09-04 16:40:57 -07002049 case CREATE_AUDIO_PATCH:
2050 case RELEASE_AUDIO_PATCH: {
2051 audio_patch_handle_t handle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002052 struct audio_patch patch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002053 if (command->mCommand == CREATE_AUDIO_PATCH) {
2054 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002055 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002056 } else {
2057 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
Mikhail Naganov7be71d22018-05-23 16:51:46 -07002058 memset(&patch, 0, sizeof(patch));
Eric Laurente45b48a2014-09-04 16:40:57 -07002059 }
2060 audio_patch_handle_t handle2;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002061 struct audio_patch patch2;
Eric Laurente45b48a2014-09-04 16:40:57 -07002062 if (command2->mCommand == CREATE_AUDIO_PATCH) {
2063 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002064 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002065 } else {
2066 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
Glenn Kastenf60b6b62015-07-06 10:53:26 -07002067 memset(&patch2, 0, sizeof(patch2));
Eric Laurente45b48a2014-09-04 16:40:57 -07002068 }
2069 if (handle != handle2) break;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002070 /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
2071 same output. */
2072 if( (command->mCommand == CREATE_AUDIO_PATCH) &&
2073 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
2074 bool isOutputDiff = false;
2075 if (patch.num_sources == patch2.num_sources) {
2076 for (unsigned count = 0; count < patch.num_sources; count++) {
2077 if (patch.sources[count].id != patch2.sources[count].id) {
2078 isOutputDiff = true;
2079 break;
2080 }
2081 }
2082 if (isOutputDiff)
2083 break;
2084 }
2085 }
Eric Laurente45b48a2014-09-04 16:40:57 -07002086 ALOGV("Filtering out %s audio patch command for handle %d",
2087 (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
2088 removedCommands.add(command2);
2089 command->mTime = command2->mTime;
2090 // force delayMs to non 0 so that code below does not request to wait for
2091 // command status as the command is now delayed
2092 delayMs = 1;
2093 } break;
2094
Jean-Michel Trivide801052015-04-14 19:10:14 -07002095 case DYN_POLICY_MIX_STATE_UPDATE: {
2096
2097 } break;
2098
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002099 case RECORDING_CONFIGURATION_UPDATE: {
2100
2101 } break;
2102
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002103 case ROUTING_UPDATED: {
2104
2105 } break;
2106
Mathias Agopian65ab4712010-07-14 17:59:35 -07002107 default:
2108 break;
2109 }
2110 }
2111
2112 // remove filtered commands
2113 for (size_t j = 0; j < removedCommands.size(); j++) {
2114 // removed commands always have time stamps greater than current command
2115 for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002116 if (mAudioCommands[k].get() == removedCommands[j].get()) {
Steve Block3856b092011-10-20 11:56:00 +01002117 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002118 mAudioCommands.removeAt(k);
2119 break;
2120 }
2121 }
2122 }
2123 removedCommands.clear();
2124
Eric Laurentaa79bef2015-01-15 14:33:51 -08002125 // Disable wait for status if delay is not 0.
2126 // Except for create audio patch command because the returned patch handle
2127 // is needed by audio policy manager
2128 if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
Eric Laurentcec4abb2012-07-03 12:23:02 -07002129 command->mWaitStatus = false;
2130 }
Eric Laurentcec4abb2012-07-03 12:23:02 -07002131
Mathias Agopian65ab4712010-07-14 17:59:35 -07002132 // insert command at the right place according to its time stamp
Eric Laurent1e693b52014-07-09 15:03:28 -07002133 ALOGV("inserting command: %d at index %zd, num commands %zu",
2134 command->mCommand, i+1, mAudioCommands.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002135 mAudioCommands.insertAt(command, i + 1);
2136}
2137
2138void AudioPolicyService::AudioCommandThread::exit()
2139{
Steve Block3856b092011-10-20 11:56:00 +01002140 ALOGV("AudioCommandThread::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002141 {
2142 AutoMutex _l(mLock);
2143 requestExit();
2144 mWaitWorkCV.signal();
2145 }
Zach Janga754b4f2015-10-27 01:29:34 +00002146 // Note that we can call it from the thread loop if all other references have been released
2147 // but it will safely return WOULD_BLOCK in this case
Mathias Agopian65ab4712010-07-14 17:59:35 -07002148 requestExitAndWait();
2149}
2150
2151void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
2152{
2153 snprintf(buffer, size, " %02d %06d.%03d %01u %p\n",
2154 mCommand,
2155 (int)ns2s(mTime),
2156 (int)ns2ms(mTime)%1000,
2157 mWaitStatus,
Eric Laurent0ede8922014-05-09 18:04:42 -07002158 mParam.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002159}
2160
Dima Zavinfce7a472011-04-19 22:30:36 -07002161/******* helpers for the service_ops callbacks defined below *********/
2162void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
2163 const char *keyValuePairs,
2164 int delayMs)
2165{
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002166 mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
Dima Zavinfce7a472011-04-19 22:30:36 -07002167 delayMs);
2168}
2169
2170int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
2171 float volume,
2172 audio_io_handle_t output,
2173 int delayMs)
2174{
Glenn Kastenfff6d712012-01-12 16:38:12 -08002175 return (int)mAudioCommandThread->volumeCommand(stream, volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002176 output, delayMs);
Dima Zavinfce7a472011-04-19 22:30:36 -07002177}
2178
Dima Zavinfce7a472011-04-19 22:30:36 -07002179int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
2180{
2181 return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
2182}
2183
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002184void AudioPolicyService::setEffectSuspended(int effectId,
2185 audio_session_t sessionId,
2186 bool suspended)
2187{
2188 mAudioCommandThread->setEffectSuspendedCommand(effectId, sessionId, suspended);
2189}
2190
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002191Status AudioPolicyService::onNewAudioModulesAvailable()
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002192{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07002193 mOutputCommandThread->audioModulesUpdateCommand();
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002194 return Status::ok();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002195}
2196
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002197
Dima Zavinfce7a472011-04-19 22:30:36 -07002198extern "C" {
Eric Laurent2d388ec2014-03-07 13:25:54 -08002199audio_module_handle_t aps_load_hw_module(void *service __unused,
2200 const char *name);
2201audio_io_handle_t aps_open_output(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002202 audio_devices_t *pDevices,
2203 uint32_t *pSamplingRate,
2204 audio_format_t *pFormat,
2205 audio_channel_mask_t *pChannelMask,
2206 uint32_t *pLatencyMs,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002207 audio_output_flags_t flags);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002208
Eric Laurent2d388ec2014-03-07 13:25:54 -08002209audio_io_handle_t aps_open_output_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002210 audio_module_handle_t module,
2211 audio_devices_t *pDevices,
2212 uint32_t *pSamplingRate,
2213 audio_format_t *pFormat,
2214 audio_channel_mask_t *pChannelMask,
2215 uint32_t *pLatencyMs,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002216 audio_output_flags_t flags,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002217 const audio_offload_info_t *offloadInfo);
2218audio_io_handle_t aps_open_dup_output(void *service __unused,
Dima Zavinfce7a472011-04-19 22:30:36 -07002219 audio_io_handle_t output1,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002220 audio_io_handle_t output2);
2221int aps_close_output(void *service __unused, audio_io_handle_t output);
2222int aps_suspend_output(void *service __unused, audio_io_handle_t output);
2223int aps_restore_output(void *service __unused, audio_io_handle_t output);
2224audio_io_handle_t aps_open_input(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002225 audio_devices_t *pDevices,
2226 uint32_t *pSamplingRate,
2227 audio_format_t *pFormat,
2228 audio_channel_mask_t *pChannelMask,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002229 audio_in_acoustics_t acoustics __unused);
2230audio_io_handle_t aps_open_input_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002231 audio_module_handle_t module,
2232 audio_devices_t *pDevices,
2233 uint32_t *pSamplingRate,
2234 audio_format_t *pFormat,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002235 audio_channel_mask_t *pChannelMask);
2236int aps_close_input(void *service __unused, audio_io_handle_t input);
2237int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
Glenn Kastend848eb42016-03-08 13:42:11 -08002238int aps_move_effects(void *service __unused, audio_session_t session,
Dima Zavinfce7a472011-04-19 22:30:36 -07002239 audio_io_handle_t src_output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002240 audio_io_handle_t dst_output);
2241char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
2242 const char *keys);
2243void aps_set_parameters(void *service, audio_io_handle_t io_handle,
2244 const char *kv_pairs, int delay_ms);
2245int aps_set_stream_volume(void *service, audio_stream_type_t stream,
Dima Zavinfce7a472011-04-19 22:30:36 -07002246 float volume, audio_io_handle_t output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002247 int delay_ms);
Eric Laurent2d388ec2014-03-07 13:25:54 -08002248int aps_set_voice_volume(void *service, float volume, int delay_ms);
2249};
Dima Zavinfce7a472011-04-19 22:30:36 -07002250
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08002251} // namespace android