blob: b5eb98fba10122799038f61efb7b8caa8ac4f783 [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];
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700597 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(current->identity.uid));
Evan Severson1f700cd2021-02-10 13:10:37 -0800598 if (!current->active) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700599 continue;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800600 }
Eric Laurent1ff16a72019-03-14 18:35:04 -0700601
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700602 app_state_t appState = apmStatFromAmState(mUidPolicy->getUidState(currentUid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700603 // clients which app is in IDLE state are not eligible for top active or
604 // latest active
605 if (appState == APP_STATE_IDLE) {
606 continue;
607 }
608
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700609 bool isAccessibility = mUidPolicy->isA11yUid(currentUid);
Eric Laurent14a88632020-07-16 12:28:30 -0700610 // Clients capturing for Accessibility services or virtual sources are not considered
Eric Laurentc21d5692020-02-25 10:24:36 -0800611 // for top or latest active to avoid masking regular clients started before
Eric Laurent14a88632020-07-16 12:28:30 -0700612 if (!isAccessibility && !isVirtualSource(current->attributes.source)) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700613 bool isAssistant = mUidPolicy->isAssistantUid(currentUid);
Eric Laurentc21d5692020-02-25 10:24:36 -0800614 bool isPrivacySensitive =
615 (current->attributes.flags & AUDIO_FLAG_CAPTURE_PRIVATE) != 0;
Eric Laurentb809a752020-06-29 09:53:13 -0700616
Eric Laurentc21d5692020-02-25 10:24:36 -0800617 if (appState == APP_STATE_TOP) {
618 if (isPrivacySensitive) {
619 if (current->startTimeNs > topSensitiveStartNs) {
620 topSensitiveActive = current;
621 topSensitiveStartNs = current->startTimeNs;
622 }
623 } else {
624 if (current->startTimeNs > topStartNs) {
625 topActive = current;
626 topStartNs = current->startTimeNs;
627 }
628 }
629 if (isAssistant) {
630 isAssistantOnTop = true;
631 }
Eric Laurenta46bedb2018-12-07 18:01:26 -0800632 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800633 // Clients capturing for HOTWORD are not considered
634 // for latest active to avoid masking regular clients started before
635 if (!(current->attributes.source == AUDIO_SOURCE_HOTWORD
636 || ((isA11yOnTop || rttCallActive) && isAssistant))) {
637 if (isPrivacySensitive) {
Eric Laurentb809a752020-06-29 09:53:13 -0700638 // if audio mode is IN_COMMUNICATION, make sure the audio mode owner
639 // is marked latest sensitive active even if another app qualifies.
640 if (current->startTimeNs > latestSensitiveStartNs
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700641 || (isInCommunication && currentUid == mPhoneStateOwnerUid)) {
Eric Laurentb809a752020-06-29 09:53:13 -0700642 if (!isInCommunication || latestSensitiveActiveOrComm == nullptr
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700643 || VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
644 latestSensitiveActiveOrComm->identity.uid))
645 != mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700646 latestSensitiveActiveOrComm = current;
647 latestSensitiveStartNs = current->startTimeNs;
648 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800649 }
650 isSensitiveActive = true;
651 } else {
652 if (current->startTimeNs > latestStartNs) {
653 latestActive = current;
654 latestStartNs = current->startTimeNs;
655 }
656 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800657 }
658 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700659 if (current->attributes.source != AUDIO_SOURCE_HOTWORD) {
660 onlyHotwordActive = false;
661 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700662 if (currentUid == mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700663 isPhoneStateOwnerActive = true;
664 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800665 }
666
Eric Laurent1ff16a72019-03-14 18:35:04 -0700667 // if no active client with UI on Top, consider latest active as top
668 if (topActive == nullptr) {
669 topActive = latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800670 topStartNs = latestStartNs;
671 }
672 if (topSensitiveActive == nullptr) {
Eric Laurentb809a752020-06-29 09:53:13 -0700673 topSensitiveActive = latestSensitiveActiveOrComm;
Eric Laurentc21d5692020-02-25 10:24:36 -0800674 topSensitiveStartNs = latestSensitiveStartNs;
Eric Laurentb809a752020-06-29 09:53:13 -0700675 } else if (latestSensitiveActiveOrComm != nullptr) {
676 // if audio mode is IN_COMMUNICATION, favor audio mode owner over an app with
677 // foreground UI in case both are capturing with privacy sensitive flag.
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700678 uid_t latestActiveUid = VALUE_OR_FATAL(
679 aidl2legacy_int32_t_uid_t(latestSensitiveActiveOrComm->identity.uid));
680 if (isInCommunication && latestActiveUid == mPhoneStateOwnerUid) {
Eric Laurentb809a752020-06-29 09:53:13 -0700681 topSensitiveActive = latestSensitiveActiveOrComm;
682 topSensitiveStartNs = latestSensitiveStartNs;
683 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800684 }
685
686 // If both privacy sensitive and regular capture are active:
687 // if the regular capture is privileged
688 // allow concurrency
689 // else
690 // favor the privacy sensitive case
691 if (topActive != nullptr && topSensitiveActive != nullptr
Ricardo Correa57a37692020-03-23 17:27:25 -0700692 && !topActive->canCaptureOutput) {
Eric Laurentc21d5692020-02-25 10:24:36 -0800693 topActive = nullptr;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800694 }
695
696 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
697 sp<AudioRecordClient> current = mAudioRecordClients[i];
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700698 uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
699 current->identity.uid));
Eric Laurent1ff16a72019-03-14 18:35:04 -0700700 if (!current->active) {
701 continue;
702 }
703
Eric Laurent4eb58f12018-12-07 16:41:02 -0800704 audio_source_t source = current->attributes.source;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700705 bool isTopOrLatestActive = topActive == nullptr ? false :
706 current->identity.uid == topActive->identity.uid;
707 bool isTopOrLatestSensitive = topSensitiveActive == nullptr ? false :
708 current->identity.uid == topSensitiveActive->identity.uid;
Eric Laurentc21d5692020-02-25 10:24:36 -0800709
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000710 auto canCaptureIfInCallOrCommunication = [&](const auto &recordClient) REQUIRES(mLock) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700711 uid_t recordUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(
712 recordClient->identity.uid));
Ricardo Correa57a37692020-03-23 17:27:25 -0700713 bool canCaptureCall = recordClient->canCaptureOutput;
Eric Laurentb809a752020-06-29 09:53:13 -0700714 bool canCaptureCommunication = recordClient->canCaptureOutput
715 || !isPhoneStateOwnerActive
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700716 || recordUid == mPhoneStateOwnerUid;
Eric Laurentb809a752020-06-29 09:53:13 -0700717 return !(isInCall && !canCaptureCall)
718 && !(isInCommunication && !canCaptureCommunication);
Eric Laurentc21d5692020-02-25 10:24:36 -0800719 };
Eric Laurent1ff16a72019-03-14 18:35:04 -0700720
721 // By default allow capture if:
722 // The assistant is not on TOP
Eric Laurenta171e352019-05-07 13:04:45 -0700723 // AND is on TOP or latest started
Eric Laurent1ff16a72019-03-14 18:35:04 -0700724 // AND there is no active privacy sensitive capture or call
725 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
726 bool allowCapture = !isAssistantOnTop
Eric Laurentc21d5692020-02-25 10:24:36 -0800727 && (isTopOrLatestActive || isTopOrLatestSensitive)
728 && !(isSensitiveActive
Ricardo Correa57a37692020-03-23 17:27:25 -0700729 && !(isTopOrLatestSensitive || current->canCaptureOutput))
Eric Laurentc21d5692020-02-25 10:24:36 -0800730 && canCaptureIfInCallOrCommunication(current);
Eric Laurent2dc962b2019-03-01 08:25:25 -0800731
732 if (isVirtualSource(source)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700733 // Allow capture for virtual (remote submix, call audio TX or RX...) sources
734 allowCapture = true;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700735 } else if (mUidPolicy->isAssistantUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700736 // For assistant allow capture if:
Eric Laurent6ede98f2019-06-11 14:50:30 -0700737 // An accessibility service is on TOP or a RTT call is active
Eric Laurent1ff16a72019-03-14 18:35:04 -0700738 // AND the source is VOICE_RECOGNITION or HOTWORD
Eric Laurenta171e352019-05-07 13:04:45 -0700739 // OR is on TOP AND uses VOICE_RECOGNITION
Eric Laurent1ff16a72019-03-14 18:35:04 -0700740 // OR uses HOTWORD
741 // AND there is no active privacy sensitive capture or call
742 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent6ede98f2019-06-11 14:50:30 -0700743 if (isA11yOnTop || rttCallActive) {
Eric Laurent4eb58f12018-12-07 16:41:02 -0800744 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700745 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800746 }
747 } else {
Eric Laurenta171e352019-05-07 13:04:45 -0700748 if (((isAssistantOnTop && source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
Eric Laurentc21d5692020-02-25 10:24:36 -0800749 source == AUDIO_SOURCE_HOTWORD)
Ricardo Correa57a37692020-03-23 17:27:25 -0700750 && !(isSensitiveActive && !current->canCaptureOutput)
Eric Laurentc21d5692020-02-25 10:24:36 -0800751 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700752 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800753 }
754 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700755 } else if (mUidPolicy->isA11yUid(currentUid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700756 // For accessibility service allow capture if:
Eric Laurent47670c92019-08-28 16:59:05 -0700757 // The assistant is not on TOP
758 // AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -0700759 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent47670c92019-08-28 16:59:05 -0700760 // OR
761 // Is on TOP AND the source is VOICE_RECOGNITION or HOTWORD
762 if (!isAssistantOnTop
Ricardo Correa57a37692020-03-23 17:27:25 -0700763 && !(isSensitiveActive && !current->canCaptureOutput)
Eric Laurentc21d5692020-02-25 10:24:36 -0800764 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent47670c92019-08-28 16:59:05 -0700765 allowCapture = true;
766 }
Eric Laurent589171c2019-07-25 18:04:29 -0700767 if (isA11yOnTop) {
768 if (source == AUDIO_SOURCE_VOICE_RECOGNITION || source == AUDIO_SOURCE_HOTWORD) {
769 allowCapture = true;
770 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800771 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700772 } else if (source == AUDIO_SOURCE_HOTWORD) {
773 // For HOTWORD source allow capture when not on TOP if:
774 // All active clients are using HOTWORD source
775 // AND no call is active
776 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurentc21d5692020-02-25 10:24:36 -0800777 if (onlyHotwordActive
778 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent4e947da2019-10-17 15:24:06 -0700779 allowCapture = true;
780 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700781 } else if (mUidPolicy->isCurrentImeUid(currentUid)) {
Kohsuke Yatoha623a132020-03-24 20:10:26 -0700782 // For current InputMethodService allow capture if:
783 // A RTT call is active AND the source is VOICE_RECOGNITION
784 if (rttCallActive && source == AUDIO_SOURCE_VOICE_RECOGNITION) {
785 allowCapture = true;
786 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800787 }
Eric Laurent5ada82e2019-08-29 17:53:54 -0700788 setAppState_l(current->portId,
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700789 allowCapture ? apmStatFromAmState(mUidPolicy->getUidState(currentUid)) :
Eric Laurent1ff16a72019-03-14 18:35:04 -0700790 APP_STATE_IDLE);
Eric Laurente8c8b432018-10-17 10:08:02 -0700791 }
792}
793
Michael Groovercfd28302018-12-11 19:16:46 -0800794void AudioPolicyService::silenceAllRecordings_l() {
795 for (size_t i = 0; i < mAudioRecordClients.size(); i++) {
796 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -0700797 if (!isVirtualSource(current->attributes.source)) {
Eric Laurent5ada82e2019-08-29 17:53:54 -0700798 setAppState_l(current->portId, APP_STATE_IDLE);
Eric Laurent1ff16a72019-03-14 18:35:04 -0700799 }
Michael Groovercfd28302018-12-11 19:16:46 -0800800 }
801}
802
Eric Laurente8c8b432018-10-17 10:08:02 -0700803/* static */
804app_state_t AudioPolicyService::apmStatFromAmState(int amState) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700805
806 if (amState == ActivityManager::PROCESS_STATE_UNKNOWN) {
Eric Laurente8c8b432018-10-17 10:08:02 -0700807 return APP_STATE_IDLE;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700808 } else if (amState <= ActivityManager::PROCESS_STATE_TOP) {
809 // include persistent services
810 return APP_STATE_TOP;
Eric Laurente8c8b432018-10-17 10:08:02 -0700811 }
812 return APP_STATE_FOREGROUND;
813}
814
Eric Laurent4eb58f12018-12-07 16:41:02 -0800815/* static */
Eric Laurent2dc962b2019-03-01 08:25:25 -0800816bool AudioPolicyService::isVirtualSource(audio_source_t source)
Eric Laurent4eb58f12018-12-07 16:41:02 -0800817{
818 switch (source) {
819 case AUDIO_SOURCE_VOICE_UPLINK:
820 case AUDIO_SOURCE_VOICE_DOWNLINK:
821 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent2dc962b2019-03-01 08:25:25 -0800822 case AUDIO_SOURCE_REMOTE_SUBMIX:
823 case AUDIO_SOURCE_FM_TUNER:
Eric Laurent68eb2122020-04-30 17:40:57 -0700824 case AUDIO_SOURCE_ECHO_REFERENCE:
Eric Laurent4eb58f12018-12-07 16:41:02 -0800825 return true;
826 default:
827 break;
828 }
829 return false;
830}
831
Eric Laurent5ada82e2019-08-29 17:53:54 -0700832void AudioPolicyService::setAppState_l(audio_port_handle_t portId, app_state_t state)
Eric Laurente8c8b432018-10-17 10:08:02 -0700833{
834 AutoCallerClear acc;
835
836 if (mAudioPolicyManager) {
Eric Laurent5ada82e2019-08-29 17:53:54 -0700837 mAudioPolicyManager->setAppState(portId, state);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700838 }
839 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
840 if (af) {
Eric Laurentf32108e2018-10-04 17:22:04 -0700841 bool silenced = state == APP_STATE_IDLE;
Eric Laurent5ada82e2019-08-29 17:53:54 -0700842 af->setRecordSilenced(portId, silenced);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700843 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800844}
845
Glenn Kasten0f11b512014-01-31 16:18:54 -0800846status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700847{
Glenn Kasten44deb052012-02-05 18:09:08 -0800848 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700849 dumpPermissionDenial(fd);
850 } else {
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000851 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700852 if (!locked) {
853 String8 result(kDeadlockedString);
854 write(fd, result.string(), result.size());
855 }
856
857 dumpInternals(fd);
Glenn Kasten9d1f02d2012-02-08 17:47:58 -0800858 if (mAudioCommandThread != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700859 mAudioCommandThread->dump(fd);
860 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700861
Eric Laurentdce54a12014-03-10 12:19:46 -0700862 if (mAudioPolicyManager) {
863 mAudioPolicyManager->dump(fd);
864 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700865
Kevin Rocard8be94972019-02-22 13:26:25 -0800866 mPackageManager.dump(fd);
867
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000868 dumpReleaseLock(mLock, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700869 }
870 return NO_ERROR;
871}
872
873status_t AudioPolicyService::dumpPermissionDenial(int fd)
874{
875 const size_t SIZE = 256;
876 char buffer[SIZE];
877 String8 result;
878 snprintf(buffer, SIZE, "Permission Denial: "
879 "can't dump AudioPolicyService from pid=%d, uid=%d\n",
880 IPCThreadState::self()->getCallingPid(),
881 IPCThreadState::self()->getCallingUid());
882 result.append(buffer);
883 write(fd, result.string(), result.size());
884 return NO_ERROR;
885}
886
887status_t AudioPolicyService::onTransact(
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800888 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800889 // make sure transactions reserved to AudioFlinger do not come from other processes
890 switch (code) {
891 case TRANSACTION_startOutput:
892 case TRANSACTION_stopOutput:
893 case TRANSACTION_releaseOutput:
894 case TRANSACTION_getInputForAttr:
895 case TRANSACTION_startInput:
896 case TRANSACTION_stopInput:
897 case TRANSACTION_releaseInput:
898 case TRANSACTION_getOutputForEffect:
899 case TRANSACTION_registerEffect:
900 case TRANSACTION_unregisterEffect:
901 case TRANSACTION_setEffectEnabled:
902 case TRANSACTION_getStrategyForStream:
903 case TRANSACTION_getOutputForAttr:
904 case TRANSACTION_moveEffectsToIo:
905 ALOGW("%s: transaction %d received from PID %d",
906 __func__, code, IPCThreadState::self()->getCallingPid());
907 return INVALID_OPERATION;
908 default:
909 break;
910 }
911
912 // make sure the following transactions come from system components
913 switch (code) {
914 case TRANSACTION_setDeviceConnectionState:
915 case TRANSACTION_handleDeviceConfigChange:
916 case TRANSACTION_setPhoneState:
917//FIXME: Allow setForceUse calls from system apps until a better use case routing API is available
918// case TRANSACTION_setForceUse:
919 case TRANSACTION_initStreamVolume:
920 case TRANSACTION_setStreamVolumeIndex:
921 case TRANSACTION_setVolumeIndexForAttributes:
922 case TRANSACTION_getStreamVolumeIndex:
923 case TRANSACTION_getVolumeIndexForAttributes:
924 case TRANSACTION_getMinVolumeIndexForAttributes:
925 case TRANSACTION_getMaxVolumeIndexForAttributes:
926 case TRANSACTION_isStreamActive:
927 case TRANSACTION_isStreamActiveRemotely:
928 case TRANSACTION_isSourceActive:
929 case TRANSACTION_getDevicesForStream:
930 case TRANSACTION_registerPolicyMixes:
931 case TRANSACTION_setMasterMono:
932 case TRANSACTION_getSurroundFormats:
Kriti Dang6537def2021-03-02 13:46:59 +0100933 case TRANSACTION_getReportedSurroundFormats:
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800934 case TRANSACTION_setSurroundFormatEnabled:
935 case TRANSACTION_setAssistantUid:
936 case TRANSACTION_setA11yServicesUids:
937 case TRANSACTION_setUidDeviceAffinities:
938 case TRANSACTION_removeUidDeviceAffinities:
939 case TRANSACTION_setUserIdDeviceAffinities:
940 case TRANSACTION_removeUserIdDeviceAffinities:
941 case TRANSACTION_getHwOffloadEncodingFormatsSupportedForA2DP:
942 case TRANSACTION_listAudioVolumeGroups:
943 case TRANSACTION_getVolumeGroupFromAudioAttributes:
944 case TRANSACTION_acquireSoundTriggerSession:
945 case TRANSACTION_releaseSoundTriggerSession:
946 case TRANSACTION_setRttEnabled:
947 case TRANSACTION_isCallScreenModeSupported:
948 case TRANSACTION_setDevicesRoleForStrategy:
949 case TRANSACTION_setSupportedSystemUsages:
950 case TRANSACTION_removeDevicesRoleForStrategy:
951 case TRANSACTION_getDevicesForRoleAndStrategy:
952 case TRANSACTION_getDevicesForAttributes:
953 case TRANSACTION_setAllowedCapturePolicy:
954 case TRANSACTION_onNewAudioModulesAvailable:
955 case TRANSACTION_setCurrentImeUid:
956 case TRANSACTION_registerSoundTriggerCaptureStateListener:
957 case TRANSACTION_setDevicesRoleForCapturePreset:
958 case TRANSACTION_addDevicesRoleForCapturePreset:
959 case TRANSACTION_removeDevicesRoleForCapturePreset:
960 case TRANSACTION_clearDevicesRoleForCapturePreset:
961 case TRANSACTION_getDevicesForRoleAndCapturePreset: {
962 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
963 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
964 __func__, code, IPCThreadState::self()->getCallingPid(),
965 IPCThreadState::self()->getCallingUid());
966 return INVALID_OPERATION;
967 }
968 } break;
969 default:
970 break;
971 }
972
973 std::string tag("IAudioPolicyService command " + std::to_string(code));
974 TimeCheck check(tag.c_str());
975
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800976 switch (code) {
977 case SHELL_COMMAND_TRANSACTION: {
978 int in = data.readFileDescriptor();
979 int out = data.readFileDescriptor();
980 int err = data.readFileDescriptor();
981 int argc = data.readInt32();
982 Vector<String16> args;
983 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
984 args.add(data.readString16());
985 }
986 sp<IBinder> unusedCallback;
987 sp<IResultReceiver> resultReceiver;
988 status_t status;
989 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
990 return status;
991 }
992 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
993 return status;
994 }
995 status = shellCommand(in, out, err, args);
996 if (resultReceiver != nullptr) {
997 resultReceiver->send(status);
998 }
999 return NO_ERROR;
1000 }
1001 }
1002
Mathias Agopian65ab4712010-07-14 17:59:35 -07001003 return BnAudioPolicyService::onTransact(code, data, reply, flags);
1004}
1005
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001006// ------------------- Shell command implementation -------------------
1007
1008// NOTE: This is a remote API - make sure all args are validated
1009status_t AudioPolicyService::shellCommand(int in, int out, int err, Vector<String16>& args) {
1010 if (!checkCallingPermission(sManageAudioPolicyPermission, nullptr, nullptr)) {
1011 return PERMISSION_DENIED;
1012 }
1013 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
1014 return BAD_VALUE;
1015 }
jovanakbe066e12019-09-02 11:54:39 -07001016 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001017 return handleSetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001018 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001019 return handleResetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -07001020 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001021 return handleGetUidState(args, out, err);
1022 } else if (args.size() == 1 && args[0] == String16("help")) {
1023 printHelp(out);
1024 return NO_ERROR;
1025 }
1026 printHelp(err);
1027 return BAD_VALUE;
1028}
1029
jovanakbe066e12019-09-02 11:54:39 -07001030static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1031 if (userId < 0) {
1032 ALOGE("Invalid user: %d", userId);
1033 dprintf(err, "Invalid user: %d\n", userId);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001034 return BAD_VALUE;
1035 }
jovanakbe066e12019-09-02 11:54:39 -07001036
1037 PermissionController pc;
1038 uid = pc.getPackageUid(packageName, 0);
1039 if (uid <= 0) {
1040 ALOGE("Unknown package: '%s'", String8(packageName).string());
1041 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1042 return BAD_VALUE;
1043 }
1044
1045 uid = multiuser_get_uid(userId, uid);
1046 return NO_ERROR;
1047}
1048
1049status_t AudioPolicyService::handleSetUidState(Vector<String16>& args, int err) {
1050 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
1051 if (!(args.size() == 3 || args.size() == 5)) {
1052 printHelp(err);
1053 return BAD_VALUE;
1054 }
1055
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001056 bool active = false;
1057 if (args[2] == String16("active")) {
1058 active = true;
1059 } else if ((args[2] != String16("idle"))) {
1060 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
1061 return BAD_VALUE;
1062 }
jovanakbe066e12019-09-02 11:54:39 -07001063
1064 int userId = 0;
1065 if (args.size() >= 5 && args[3] == String16("--user")) {
1066 userId = atoi(String8(args[4]));
1067 }
1068
1069 uid_t uid;
1070 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1071 return BAD_VALUE;
1072 }
1073
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001074 sp<UidPolicy> uidPolicy;
1075 {
1076 Mutex::Autolock _l(mLock);
1077 uidPolicy = mUidPolicy;
1078 }
1079 if (uidPolicy) {
1080 uidPolicy->addOverrideUid(uid, active);
1081 return NO_ERROR;
1082 }
1083 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001084}
1085
1086status_t AudioPolicyService::handleResetUidState(Vector<String16>& args, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001087 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1088 if (!(args.size() == 2 || args.size() == 4)) {
1089 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001090 return BAD_VALUE;
1091 }
jovanakbe066e12019-09-02 11:54:39 -07001092
1093 int userId = 0;
1094 if (args.size() >= 4 && args[2] == String16("--user")) {
1095 userId = atoi(String8(args[3]));
1096 }
1097
1098 uid_t uid;
1099 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1100 return BAD_VALUE;
1101 }
1102
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001103 sp<UidPolicy> uidPolicy;
1104 {
1105 Mutex::Autolock _l(mLock);
1106 uidPolicy = mUidPolicy;
1107 }
1108 if (uidPolicy) {
1109 uidPolicy->removeOverrideUid(uid);
1110 return NO_ERROR;
1111 }
1112 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001113}
1114
1115status_t AudioPolicyService::handleGetUidState(Vector<String16>& args, int out, int err) {
jovanakbe066e12019-09-02 11:54:39 -07001116 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
1117 if (!(args.size() == 2 || args.size() == 4)) {
1118 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001119 return BAD_VALUE;
1120 }
jovanakbe066e12019-09-02 11:54:39 -07001121
1122 int userId = 0;
1123 if (args.size() >= 4 && args[2] == String16("--user")) {
1124 userId = atoi(String8(args[3]));
1125 }
1126
1127 uid_t uid;
1128 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
1129 return BAD_VALUE;
1130 }
1131
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001132 sp<UidPolicy> uidPolicy;
1133 {
1134 Mutex::Autolock _l(mLock);
1135 uidPolicy = mUidPolicy;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001136 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001137 if (uidPolicy) {
1138 return dprintf(out, uidPolicy->isUidActive(uid) ? "active\n" : "idle\n");
1139 }
1140 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001141}
1142
1143status_t AudioPolicyService::printHelp(int out) {
1144 return dprintf(out, "Audio policy service commands:\n"
jovanakbe066e12019-09-02 11:54:39 -07001145 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
1146 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
1147 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001148 " help print this message\n");
1149}
1150
1151// ----------- AudioPolicyService::UidPolicy implementation ----------
1152
1153void AudioPolicyService::UidPolicy::registerSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001154 status_t res = mAm.linkToDeath(this);
1155 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001156 | ActivityManager::UID_OBSERVER_IDLE
Eric Laurente8c8b432018-10-17 10:08:02 -07001157 | ActivityManager::UID_OBSERVER_ACTIVE
1158 | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001159 ActivityManager::PROCESS_STATE_UNKNOWN,
1160 String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001161 if (!res) {
1162 Mutex::Autolock _l(mLock);
1163 mObserverRegistered = true;
1164 } else {
1165 ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
Eric Laurent4eb58f12018-12-07 16:41:02 -08001166
Steven Moreland2f348142019-07-02 15:59:07 -07001167 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001168 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001169}
1170
1171void AudioPolicyService::UidPolicy::unregisterSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -07001172 mAm.unlinkToDeath(this);
1173 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001174 Mutex::Autolock _l(mLock);
1175 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001176}
1177
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001178void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
1179 Mutex::Autolock _l(mLock);
1180 mCachedUids.clear();
1181 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001182}
1183
Eric Laurente8c8b432018-10-17 10:08:02 -07001184void AudioPolicyService::UidPolicy::checkRegistered() {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001185 bool needToReregister = false;
1186 {
1187 Mutex::Autolock _l(mLock);
1188 needToReregister = !mObserverRegistered;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001189 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001190 if (needToReregister) {
1191 // Looks like ActivityManager has died previously, attempt to re-register.
1192 registerSelf();
1193 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001194}
1195
1196bool AudioPolicyService::UidPolicy::isUidActive(uid_t uid) {
1197 if (isServiceUid(uid)) return true;
1198 checkRegistered();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001199 {
1200 Mutex::Autolock _l(mLock);
1201 auto overrideIter = mOverrideUids.find(uid);
1202 if (overrideIter != mOverrideUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001203 return overrideIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001204 }
1205 // In an absense of the ActivityManager, assume everything to be active.
1206 if (!mObserverRegistered) return true;
1207 auto cacheIter = mCachedUids.find(uid);
Mikhail Naganoveba668a2018-04-05 08:13:15 -07001208 if (cacheIter != mCachedUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001209 return cacheIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001210 }
1211 }
1212 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001213 bool active = am.isUidActive(uid, String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001214 {
1215 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001216 mCachedUids.insert(std::pair<uid_t,
1217 std::pair<bool, int>>(uid, std::pair<bool, int>(active,
1218 ActivityManager::PROCESS_STATE_UNKNOWN)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001219 }
1220 return active;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001221}
1222
Eric Laurente8c8b432018-10-17 10:08:02 -07001223int AudioPolicyService::UidPolicy::getUidState(uid_t uid) {
1224 if (isServiceUid(uid)) {
1225 return ActivityManager::PROCESS_STATE_TOP;
1226 }
1227 checkRegistered();
1228 {
1229 Mutex::Autolock _l(mLock);
1230 auto overrideIter = mOverrideUids.find(uid);
1231 if (overrideIter != mOverrideUids.end()) {
1232 if (overrideIter->second.first) {
1233 if (overrideIter->second.second != ActivityManager::PROCESS_STATE_UNKNOWN) {
1234 return overrideIter->second.second;
1235 } else {
1236 auto cacheIter = mCachedUids.find(uid);
1237 if (cacheIter != mCachedUids.end()) {
1238 return cacheIter->second.second;
1239 }
1240 }
1241 }
1242 return ActivityManager::PROCESS_STATE_UNKNOWN;
1243 }
1244 // In an absense of the ActivityManager, assume everything to be active.
1245 if (!mObserverRegistered) {
1246 return ActivityManager::PROCESS_STATE_TOP;
1247 }
1248 auto cacheIter = mCachedUids.find(uid);
1249 if (cacheIter != mCachedUids.end()) {
1250 if (cacheIter->second.first) {
1251 return cacheIter->second.second;
1252 } else {
1253 return ActivityManager::PROCESS_STATE_UNKNOWN;
1254 }
1255 }
1256 }
1257 ActivityManager am;
Hui Yu12c7ec72020-05-04 17:40:52 +00001258 bool active = am.isUidActive(uid, String16("audioserver"));
Eric Laurente8c8b432018-10-17 10:08:02 -07001259 int state = ActivityManager::PROCESS_STATE_UNKNOWN;
1260 if (active) {
1261 state = am.getUidProcessState(uid, String16("audioserver"));
1262 }
1263 {
1264 Mutex::Autolock _l(mLock);
1265 mCachedUids.insert(std::pair<uid_t,
1266 std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
1267 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001268
Eric Laurente8c8b432018-10-17 10:08:02 -07001269 return state;
1270}
1271
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001272void AudioPolicyService::UidPolicy::onUidActive(uid_t uid) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001273 updateUid(&mCachedUids, uid, true, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001274}
1275
1276void AudioPolicyService::UidPolicy::onUidGone(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001277 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, false);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001278}
1279
1280void AudioPolicyService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001281 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001282}
1283
Eric Laurente8c8b432018-10-17 10:08:02 -07001284void AudioPolicyService::UidPolicy::onUidStateChanged(uid_t uid,
1285 int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07001286 int64_t procStateSeq __unused,
1287 int32_t capability __unused) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001288 if (procState != ActivityManager::PROCESS_STATE_UNKNOWN) {
1289 updateUid(&mCachedUids, uid, true, procState, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001290 }
1291}
1292
1293void AudioPolicyService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001294 updateUid(&mOverrideUids, uid, active, ActivityManager::PROCESS_STATE_UNKNOWN, insert);
1295}
1296
1297void AudioPolicyService::UidPolicy::notifyService() {
1298 sp<AudioPolicyService> service = mService.promote();
1299 if (service != nullptr) {
1300 service->updateUidStates();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001301 }
1302}
1303
Eric Laurente8c8b432018-10-17 10:08:02 -07001304void AudioPolicyService::UidPolicy::updateUid(std::unordered_map<uid_t,
1305 std::pair<bool, int>> *uids,
1306 uid_t uid,
1307 bool active,
1308 int state,
1309 bool insert) {
1310 if (isServiceUid(uid)) {
1311 return;
1312 }
1313 bool wasActive = isUidActive(uid);
1314 int previousState = getUidState(uid);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001315 {
1316 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001317 updateUidLocked(uids, uid, active, state, insert);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001318 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001319 if (wasActive != isUidActive(uid) || state != previousState) {
1320 notifyService();
1321 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001322}
1323
Eric Laurente8c8b432018-10-17 10:08:02 -07001324void AudioPolicyService::UidPolicy::updateUidLocked(std::unordered_map<uid_t,
1325 std::pair<bool, int>> *uids,
1326 uid_t uid,
1327 bool active,
1328 int state,
1329 bool insert) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001330 auto it = uids->find(uid);
1331 if (it != uids->end()) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001332 if (insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001333 if (state == ActivityManager::PROCESS_STATE_UNKNOWN) {
1334 it->second.first = active;
1335 }
1336 if (it->second.first) {
1337 it->second.second = state;
1338 } else {
1339 it->second.second = ActivityManager::PROCESS_STATE_UNKNOWN;
1340 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001341 } else {
1342 uids->erase(it);
1343 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001344 } else if (insert && (state == ActivityManager::PROCESS_STATE_UNKNOWN)) {
1345 uids->insert(std::pair<uid_t, std::pair<bool, int>>(uid,
1346 std::pair<bool, int>(active, state)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001347 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001348}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001349
Eric Laurent4eb58f12018-12-07 16:41:02 -08001350bool AudioPolicyService::UidPolicy::isA11yOnTop() {
1351 for (const auto &uid : mCachedUids) {
Eric Laurent47670c92019-08-28 16:59:05 -07001352 if (!isA11yUid(uid.first)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001353 continue;
1354 }
Amith Yamasanibcbb3002019-01-23 13:53:33 -08001355 if (uid.second.second >= ActivityManager::PROCESS_STATE_TOP
1356 && uid.second.second <= ActivityManager::PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001357 return true;
1358 }
1359 }
1360 return false;
1361}
1362
Eric Laurentb78763e2018-10-17 10:08:02 -07001363bool AudioPolicyService::UidPolicy::isA11yUid(uid_t uid)
1364{
1365 std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid);
1366 return it != mA11yUids.end();
1367}
1368
Michael Groovercfd28302018-12-11 19:16:46 -08001369// ----------- AudioPolicyService::SensorPrivacyService implementation ----------
1370void AudioPolicyService::SensorPrivacyPolicy::registerSelf() {
1371 SensorPrivacyManager spm;
1372 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1373 spm.addSensorPrivacyListener(this);
1374}
1375
Evan Severson241d9592021-01-08 12:16:02 -08001376void AudioPolicyService::SensorPrivacyPolicy::registerSelfForMicrophoneOnly(int userId) {
1377 SensorPrivacyManager spm;
1378 mSensorPrivacyEnabled = spm.isIndividualSensorPrivacyEnabled(userId,
1379 SensorPrivacyManager::INDIVIDUAL_SENSOR_MICROPHONE);
1380 spm.addIndividualSensorPrivacyListener(userId,
1381 SensorPrivacyManager::INDIVIDUAL_SENSOR_MICROPHONE, this);
1382}
1383
Michael Groovercfd28302018-12-11 19:16:46 -08001384void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
1385 SensorPrivacyManager spm;
1386 spm.removeSensorPrivacyListener(this);
1387}
1388
1389bool AudioPolicyService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1390 return mSensorPrivacyEnabled;
1391}
1392
1393binder::Status AudioPolicyService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
1394 mSensorPrivacyEnabled = enabled;
1395 sp<AudioPolicyService> service = mService.promote();
1396 if (service != nullptr) {
1397 service->updateUidStates();
1398 }
1399 return binder::Status::ok();
1400}
1401
Mathias Agopian65ab4712010-07-14 17:59:35 -07001402// ----------- AudioPolicyService::AudioCommandThread implementation ----------
1403
Eric Laurentbfb1b832013-01-07 09:53:42 -08001404AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
1405 const wp<AudioPolicyService>& service)
1406 : Thread(false), mName(name), mService(service)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001407{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001408}
1409
1410
1411AudioPolicyService::AudioCommandThread::~AudioCommandThread()
1412{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001413 if (!mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001414 release_wake_lock(mName.string());
1415 }
1416 mAudioCommands.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001417}
1418
1419void AudioPolicyService::AudioCommandThread::onFirstRef()
1420{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001421 run(mName.string(), ANDROID_PRIORITY_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001422}
1423
1424bool AudioPolicyService::AudioCommandThread::threadLoop()
1425{
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001426 nsecs_t waitTime = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001427
1428 mLock.lock();
1429 while (!exitPending())
1430 {
Eric Laurent59a89232014-06-08 14:14:17 -07001431 sp<AudioPolicyService> svc;
1432 while (!mAudioCommands.isEmpty() && !exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001433 nsecs_t curTime = systemTime();
1434 // commands are sorted by increasing time stamp: execute them from index 0 and up
1435 if (mAudioCommands[0]->mTime <= curTime) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001436 sp<AudioCommand> command = mAudioCommands[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001437 mAudioCommands.removeAt(0);
Eric Laurent0ede8922014-05-09 18:04:42 -07001438 mLastCommand = command;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001439
1440 switch (command->mCommand) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001441 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001442 VolumeData *data = (VolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001443 ALOGV("AudioCommandThread() processing set volume stream %d, \
Eric Laurentde070132010-07-13 04:45:46 -07001444 volume %f, output %d", data->mStream, data->mVolume, data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001445 mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07001446 command->mStatus = AudioSystem::setStreamVolume(data->mStream,
1447 data->mVolume,
1448 data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001449 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001450 }break;
1451 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001452 ParametersData *data = (ParametersData *)command->mParam.get();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001453 ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
1454 data->mKeyValuePairs.string(), data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001455 mLock.unlock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001456 command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
Andy Hungfe726a62018-09-27 15:17:25 -07001457 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001458 }break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001459 case SET_VOICE_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001460 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001461 ALOGV("AudioCommandThread() processing set voice volume volume %f",
Eric Laurentde070132010-07-13 04:45:46 -07001462 data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001463 mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001464 command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001465 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001466 }break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001467 case STOP_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001468 StopOutputData *data = (StopOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001469 ALOGV("AudioCommandThread() processing stop output portId %d",
1470 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001471 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001472 if (svc == 0) {
1473 break;
1474 }
1475 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001476 svc->doStopOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001477 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001478 }break;
1479 case RELEASE_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001480 ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001481 ALOGV("AudioCommandThread() processing release output portId %d",
1482 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001483 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001484 if (svc == 0) {
1485 break;
1486 }
1487 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001488 svc->doReleaseOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001489 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001490 }break;
Eric Laurent951f4552014-05-20 10:48:17 -07001491 case CREATE_AUDIO_PATCH: {
1492 CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
1493 ALOGV("AudioCommandThread() processing create audio patch");
1494 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1495 if (af == 0) {
1496 command->mStatus = PERMISSION_DENIED;
1497 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001498 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001499 command->mStatus = af->createAudioPatch(&data->mPatch, &data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001500 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001501 }
1502 } break;
1503 case RELEASE_AUDIO_PATCH: {
1504 ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
1505 ALOGV("AudioCommandThread() processing release audio patch");
1506 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1507 if (af == 0) {
1508 command->mStatus = PERMISSION_DENIED;
1509 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001510 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001511 command->mStatus = af->releaseAudioPatch(data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001512 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001513 }
1514 } break;
Eric Laurentb52c1522014-05-20 11:27:36 -07001515 case UPDATE_AUDIOPORT_LIST: {
1516 ALOGV("AudioCommandThread() processing update audio port list");
Eric Laurent59a89232014-06-08 14:14:17 -07001517 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001518 if (svc == 0) {
1519 break;
1520 }
1521 mLock.unlock();
1522 svc->doOnAudioPortListUpdate();
1523 mLock.lock();
1524 }break;
1525 case UPDATE_AUDIOPATCH_LIST: {
1526 ALOGV("AudioCommandThread() processing update audio patch list");
Eric Laurent59a89232014-06-08 14:14:17 -07001527 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001528 if (svc == 0) {
1529 break;
1530 }
1531 mLock.unlock();
1532 svc->doOnAudioPatchListUpdate();
1533 mLock.lock();
1534 }break;
François Gaffiecfe17322018-11-07 13:41:29 +01001535 case CHANGED_AUDIOVOLUMEGROUP: {
1536 AudioVolumeGroupData *data =
1537 static_cast<AudioVolumeGroupData *>(command->mParam.get());
1538 ALOGV("AudioCommandThread() processing update audio volume group");
1539 svc = mService.promote();
1540 if (svc == 0) {
1541 break;
1542 }
1543 mLock.unlock();
1544 svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
1545 mLock.lock();
1546 }break;
Eric Laurente1715a42014-05-20 11:30:42 -07001547 case SET_AUDIOPORT_CONFIG: {
1548 SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
1549 ALOGV("AudioCommandThread() processing set port config");
1550 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1551 if (af == 0) {
1552 command->mStatus = PERMISSION_DENIED;
1553 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001554 mLock.unlock();
Eric Laurente1715a42014-05-20 11:30:42 -07001555 command->mStatus = af->setAudioPortConfig(&data->mConfig);
Andy Hungfe726a62018-09-27 15:17:25 -07001556 mLock.lock();
Eric Laurente1715a42014-05-20 11:30:42 -07001557 }
1558 } break;
Jean-Michel Trivide801052015-04-14 19:10:14 -07001559 case DYN_POLICY_MIX_STATE_UPDATE: {
1560 DynPolicyMixStateUpdateData *data =
1561 (DynPolicyMixStateUpdateData *)command->mParam.get();
Jean-Michel Trivide801052015-04-14 19:10:14 -07001562 ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
1563 data->mRegId.string(), data->mState);
1564 svc = mService.promote();
1565 if (svc == 0) {
1566 break;
1567 }
1568 mLock.unlock();
1569 svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
1570 mLock.lock();
1571 } break;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001572 case RECORDING_CONFIGURATION_UPDATE: {
1573 RecordingConfigurationUpdateData *data =
1574 (RecordingConfigurationUpdateData *)command->mParam.get();
1575 ALOGV("AudioCommandThread() processing recording configuration update");
1576 svc = mService.promote();
1577 if (svc == 0) {
1578 break;
1579 }
1580 mLock.unlock();
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001581 svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -08001582 &data->mClientConfig, data->mClientEffects,
1583 &data->mDeviceConfig, data->mEffects,
1584 data->mPatchHandle, data->mSource);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001585 mLock.lock();
1586 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001587 case SET_EFFECT_SUSPENDED: {
1588 SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
1589 ALOGV("AudioCommandThread() processing set effect suspended");
1590 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1591 if (af != 0) {
1592 mLock.unlock();
1593 af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
1594 mLock.lock();
1595 }
1596 } break;
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001597 case AUDIO_MODULES_UPDATE: {
1598 ALOGV("AudioCommandThread() processing audio modules update");
1599 svc = mService.promote();
1600 if (svc == 0) {
1601 break;
1602 }
1603 mLock.unlock();
1604 svc->doOnNewAudioModulesAvailable();
1605 mLock.lock();
1606 } break;
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07001607 case ROUTING_UPDATED: {
1608 ALOGV("AudioCommandThread() processing routing update");
1609 svc = mService.promote();
1610 if (svc == 0) {
1611 break;
1612 }
1613 mLock.unlock();
1614 svc->doOnRoutingUpdated();
1615 mLock.lock();
1616 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001617
Mathias Agopian65ab4712010-07-14 17:59:35 -07001618 default:
Steve Block5ff1dd52012-01-05 23:22:43 +00001619 ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001620 }
Eric Laurent0ede8922014-05-09 18:04:42 -07001621 {
1622 Mutex::Autolock _l(command->mLock);
1623 if (command->mWaitStatus) {
1624 command->mWaitStatus = false;
1625 command->mCond.signal();
1626 }
1627 }
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001628 waitTime = -1;
Zach Janga754b4f2015-10-27 01:29:34 +00001629 // release mLock before releasing strong reference on the service as
1630 // AudioPolicyService destructor calls AudioCommandThread::exit() which
1631 // acquires mLock.
1632 mLock.unlock();
1633 svc.clear();
1634 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001635 } else {
1636 waitTime = mAudioCommands[0]->mTime - curTime;
1637 break;
1638 }
1639 }
Zach Janga754b4f2015-10-27 01:29:34 +00001640
1641 // release delayed commands wake lock if the queue is empty
1642 if (mAudioCommands.isEmpty()) {
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07001643 release_wake_lock(mName.string());
Zach Janga754b4f2015-10-27 01:29:34 +00001644 }
1645
1646 // At this stage we have either an empty command queue or the first command in the queue
1647 // has a finite delay. So unless we are exiting it is safe to wait.
1648 if (!exitPending()) {
Eric Laurent59a89232014-06-08 14:14:17 -07001649 ALOGV("AudioCommandThread() going to sleep");
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001650 if (waitTime == -1) {
1651 mWaitWorkCV.wait(mLock);
1652 } else {
1653 mWaitWorkCV.waitRelative(mLock, waitTime);
1654 }
Eric Laurent59a89232014-06-08 14:14:17 -07001655 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001656 }
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07001657 // release delayed commands wake lock before quitting
1658 if (!mAudioCommands.isEmpty()) {
1659 release_wake_lock(mName.string());
1660 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001661 mLock.unlock();
1662 return false;
1663}
1664
1665status_t AudioPolicyService::AudioCommandThread::dump(int fd)
1666{
1667 const size_t SIZE = 256;
1668 char buffer[SIZE];
1669 String8 result;
1670
1671 snprintf(buffer, SIZE, "AudioCommandThread %p Dump\n", this);
1672 result.append(buffer);
1673 write(fd, result.string(), result.size());
1674
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001675 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001676 if (!locked) {
1677 String8 result2(kCmdDeadlockedString);
1678 write(fd, result2.string(), result2.size());
1679 }
1680
1681 snprintf(buffer, SIZE, "- Commands:\n");
1682 result = String8(buffer);
1683 result.append(" Command Time Wait pParam\n");
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001684 for (size_t i = 0; i < mAudioCommands.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001685 mAudioCommands[i]->dump(buffer, SIZE);
1686 result.append(buffer);
1687 }
1688 result.append(" Last Command\n");
Eric Laurent0ede8922014-05-09 18:04:42 -07001689 if (mLastCommand != 0) {
1690 mLastCommand->dump(buffer, SIZE);
1691 result.append(buffer);
1692 } else {
1693 result.append(" none\n");
1694 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001695
1696 write(fd, result.string(), result.size());
1697
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001698 dumpReleaseLock(mLock, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001699
1700 return NO_ERROR;
1701}
1702
Glenn Kastenfff6d712012-01-12 16:38:12 -08001703status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
Eric Laurentde070132010-07-13 04:45:46 -07001704 float volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001705 audio_io_handle_t output,
Eric Laurentde070132010-07-13 04:45:46 -07001706 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001707{
Eric Laurent0ede8922014-05-09 18:04:42 -07001708 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001709 command->mCommand = SET_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07001710 sp<VolumeData> data = new VolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001711 data->mStream = stream;
1712 data->mVolume = volume;
1713 data->mIO = output;
1714 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07001715 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01001716 ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
Eric Laurentde070132010-07-13 04:45:46 -07001717 stream, volume, output);
Eric Laurent0ede8922014-05-09 18:04:42 -07001718 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001719}
1720
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001721status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
Dima Zavinfce7a472011-04-19 22:30:36 -07001722 const char *keyValuePairs,
Eric Laurentde070132010-07-13 04:45:46 -07001723 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001724{
Eric Laurent0ede8922014-05-09 18:04:42 -07001725 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001726 command->mCommand = SET_PARAMETERS;
Eric Laurent0ede8922014-05-09 18:04:42 -07001727 sp<ParametersData> data = new ParametersData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001728 data->mIO = ioHandle;
Dima Zavinfce7a472011-04-19 22:30:36 -07001729 data->mKeyValuePairs = String8(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001730 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07001731 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01001732 ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
Dima Zavinfce7a472011-04-19 22:30:36 -07001733 keyValuePairs, ioHandle, delayMs);
Eric Laurent0ede8922014-05-09 18:04:42 -07001734 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001735}
1736
1737status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
1738{
Eric Laurent0ede8922014-05-09 18:04:42 -07001739 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001740 command->mCommand = SET_VOICE_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07001741 sp<VoiceVolumeData> data = new VoiceVolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001742 data->mVolume = volume;
1743 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07001744 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01001745 ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
Eric Laurent0ede8922014-05-09 18:04:42 -07001746 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001747}
1748
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001749void AudioPolicyService::AudioCommandThread::setEffectSuspendedCommand(int effectId,
1750 audio_session_t sessionId,
1751 bool suspended)
1752{
1753 sp<AudioCommand> command = new AudioCommand();
1754 command->mCommand = SET_EFFECT_SUSPENDED;
1755 sp<SetEffectSuspendedData> data = new SetEffectSuspendedData();
1756 data->mEffectId = effectId;
1757 data->mSessionId = sessionId;
1758 data->mSuspended = suspended;
1759 command->mParam = data;
1760 ALOGV("AudioCommandThread() adding set suspended effectId %d sessionId %d suspended %d",
1761 effectId, sessionId, suspended);
1762 sendCommand(command);
1763}
1764
1765
Eric Laurentd7fe0862018-07-14 16:48:01 -07001766void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001767{
Eric Laurent0ede8922014-05-09 18:04:42 -07001768 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001769 command->mCommand = STOP_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07001770 sp<StopOutputData> data = new StopOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001771 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01001772 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07001773 ALOGV("AudioCommandThread() adding stop output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07001774 sendCommand(command);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001775}
1776
Eric Laurentd7fe0862018-07-14 16:48:01 -07001777void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001778{
Eric Laurent0ede8922014-05-09 18:04:42 -07001779 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001780 command->mCommand = RELEASE_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07001781 sp<ReleaseOutputData> data = new ReleaseOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001782 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01001783 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07001784 ALOGV("AudioCommandThread() adding release output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07001785 sendCommand(command);
1786}
1787
Eric Laurent951f4552014-05-20 10:48:17 -07001788status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
1789 const struct audio_patch *patch,
1790 audio_patch_handle_t *handle,
1791 int delayMs)
1792{
1793 status_t status = NO_ERROR;
1794
1795 sp<AudioCommand> command = new AudioCommand();
1796 command->mCommand = CREATE_AUDIO_PATCH;
1797 CreateAudioPatchData *data = new CreateAudioPatchData();
1798 data->mPatch = *patch;
1799 data->mHandle = *handle;
1800 command->mParam = data;
1801 command->mWaitStatus = true;
1802 ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
1803 status = sendCommand(command, delayMs);
1804 if (status == NO_ERROR) {
1805 *handle = data->mHandle;
1806 }
1807 return status;
1808}
1809
1810status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
1811 int delayMs)
1812{
1813 sp<AudioCommand> command = new AudioCommand();
1814 command->mCommand = RELEASE_AUDIO_PATCH;
1815 ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
1816 data->mHandle = handle;
1817 command->mParam = data;
1818 command->mWaitStatus = true;
1819 ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
1820 return sendCommand(command, delayMs);
1821}
1822
Eric Laurentb52c1522014-05-20 11:27:36 -07001823void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
1824{
1825 sp<AudioCommand> command = new AudioCommand();
1826 command->mCommand = UPDATE_AUDIOPORT_LIST;
1827 ALOGV("AudioCommandThread() adding update audio port list");
1828 sendCommand(command);
1829}
1830
1831void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
1832{
1833 sp<AudioCommand>command = new AudioCommand();
1834 command->mCommand = UPDATE_AUDIOPATCH_LIST;
1835 ALOGV("AudioCommandThread() adding update audio patch list");
1836 sendCommand(command);
1837}
1838
François Gaffiecfe17322018-11-07 13:41:29 +01001839void AudioPolicyService::AudioCommandThread::changeAudioVolumeGroupCommand(volume_group_t group,
1840 int flags)
1841{
1842 sp<AudioCommand>command = new AudioCommand();
1843 command->mCommand = CHANGED_AUDIOVOLUMEGROUP;
1844 AudioVolumeGroupData *data= new AudioVolumeGroupData();
1845 data->mGroup = group;
1846 data->mFlags = flags;
1847 command->mParam = data;
1848 ALOGV("AudioCommandThread() adding audio volume group changed");
1849 sendCommand(command);
1850}
1851
Eric Laurente1715a42014-05-20 11:30:42 -07001852status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
1853 const struct audio_port_config *config, int delayMs)
1854{
1855 sp<AudioCommand> command = new AudioCommand();
1856 command->mCommand = SET_AUDIOPORT_CONFIG;
1857 SetAudioPortConfigData *data = new SetAudioPortConfigData();
1858 data->mConfig = *config;
1859 command->mParam = data;
1860 command->mWaitStatus = true;
1861 ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
1862 return sendCommand(command, delayMs);
1863}
1864
Jean-Michel Trivide801052015-04-14 19:10:14 -07001865void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001866 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -07001867{
1868 sp<AudioCommand> command = new AudioCommand();
1869 command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
1870 DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
1871 data->mRegId = regId;
1872 data->mState = state;
1873 command->mParam = data;
1874 ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
1875 regId.string(), state);
1876 sendCommand(command);
1877}
1878
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001879void AudioPolicyService::AudioCommandThread::recordingConfigurationUpdateCommand(
Eric Laurenta9f86652018-11-28 17:23:11 -08001880 int event,
1881 const record_client_info_t *clientInfo,
1882 const audio_config_base_t *clientConfig,
1883 std::vector<effect_descriptor_t> clientEffects,
1884 const audio_config_base_t *deviceConfig,
1885 std::vector<effect_descriptor_t> effects,
1886 audio_patch_handle_t patchHandle,
1887 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001888{
1889 sp<AudioCommand>command = new AudioCommand();
1890 command->mCommand = RECORDING_CONFIGURATION_UPDATE;
1891 RecordingConfigurationUpdateData *data = new RecordingConfigurationUpdateData();
1892 data->mEvent = event;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001893 data->mClientInfo = *clientInfo;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08001894 data->mClientConfig = *clientConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08001895 data->mClientEffects = clientEffects;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08001896 data->mDeviceConfig = *deviceConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08001897 data->mEffects = effects;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08001898 data->mPatchHandle = patchHandle;
Eric Laurenta9f86652018-11-28 17:23:11 -08001899 data->mSource = source;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001900 command->mParam = data;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001901 ALOGV("AudioCommandThread() adding recording configuration update event %d, source %d uid %u",
1902 event, clientInfo->source, clientInfo->uid);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001903 sendCommand(command);
1904}
1905
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001906void AudioPolicyService::AudioCommandThread::audioModulesUpdateCommand()
1907{
1908 sp<AudioCommand> command = new AudioCommand();
1909 command->mCommand = AUDIO_MODULES_UPDATE;
1910 sendCommand(command);
1911}
1912
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07001913void AudioPolicyService::AudioCommandThread::routingChangedCommand()
1914{
1915 sp<AudioCommand>command = new AudioCommand();
1916 command->mCommand = ROUTING_UPDATED;
1917 ALOGV("AudioCommandThread() adding routing update");
1918 sendCommand(command);
1919}
1920
Eric Laurent0ede8922014-05-09 18:04:42 -07001921status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
1922{
1923 {
1924 Mutex::Autolock _l(mLock);
1925 insertCommand_l(command, delayMs);
1926 mWaitWorkCV.signal();
1927 }
1928 Mutex::Autolock _l(command->mLock);
1929 while (command->mWaitStatus) {
1930 nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
1931 if (command->mCond.waitRelative(command->mLock, timeOutNs) != NO_ERROR) {
1932 command->mStatus = TIMED_OUT;
1933 command->mWaitStatus = false;
1934 }
1935 }
1936 return command->mStatus;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001937}
1938
Mathias Agopian65ab4712010-07-14 17:59:35 -07001939// insertCommand_l() must be called with mLock held
Eric Laurent0ede8922014-05-09 18:04:42 -07001940void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001941{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001942 ssize_t i; // not size_t because i will count down to -1
Eric Laurent0ede8922014-05-09 18:04:42 -07001943 Vector < sp<AudioCommand> > removedCommands;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001944 command->mTime = systemTime() + milliseconds(delayMs);
1945
1946 // acquire wake lock to make sure delayed commands are processed
Eric Laurentbfb1b832013-01-07 09:53:42 -08001947 if (mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001948 acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.string());
1949 }
1950
1951 // check same pending commands with later time stamps and eliminate them
Ivan Lozano5ff158f2017-10-30 09:06:24 -07001952 for (i = (ssize_t)mAudioCommands.size()-1; i >= 0; i--) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001953 sp<AudioCommand> command2 = mAudioCommands[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001954 // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
1955 if (command2->mTime <= command->mTime) break;
Eric Laurente45b48a2014-09-04 16:40:57 -07001956
1957 // create audio patch or release audio patch commands are equivalent
1958 // with regard to filtering
1959 if ((command->mCommand == CREATE_AUDIO_PATCH) ||
1960 (command->mCommand == RELEASE_AUDIO_PATCH)) {
1961 if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
1962 (command2->mCommand != RELEASE_AUDIO_PATCH)) {
1963 continue;
1964 }
1965 } else if (command2->mCommand != command->mCommand) continue;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001966
1967 switch (command->mCommand) {
1968 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001969 ParametersData *data = (ParametersData *)command->mParam.get();
1970 ParametersData *data2 = (ParametersData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001971 if (data->mIO != data2->mIO) break;
Steve Block3856b092011-10-20 11:56:00 +01001972 ALOGV("Comparing parameter command %s to new command %s",
Eric Laurentde070132010-07-13 04:45:46 -07001973 data2->mKeyValuePairs.string(), data->mKeyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001974 AudioParameter param = AudioParameter(data->mKeyValuePairs);
1975 AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
1976 for (size_t j = 0; j < param.size(); j++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001977 String8 key;
1978 String8 value;
1979 param.getAt(j, key, value);
1980 for (size_t k = 0; k < param2.size(); k++) {
1981 String8 key2;
1982 String8 value2;
1983 param2.getAt(k, key2, value2);
1984 if (key2 == key) {
1985 param2.remove(key2);
1986 ALOGV("Filtering out parameter %s", key2.string());
1987 break;
1988 }
1989 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001990 }
1991 // if all keys have been filtered out, remove the command.
1992 // otherwise, update the key value pairs
1993 if (param2.size() == 0) {
1994 removedCommands.add(command2);
1995 } else {
1996 data2->mKeyValuePairs = param2.toString();
1997 }
Eric Laurent21e54562013-09-23 12:08:05 -07001998 command->mTime = command2->mTime;
1999 // force delayMs to non 0 so that code below does not request to wait for
2000 // command status as the command is now delayed
2001 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002002 } break;
2003
2004 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07002005 VolumeData *data = (VolumeData *)command->mParam.get();
2006 VolumeData *data2 = (VolumeData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002007 if (data->mIO != data2->mIO) break;
2008 if (data->mStream != data2->mStream) break;
Steve Block3856b092011-10-20 11:56:00 +01002009 ALOGV("Filtering out volume command on output %d for stream %d",
Eric Laurentde070132010-07-13 04:45:46 -07002010 data->mIO, data->mStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002011 removedCommands.add(command2);
Eric Laurent21e54562013-09-23 12:08:05 -07002012 command->mTime = command2->mTime;
2013 // force delayMs to non 0 so that code below does not request to wait for
2014 // command status as the command is now delayed
2015 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002016 } break;
Eric Laurente45b48a2014-09-04 16:40:57 -07002017
Eric Laurentbaf35fe2016-07-27 15:36:53 -07002018 case SET_VOICE_VOLUME: {
2019 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
2020 VoiceVolumeData *data2 = (VoiceVolumeData *)command2->mParam.get();
2021 ALOGV("Filtering out voice volume command value %f replaced by %f",
2022 data2->mVolume, data->mVolume);
2023 removedCommands.add(command2);
2024 command->mTime = command2->mTime;
2025 // force delayMs to non 0 so that code below does not request to wait for
2026 // command status as the command is now delayed
2027 delayMs = 1;
2028 } break;
2029
Eric Laurente45b48a2014-09-04 16:40:57 -07002030 case CREATE_AUDIO_PATCH:
2031 case RELEASE_AUDIO_PATCH: {
2032 audio_patch_handle_t handle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002033 struct audio_patch patch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002034 if (command->mCommand == CREATE_AUDIO_PATCH) {
2035 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002036 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002037 } else {
2038 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
Mikhail Naganov7be71d22018-05-23 16:51:46 -07002039 memset(&patch, 0, sizeof(patch));
Eric Laurente45b48a2014-09-04 16:40:57 -07002040 }
2041 audio_patch_handle_t handle2;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002042 struct audio_patch patch2;
Eric Laurente45b48a2014-09-04 16:40:57 -07002043 if (command2->mCommand == CREATE_AUDIO_PATCH) {
2044 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002045 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07002046 } else {
2047 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
Glenn Kastenf60b6b62015-07-06 10:53:26 -07002048 memset(&patch2, 0, sizeof(patch2));
Eric Laurente45b48a2014-09-04 16:40:57 -07002049 }
2050 if (handle != handle2) break;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07002051 /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
2052 same output. */
2053 if( (command->mCommand == CREATE_AUDIO_PATCH) &&
2054 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
2055 bool isOutputDiff = false;
2056 if (patch.num_sources == patch2.num_sources) {
2057 for (unsigned count = 0; count < patch.num_sources; count++) {
2058 if (patch.sources[count].id != patch2.sources[count].id) {
2059 isOutputDiff = true;
2060 break;
2061 }
2062 }
2063 if (isOutputDiff)
2064 break;
2065 }
2066 }
Eric Laurente45b48a2014-09-04 16:40:57 -07002067 ALOGV("Filtering out %s audio patch command for handle %d",
2068 (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
2069 removedCommands.add(command2);
2070 command->mTime = command2->mTime;
2071 // force delayMs to non 0 so that code below does not request to wait for
2072 // command status as the command is now delayed
2073 delayMs = 1;
2074 } break;
2075
Jean-Michel Trivide801052015-04-14 19:10:14 -07002076 case DYN_POLICY_MIX_STATE_UPDATE: {
2077
2078 } break;
2079
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002080 case RECORDING_CONFIGURATION_UPDATE: {
2081
2082 } break;
2083
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07002084 case ROUTING_UPDATED: {
2085
2086 } break;
2087
Mathias Agopian65ab4712010-07-14 17:59:35 -07002088 default:
2089 break;
2090 }
2091 }
2092
2093 // remove filtered commands
2094 for (size_t j = 0; j < removedCommands.size(); j++) {
2095 // removed commands always have time stamps greater than current command
2096 for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
Eric Laurent0ede8922014-05-09 18:04:42 -07002097 if (mAudioCommands[k].get() == removedCommands[j].get()) {
Steve Block3856b092011-10-20 11:56:00 +01002098 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002099 mAudioCommands.removeAt(k);
2100 break;
2101 }
2102 }
2103 }
2104 removedCommands.clear();
2105
Eric Laurentaa79bef2015-01-15 14:33:51 -08002106 // Disable wait for status if delay is not 0.
2107 // Except for create audio patch command because the returned patch handle
2108 // is needed by audio policy manager
2109 if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
Eric Laurentcec4abb2012-07-03 12:23:02 -07002110 command->mWaitStatus = false;
2111 }
Eric Laurentcec4abb2012-07-03 12:23:02 -07002112
Mathias Agopian65ab4712010-07-14 17:59:35 -07002113 // insert command at the right place according to its time stamp
Eric Laurent1e693b52014-07-09 15:03:28 -07002114 ALOGV("inserting command: %d at index %zd, num commands %zu",
2115 command->mCommand, i+1, mAudioCommands.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002116 mAudioCommands.insertAt(command, i + 1);
2117}
2118
2119void AudioPolicyService::AudioCommandThread::exit()
2120{
Steve Block3856b092011-10-20 11:56:00 +01002121 ALOGV("AudioCommandThread::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002122 {
2123 AutoMutex _l(mLock);
2124 requestExit();
2125 mWaitWorkCV.signal();
2126 }
Zach Janga754b4f2015-10-27 01:29:34 +00002127 // Note that we can call it from the thread loop if all other references have been released
2128 // but it will safely return WOULD_BLOCK in this case
Mathias Agopian65ab4712010-07-14 17:59:35 -07002129 requestExitAndWait();
2130}
2131
2132void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
2133{
2134 snprintf(buffer, size, " %02d %06d.%03d %01u %p\n",
2135 mCommand,
2136 (int)ns2s(mTime),
2137 (int)ns2ms(mTime)%1000,
2138 mWaitStatus,
Eric Laurent0ede8922014-05-09 18:04:42 -07002139 mParam.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002140}
2141
Dima Zavinfce7a472011-04-19 22:30:36 -07002142/******* helpers for the service_ops callbacks defined below *********/
2143void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
2144 const char *keyValuePairs,
2145 int delayMs)
2146{
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002147 mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
Dima Zavinfce7a472011-04-19 22:30:36 -07002148 delayMs);
2149}
2150
2151int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
2152 float volume,
2153 audio_io_handle_t output,
2154 int delayMs)
2155{
Glenn Kastenfff6d712012-01-12 16:38:12 -08002156 return (int)mAudioCommandThread->volumeCommand(stream, volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002157 output, delayMs);
Dima Zavinfce7a472011-04-19 22:30:36 -07002158}
2159
Dima Zavinfce7a472011-04-19 22:30:36 -07002160int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
2161{
2162 return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
2163}
2164
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002165void AudioPolicyService::setEffectSuspended(int effectId,
2166 audio_session_t sessionId,
2167 bool suspended)
2168{
2169 mAudioCommandThread->setEffectSuspendedCommand(effectId, sessionId, suspended);
2170}
2171
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002172Status AudioPolicyService::onNewAudioModulesAvailable()
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002173{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07002174 mOutputCommandThread->audioModulesUpdateCommand();
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002175 return Status::ok();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00002176}
2177
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002178
Dima Zavinfce7a472011-04-19 22:30:36 -07002179extern "C" {
Eric Laurent2d388ec2014-03-07 13:25:54 -08002180audio_module_handle_t aps_load_hw_module(void *service __unused,
2181 const char *name);
2182audio_io_handle_t aps_open_output(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002183 audio_devices_t *pDevices,
2184 uint32_t *pSamplingRate,
2185 audio_format_t *pFormat,
2186 audio_channel_mask_t *pChannelMask,
2187 uint32_t *pLatencyMs,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002188 audio_output_flags_t flags);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002189
Eric Laurent2d388ec2014-03-07 13:25:54 -08002190audio_io_handle_t aps_open_output_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002191 audio_module_handle_t module,
2192 audio_devices_t *pDevices,
2193 uint32_t *pSamplingRate,
2194 audio_format_t *pFormat,
2195 audio_channel_mask_t *pChannelMask,
2196 uint32_t *pLatencyMs,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002197 audio_output_flags_t flags,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002198 const audio_offload_info_t *offloadInfo);
2199audio_io_handle_t aps_open_dup_output(void *service __unused,
Dima Zavinfce7a472011-04-19 22:30:36 -07002200 audio_io_handle_t output1,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002201 audio_io_handle_t output2);
2202int aps_close_output(void *service __unused, audio_io_handle_t output);
2203int aps_suspend_output(void *service __unused, audio_io_handle_t output);
2204int aps_restore_output(void *service __unused, audio_io_handle_t output);
2205audio_io_handle_t aps_open_input(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002206 audio_devices_t *pDevices,
2207 uint32_t *pSamplingRate,
2208 audio_format_t *pFormat,
2209 audio_channel_mask_t *pChannelMask,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002210 audio_in_acoustics_t acoustics __unused);
2211audio_io_handle_t aps_open_input_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002212 audio_module_handle_t module,
2213 audio_devices_t *pDevices,
2214 uint32_t *pSamplingRate,
2215 audio_format_t *pFormat,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002216 audio_channel_mask_t *pChannelMask);
2217int aps_close_input(void *service __unused, audio_io_handle_t input);
2218int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
Glenn Kastend848eb42016-03-08 13:42:11 -08002219int aps_move_effects(void *service __unused, audio_session_t session,
Dima Zavinfce7a472011-04-19 22:30:36 -07002220 audio_io_handle_t src_output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002221 audio_io_handle_t dst_output);
2222char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
2223 const char *keys);
2224void aps_set_parameters(void *service, audio_io_handle_t io_handle,
2225 const char *kv_pairs, int delay_ms);
2226int aps_set_stream_volume(void *service, audio_stream_type_t stream,
Dima Zavinfce7a472011-04-19 22:30:36 -07002227 float volume, audio_io_handle_t output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08002228 int delay_ms);
Eric Laurent2d388ec2014-03-07 13:25:54 -08002229int aps_set_voice_volume(void *service, float volume, int delay_ms);
2230};
Dima Zavinfce7a472011-04-19 22:30:36 -07002231
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08002232} // namespace android