blob: 8c052100a31be7705804bf1e7cc25ce0712243fb [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>
Mikhail Naganov959e2d02019-03-28 11:08:19 -070026
27#include <audio_utils/clock.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
30#include <cutils/properties.h>
31#include <binder/IPCThreadState.h>
Svet Ganovf4ddfef2018-01-16 07:37:58 -080032#include <binder/PermissionController.h>
33#include <binder/IResultReceiver.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070034#include <utils/String16.h>
35#include <utils/threads.h>
36#include "AudioPolicyService.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <hardware_legacy/power.h>
Eric Laurent7c7f10b2011-06-17 21:29:58 -070038#include <media/AudioEffect.h>
Chih-Hung Hsiehc84d9d22014-11-14 13:33:34 -080039#include <media/AudioParameter.h>
Andy Hungab7ef302018-05-15 19:35:29 -070040#include <mediautils/ServiceUtilities.h>
Michael Groovercfd28302018-12-11 19:16:46 -080041#include <sensorprivacy/SensorPrivacyManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042
Dima Zavin64760242011-05-11 14:15:23 -070043#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070044#include <system/audio_policy.h>
Mikhail Naganov61a4fac2016-10-13 14:44:18 -070045
Mathias Agopian65ab4712010-07-14 17:59:35 -070046namespace android {
47
Glenn Kasten8dad0e32012-01-09 08:41:22 -080048static const char kDeadlockedString[] = "AudioPolicyService may be deadlocked\n";
49static const char kCmdDeadlockedString[] = "AudioPolicyService command thread may be deadlocked\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070050
Mikhail Naganov959e2d02019-03-28 11:08:19 -070051static const int kDumpLockTimeoutNs = 1 * NANOS_PER_SECOND;
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
Eric Laurent0ede8922014-05-09 18:04:42 -070053static const nsecs_t kAudioCommandTimeoutNs = seconds(3); // 3 seconds
Christer Fletcher5fa8c4b2013-01-18 15:27:03 +010054
Svet Ganovf4ddfef2018-01-16 07:37:58 -080055static const String16 sManageAudioPolicyPermission("android.permission.MANAGE_AUDIO_POLICY");
Dima Zavinfce7a472011-04-19 22:30:36 -070056
Mathias Agopian65ab4712010-07-14 17:59:35 -070057// ----------------------------------------------------------------------------
58
59AudioPolicyService::AudioPolicyService()
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -070060 : BnAudioPolicyService(),
Ytai Ben-Tsvi85093d52020-03-26 09:41:15 -070061 mAudioPolicyManager(NULL),
62 mAudioPolicyClient(NULL),
63 mPhoneState(AUDIO_MODE_INVALID),
64 mCaptureStateNotifier(false) {
Eric Laurentf5ada6e2014-10-09 17:49:00 -070065}
66
67void AudioPolicyService::onFirstRef()
68{
Eric Laurent8b1e80b2014-10-07 09:08:47 -070069 {
70 Mutex::Autolock _l(mLock);
Eric Laurent93575202011-01-18 18:39:02 -080071
Eric Laurent8b1e80b2014-10-07 09:08:47 -070072 // start audio commands thread
73 mAudioCommandThread = new AudioCommandThread(String8("ApmAudio"), this);
74 // start output activity command thread
75 mOutputCommandThread = new AudioCommandThread(String8("ApmOutput"), this);
Eric Laurentdce54a12014-03-10 12:19:46 -070076
Eric Laurent8b1e80b2014-10-07 09:08:47 -070077 mAudioPolicyClient = new AudioPolicyClient(this);
78 mAudioPolicyManager = createAudioPolicyManager(mAudioPolicyClient);
Eric Laurent8b1e80b2014-10-07 09:08:47 -070079 }
bryant_liuba2b4392014-06-11 16:49:30 +080080 // load audio processing modules
Mikhail Naganov12b716c2020-04-30 22:37:43 +000081 sp<AudioPolicyEffects> audioPolicyEffects = new AudioPolicyEffects();
82 sp<UidPolicy> uidPolicy = new UidPolicy(this);
83 sp<SensorPrivacyPolicy> sensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Eric Laurent8b1e80b2014-10-07 09:08:47 -070084 {
85 Mutex::Autolock _l(mLock);
86 mAudioPolicyEffects = audioPolicyEffects;
Mikhail Naganov12b716c2020-04-30 22:37:43 +000087 mUidPolicy = uidPolicy;
88 mSensorPrivacyPolicy = sensorPrivacyPolicy;
Eric Laurent8b1e80b2014-10-07 09:08:47 -070089 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +000090 uidPolicy->registerSelf();
91 sensorPrivacyPolicy->registerSelf();
Mathias Agopian65ab4712010-07-14 17:59:35 -070092}
93
94AudioPolicyService::~AudioPolicyService()
95{
Mathias Agopian65ab4712010-07-14 17:59:35 -070096 mAudioCommandThread->exit();
Eric Laurent657ff612014-05-07 11:58:24 -070097 mOutputCommandThread->exit();
Eric Laurent7c7f10b2011-06-17 21:29:58 -070098
Eric Laurentf269b8e2014-06-09 20:01:29 -070099 destroyAudioPolicyManager(mAudioPolicyManager);
Eric Laurentdce54a12014-03-10 12:19:46 -0700100 delete mAudioPolicyClient;
Eric Laurentb52c1522014-05-20 11:27:36 -0700101
102 mNotificationClients.clear();
bryant_liuba2b4392014-06-11 16:49:30 +0800103 mAudioPolicyEffects.clear();
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800104
105 mUidPolicy->unregisterSelf();
Michael Groovercfd28302018-12-11 19:16:46 -0800106 mSensorPrivacyPolicy->unregisterSelf();
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000107
108 mUidPolicy.clear();
Michael Groovercfd28302018-12-11 19:16:46 -0800109 mSensorPrivacyPolicy.clear();
Eric Laurentb52c1522014-05-20 11:27:36 -0700110}
111
112// A notification client is always registered by AudioSystem when the client process
113// connects to AudioPolicyService.
114void AudioPolicyService::registerClient(const sp<IAudioPolicyServiceClient>& client)
115{
Eric Laurent12590252015-08-21 18:40:20 -0700116 if (client == 0) {
117 ALOGW("%s got NULL client", __FUNCTION__);
118 return;
119 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800120 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700121
122 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800123 pid_t pid = IPCThreadState::self()->getCallingPid();
124 int64_t token = ((int64_t)uid<<32) | pid;
125
126 if (mNotificationClients.indexOfKey(token) < 0) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700127 sp<NotificationClient> notificationClient = new NotificationClient(this,
128 client,
luochaojiang908c7d72018-06-21 14:58:04 +0800129 uid,
130 pid);
131 ALOGV("registerClient() client %p, uid %d pid %d", client.get(), uid, pid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700132
luochaojiang908c7d72018-06-21 14:58:04 +0800133 mNotificationClients.add(token, notificationClient);
Eric Laurentb52c1522014-05-20 11:27:36 -0700134
Marco Nelissenf8880202014-11-14 07:58:25 -0800135 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurentb52c1522014-05-20 11:27:36 -0700136 binder->linkToDeath(notificationClient);
137 }
138}
139
Eric Laurente8726fe2015-06-26 09:39:24 -0700140void AudioPolicyService::setAudioPortCallbacksEnabled(bool enabled)
141{
142 Mutex::Autolock _l(mNotificationClientsLock);
143
144 uid_t uid = IPCThreadState::self()->getCallingUid();
luochaojiang908c7d72018-06-21 14:58:04 +0800145 pid_t pid = IPCThreadState::self()->getCallingPid();
146 int64_t token = ((int64_t)uid<<32) | pid;
147
148 if (mNotificationClients.indexOfKey(token) < 0) {
Eric Laurente8726fe2015-06-26 09:39:24 -0700149 return;
150 }
luochaojiang908c7d72018-06-21 14:58:04 +0800151 mNotificationClients.valueFor(token)->setAudioPortCallbacksEnabled(enabled);
Eric Laurente8726fe2015-06-26 09:39:24 -0700152}
153
François Gaffiecfe17322018-11-07 13:41:29 +0100154void AudioPolicyService::setAudioVolumeGroupCallbacksEnabled(bool enabled)
155{
156 Mutex::Autolock _l(mNotificationClientsLock);
157
158 uid_t uid = IPCThreadState::self()->getCallingUid();
159 pid_t pid = IPCThreadState::self()->getCallingPid();
160 int64_t token = ((int64_t)uid<<32) | pid;
161
162 if (mNotificationClients.indexOfKey(token) < 0) {
163 return;
164 }
165 mNotificationClients.valueFor(token)->setAudioVolumeGroupCallbacksEnabled(enabled);
166}
167
Eric Laurentb52c1522014-05-20 11:27:36 -0700168// removeNotificationClient() is called when the client process dies.
luochaojiang908c7d72018-06-21 14:58:04 +0800169void AudioPolicyService::removeNotificationClient(uid_t uid, pid_t pid)
Eric Laurentb52c1522014-05-20 11:27:36 -0700170{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000171 bool hasSameUid = false;
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800172 {
173 Mutex::Autolock _l(mNotificationClientsLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800174 int64_t token = ((int64_t)uid<<32) | pid;
175 mNotificationClients.removeItem(token);
luochaojiang908c7d72018-06-21 14:58:04 +0800176 for (size_t i = 0; i < mNotificationClients.size(); i++) {
177 if (mNotificationClients.valueAt(i)->uid() == uid) {
178 hasSameUid = true;
179 break;
180 }
181 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000182 }
183 {
184 Mutex::Autolock _l(mLock);
luochaojiang908c7d72018-06-21 14:58:04 +0800185 if (mAudioPolicyManager && !hasSameUid) {
Eric Laurent10b71232018-04-13 18:14:44 -0700186 // called from binder death notification: no need to clear caller identity
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700187 mAudioPolicyManager->releaseResourcesForUid(uid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700188 }
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800189 }
Eric Laurentb52c1522014-05-20 11:27:36 -0700190}
191
192void AudioPolicyService::onAudioPortListUpdate()
193{
194 mOutputCommandThread->updateAudioPortListCommand();
195}
196
197void AudioPolicyService::doOnAudioPortListUpdate()
198{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800199 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700200 for (size_t i = 0; i < mNotificationClients.size(); i++) {
201 mNotificationClients.valueAt(i)->onAudioPortListUpdate();
202 }
203}
204
205void AudioPolicyService::onAudioPatchListUpdate()
206{
207 mOutputCommandThread->updateAudioPatchListCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700208}
209
Eric Laurentb52c1522014-05-20 11:27:36 -0700210void AudioPolicyService::doOnAudioPatchListUpdate()
211{
Eric Laurent0ebd5f92014-11-19 19:04:52 -0800212 Mutex::Autolock _l(mNotificationClientsLock);
Eric Laurentb52c1522014-05-20 11:27:36 -0700213 for (size_t i = 0; i < mNotificationClients.size(); i++) {
214 mNotificationClients.valueAt(i)->onAudioPatchListUpdate();
215 }
216}
217
François Gaffiecfe17322018-11-07 13:41:29 +0100218void AudioPolicyService::onAudioVolumeGroupChanged(volume_group_t group, int flags)
219{
220 mOutputCommandThread->changeAudioVolumeGroupCommand(group, flags);
221}
222
223void AudioPolicyService::doOnAudioVolumeGroupChanged(volume_group_t group, int flags)
224{
225 Mutex::Autolock _l(mNotificationClientsLock);
226 for (size_t i = 0; i < mNotificationClients.size(); i++) {
227 mNotificationClients.valueAt(i)->onAudioVolumeGroupChanged(group, flags);
228 }
229}
230
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700231void AudioPolicyService::onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700232{
233 ALOGV("AudioPolicyService::onDynamicPolicyMixStateUpdate(%s, %d)",
234 regId.string(), state);
235 mOutputCommandThread->dynamicPolicyMixStateUpdateCommand(regId, state);
236}
237
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700238void AudioPolicyService::doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700239{
240 Mutex::Autolock _l(mNotificationClientsLock);
241 for (size_t i = 0; i < mNotificationClients.size(); i++) {
242 mNotificationClients.valueAt(i)->onDynamicPolicyMixStateUpdate(regId, state);
243 }
244}
245
Eric Laurenta9f86652018-11-28 17:23:11 -0800246void AudioPolicyService::onRecordingConfigurationUpdate(
247 int event,
248 const record_client_info_t *clientInfo,
249 const audio_config_base_t *clientConfig,
250 std::vector<effect_descriptor_t> clientEffects,
251 const audio_config_base_t *deviceConfig,
252 std::vector<effect_descriptor_t> effects,
253 audio_patch_handle_t patchHandle,
254 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800255{
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800256 mOutputCommandThread->recordingConfigurationUpdateCommand(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800257 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800258}
259
Eric Laurenta9f86652018-11-28 17:23:11 -0800260void AudioPolicyService::doOnRecordingConfigurationUpdate(
261 int event,
262 const record_client_info_t *clientInfo,
263 const audio_config_base_t *clientConfig,
264 std::vector<effect_descriptor_t> clientEffects,
265 const audio_config_base_t *deviceConfig,
266 std::vector<effect_descriptor_t> effects,
267 audio_patch_handle_t patchHandle,
268 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800269{
270 Mutex::Autolock _l(mNotificationClientsLock);
271 for (size_t i = 0; i < mNotificationClients.size(); i++) {
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800272 mNotificationClients.valueAt(i)->onRecordingConfigurationUpdate(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800273 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800274 }
275}
276
277status_t AudioPolicyService::clientCreateAudioPatch(const struct audio_patch *patch,
278 audio_patch_handle_t *handle,
279 int delayMs)
280{
281 return mAudioCommandThread->createAudioPatchCommand(patch, handle, delayMs);
282}
283
284status_t AudioPolicyService::clientReleaseAudioPatch(audio_patch_handle_t handle,
285 int delayMs)
286{
287 return mAudioCommandThread->releaseAudioPatchCommand(handle, delayMs);
288}
289
Eric Laurente1715a42014-05-20 11:30:42 -0700290status_t AudioPolicyService::clientSetAudioPortConfig(const struct audio_port_config *config,
291 int delayMs)
292{
293 return mAudioCommandThread->setAudioPortConfigCommand(config, delayMs);
294}
295
Eric Laurentb52c1522014-05-20 11:27:36 -0700296AudioPolicyService::NotificationClient::NotificationClient(const sp<AudioPolicyService>& service,
297 const sp<IAudioPolicyServiceClient>& client,
luochaojiang908c7d72018-06-21 14:58:04 +0800298 uid_t uid,
299 pid_t pid)
300 : mService(service), mUid(uid), mPid(pid), mAudioPolicyServiceClient(client),
François Gaffiecfe17322018-11-07 13:41:29 +0100301 mAudioPortCallbacksEnabled(false), mAudioVolumeGroupCallbacksEnabled(false)
Eric Laurentb52c1522014-05-20 11:27:36 -0700302{
303}
304
305AudioPolicyService::NotificationClient::~NotificationClient()
306{
307}
308
309void AudioPolicyService::NotificationClient::binderDied(const wp<IBinder>& who __unused)
310{
311 sp<NotificationClient> keep(this);
312 sp<AudioPolicyService> service = mService.promote();
313 if (service != 0) {
luochaojiang908c7d72018-06-21 14:58:04 +0800314 service->removeNotificationClient(mUid, mPid);
Eric Laurentb52c1522014-05-20 11:27:36 -0700315 }
316}
317
318void AudioPolicyService::NotificationClient::onAudioPortListUpdate()
319{
Eric Laurente8726fe2015-06-26 09:39:24 -0700320 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700321 mAudioPolicyServiceClient->onAudioPortListUpdate();
322 }
323}
324
325void AudioPolicyService::NotificationClient::onAudioPatchListUpdate()
326{
Eric Laurente8726fe2015-06-26 09:39:24 -0700327 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
Eric Laurentb52c1522014-05-20 11:27:36 -0700328 mAudioPolicyServiceClient->onAudioPatchListUpdate();
329 }
330}
Eric Laurent57dae992011-07-24 13:36:09 -0700331
François Gaffiecfe17322018-11-07 13:41:29 +0100332void AudioPolicyService::NotificationClient::onAudioVolumeGroupChanged(volume_group_t group,
333 int flags)
334{
335 if (mAudioPolicyServiceClient != 0 && mAudioVolumeGroupCallbacksEnabled) {
336 mAudioPolicyServiceClient->onAudioVolumeGroupChanged(group, flags);
337 }
338}
339
340
Jean-Michel Trivide801052015-04-14 19:10:14 -0700341void AudioPolicyService::NotificationClient::onDynamicPolicyMixStateUpdate(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -0700342 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -0700343{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700344 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800345 mAudioPolicyServiceClient->onDynamicPolicyMixStateUpdate(regId, state);
346 }
347}
348
349void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate(
Eric Laurenta9f86652018-11-28 17:23:11 -0800350 int event,
351 const record_client_info_t *clientInfo,
352 const audio_config_base_t *clientConfig,
353 std::vector<effect_descriptor_t> clientEffects,
354 const audio_config_base_t *deviceConfig,
355 std::vector<effect_descriptor_t> effects,
356 audio_patch_handle_t patchHandle,
357 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -0800358{
Andy Hung4ef19fa2018-05-15 19:35:29 -0700359 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
Jean-Michel Triviac4e4292016-12-22 11:39:31 -0800360 mAudioPolicyServiceClient->onRecordingConfigurationUpdate(event, clientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -0800361 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
Jean-Michel Trivide801052015-04-14 19:10:14 -0700362 }
363}
364
Eric Laurente8726fe2015-06-26 09:39:24 -0700365void AudioPolicyService::NotificationClient::setAudioPortCallbacksEnabled(bool enabled)
366{
367 mAudioPortCallbacksEnabled = enabled;
368}
369
François Gaffiecfe17322018-11-07 13:41:29 +0100370void AudioPolicyService::NotificationClient::setAudioVolumeGroupCallbacksEnabled(bool enabled)
371{
372 mAudioVolumeGroupCallbacksEnabled = enabled;
373}
Eric Laurente8726fe2015-06-26 09:39:24 -0700374
Mathias Agopian65ab4712010-07-14 17:59:35 -0700375void AudioPolicyService::binderDied(const wp<IBinder>& who) {
Glenn Kasten411e4472012-11-02 10:00:06 -0700376 ALOGW("binderDied() %p, calling pid %d", who.unsafe_get(),
Eric Laurentde070132010-07-13 04:45:46 -0700377 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700378}
379
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000380static bool dumpTryLock(Mutex& mutex) ACQUIRE(mutex) NO_THREAD_SAFETY_ANALYSIS
Mathias Agopian65ab4712010-07-14 17:59:35 -0700381{
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000382 return mutex.timedLock(kDumpLockTimeoutNs) == NO_ERROR;
383}
384
385static void dumpReleaseLock(Mutex& mutex, bool locked) RELEASE(mutex) NO_THREAD_SAFETY_ANALYSIS
386{
387 if (locked) mutex.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700388}
389
390status_t AudioPolicyService::dumpInternals(int fd)
391{
392 const size_t SIZE = 256;
393 char buffer[SIZE];
394 String8 result;
395
Eric Laurentdce54a12014-03-10 12:19:46 -0700396 snprintf(buffer, SIZE, "AudioPolicyManager: %p\n", mAudioPolicyManager);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700397 result.append(buffer);
398 snprintf(buffer, SIZE, "Command Thread: %p\n", mAudioCommandThread.get());
399 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700400
Hayden Gomes524159d2019-12-23 14:41:47 -0800401 snprintf(buffer, SIZE, "Supported System Usages:\n");
402 result.append(buffer);
403 for (std::vector<audio_usage_t>::iterator it = mSupportedSystemUsages.begin();
404 it != mSupportedSystemUsages.end(); ++it) {
405 snprintf(buffer, SIZE, "\t%d\n", *it);
406 result.append(buffer);
407 }
408
Mathias Agopian65ab4712010-07-14 17:59:35 -0700409 write(fd, result.string(), result.size());
410 return NO_ERROR;
411}
412
Eric Laurente8c8b432018-10-17 10:08:02 -0700413void AudioPolicyService::updateUidStates()
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800414{
Eric Laurente8c8b432018-10-17 10:08:02 -0700415 Mutex::Autolock _l(mLock);
416 updateUidStates_l();
417}
418
419void AudioPolicyService::updateUidStates_l()
420{
Eric Laurent4eb58f12018-12-07 16:41:02 -0800421// Go over all active clients and allow capture (does not force silence) in the
422// following cases:
Eric Laurent8ed73c12019-08-30 17:25:19 -0700423// The client is the assistant
Eric Laurent6ede98f2019-06-11 14:50:30 -0700424// AND an accessibility service is on TOP or a RTT call is active
Eric Laurent589171c2019-07-25 18:04:29 -0700425// AND the source is VOICE_RECOGNITION or HOTWORD
426// OR uses VOICE_RECOGNITION AND is on TOP
427// OR uses HOTWORD
Eric Laurent1ff16a72019-03-14 18:35:04 -0700428// AND there is no active privacy sensitive capture or call
429// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurenta46bedb2018-12-07 18:01:26 -0800430// OR The client is an accessibility service
Eric Laurent589171c2019-07-25 18:04:29 -0700431// AND Is on TOP
432// AND the source is VOICE_RECOGNITION or HOTWORD
433// OR The assistant is not on TOP
434// AND there is no active privacy sensitive capture or call
435// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurenta171e352019-05-07 13:04:45 -0700436// AND is on TOP
Eric Laurenta46bedb2018-12-07 18:01:26 -0800437// AND the source is VOICE_RECOGNITION or HOTWORD
Eric Laurent1ff16a72019-03-14 18:35:04 -0700438// OR the client source is virtual (remote submix, call audio TX or RX...)
Eric Laurent4e947da2019-10-17 15:24:06 -0700439// OR the client source is HOTWORD
440// AND is on TOP
441// OR all active clients are using HOTWORD source
442// AND no call is active
443// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Kohsuke Yatoha623a132020-03-24 20:10:26 -0700444// OR the client is the current InputMethodService
445// AND a RTT call is active AND the source is VOICE_RECOGNITION
Eric Laurenta171e352019-05-07 13:04:45 -0700446// OR Any client
Eric Laurenta46bedb2018-12-07 18:01:26 -0800447// AND The assistant is not on TOP
Eric Laurenta171e352019-05-07 13:04:45 -0700448// AND is on TOP or latest started
Eric Laurent1ff16a72019-03-14 18:35:04 -0700449// AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -0700450// OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent4eb58f12018-12-07 16:41:02 -0800451
Eric Laurent4e947da2019-10-17 15:24:06 -0700452
Eric Laurent4eb58f12018-12-07 16:41:02 -0800453 sp<AudioRecordClient> topActive;
454 sp<AudioRecordClient> latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800455 sp<AudioRecordClient> topSensitiveActive;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800456 sp<AudioRecordClient> latestSensitiveActive;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700457
Eric Laurenta46bedb2018-12-07 18:01:26 -0800458 nsecs_t topStartNs = 0;
459 nsecs_t latestStartNs = 0;
Eric Laurentc21d5692020-02-25 10:24:36 -0800460 nsecs_t topSensitiveStartNs = 0;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800461 nsecs_t latestSensitiveStartNs = 0;
462 bool isA11yOnTop = mUidPolicy->isA11yOnTop();
463 bool isAssistantOnTop = false;
464 bool isSensitiveActive = false;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700465 bool isInCall = mPhoneState == AUDIO_MODE_IN_CALL;
Eric Laurentc21d5692020-02-25 10:24:36 -0800466 bool isInCommunication = mPhoneState == AUDIO_MODE_IN_COMMUNICATION;
467 bool rttCallActive = (isInCall || isInCommunication)
Eric Laurent6ede98f2019-06-11 14:50:30 -0700468 && mUidPolicy->isRttEnabled();
Eric Laurent4e947da2019-10-17 15:24:06 -0700469 bool onlyHotwordActive = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800470
Michael Groovercfd28302018-12-11 19:16:46 -0800471 // if Sensor Privacy is enabled then all recordings should be silenced.
472 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
473 silenceAllRecordings_l();
474 return;
475 }
476
Eric Laurente8c8b432018-10-17 10:08:02 -0700477 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
478 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -0700479 if (!current->active) {
480 continue;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800481 }
Eric Laurent1ff16a72019-03-14 18:35:04 -0700482
483 app_state_t appState = apmStatFromAmState(mUidPolicy->getUidState(current->uid));
484 // clients which app is in IDLE state are not eligible for top active or
485 // latest active
486 if (appState == APP_STATE_IDLE) {
487 continue;
488 }
489
Eric Laurent589171c2019-07-25 18:04:29 -0700490 bool isAccessibility = mUidPolicy->isA11yUid(current->uid);
Eric Laurentc21d5692020-02-25 10:24:36 -0800491 // Clients capturing for Accessibility services are not considered
492 // for top or latest active to avoid masking regular clients started before
493 if (!isAccessibility) {
494 bool isAssistant = mUidPolicy->isAssistantUid(current->uid);
495 bool isPrivacySensitive =
496 (current->attributes.flags & AUDIO_FLAG_CAPTURE_PRIVATE) != 0;
497 if (appState == APP_STATE_TOP) {
498 if (isPrivacySensitive) {
499 if (current->startTimeNs > topSensitiveStartNs) {
500 topSensitiveActive = current;
501 topSensitiveStartNs = current->startTimeNs;
502 }
503 } else {
504 if (current->startTimeNs > topStartNs) {
505 topActive = current;
506 topStartNs = current->startTimeNs;
507 }
508 }
509 if (isAssistant) {
510 isAssistantOnTop = true;
511 }
Eric Laurenta46bedb2018-12-07 18:01:26 -0800512 }
Eric Laurentc21d5692020-02-25 10:24:36 -0800513 // Clients capturing for HOTWORD are not considered
514 // for latest active to avoid masking regular clients started before
515 if (!(current->attributes.source == AUDIO_SOURCE_HOTWORD
516 || ((isA11yOnTop || rttCallActive) && isAssistant))) {
517 if (isPrivacySensitive) {
518 if (current->startTimeNs > latestSensitiveStartNs) {
519 latestSensitiveActive = current;
520 latestSensitiveStartNs = current->startTimeNs;
521 }
522 isSensitiveActive = true;
523 } else {
524 if (current->startTimeNs > latestStartNs) {
525 latestActive = current;
526 latestStartNs = current->startTimeNs;
527 }
528 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800529 }
530 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700531 if (current->attributes.source != AUDIO_SOURCE_HOTWORD) {
532 onlyHotwordActive = false;
533 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800534 }
535
Eric Laurent1ff16a72019-03-14 18:35:04 -0700536 // if no active client with UI on Top, consider latest active as top
537 if (topActive == nullptr) {
538 topActive = latestActive;
Eric Laurentc21d5692020-02-25 10:24:36 -0800539 topStartNs = latestStartNs;
540 }
541 if (topSensitiveActive == nullptr) {
542 topSensitiveActive = latestSensitiveActive;
543 topSensitiveStartNs = latestSensitiveStartNs;
544 }
545
546 // If both privacy sensitive and regular capture are active:
547 // if the regular capture is privileged
548 // allow concurrency
549 // else
550 // favor the privacy sensitive case
551 if (topActive != nullptr && topSensitiveActive != nullptr
Ricardo Correa57a37692020-03-23 17:27:25 -0700552 && !topActive->canCaptureOutput) {
Eric Laurentc21d5692020-02-25 10:24:36 -0800553 topActive = nullptr;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800554 }
555
556 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
557 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -0700558 if (!current->active) {
559 continue;
560 }
561
Eric Laurent4eb58f12018-12-07 16:41:02 -0800562 audio_source_t source = current->attributes.source;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700563 bool isTopOrLatestActive = topActive == nullptr ? false : current->uid == topActive->uid;
Eric Laurentc21d5692020-02-25 10:24:36 -0800564 bool isTopOrLatestSensitive = topSensitiveActive == nullptr ?
565 false : current->uid == topSensitiveActive->uid;
566
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000567 auto canCaptureIfInCallOrCommunication = [&](const auto &recordClient) REQUIRES(mLock) {
Ricardo Correa57a37692020-03-23 17:27:25 -0700568 bool canCaptureCall = recordClient->canCaptureOutput;
569 bool canCaptureCommunication = recordClient->canCaptureOutput
Eric Laurentc21d5692020-02-25 10:24:36 -0800570 || recordClient->uid == mPhoneStateOwnerUid
571 || isServiceUid(mPhoneStateOwnerUid);
572 return !(isInCall && !canCaptureCall)
573 && !(isInCommunication && !canCaptureCommunication);
574 };
Eric Laurent1ff16a72019-03-14 18:35:04 -0700575
576 // By default allow capture if:
577 // The assistant is not on TOP
Eric Laurenta171e352019-05-07 13:04:45 -0700578 // AND is on TOP or latest started
Eric Laurent1ff16a72019-03-14 18:35:04 -0700579 // AND there is no active privacy sensitive capture or call
580 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
581 bool allowCapture = !isAssistantOnTop
Eric Laurentc21d5692020-02-25 10:24:36 -0800582 && (isTopOrLatestActive || isTopOrLatestSensitive)
583 && !(isSensitiveActive
Ricardo Correa57a37692020-03-23 17:27:25 -0700584 && !(isTopOrLatestSensitive || current->canCaptureOutput))
Eric Laurentc21d5692020-02-25 10:24:36 -0800585 && canCaptureIfInCallOrCommunication(current);
Eric Laurent2dc962b2019-03-01 08:25:25 -0800586
587 if (isVirtualSource(source)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700588 // Allow capture for virtual (remote submix, call audio TX or RX...) sources
589 allowCapture = true;
Eric Laurent2dc962b2019-03-01 08:25:25 -0800590 } else if (mUidPolicy->isAssistantUid(current->uid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700591 // For assistant allow capture if:
Eric Laurent6ede98f2019-06-11 14:50:30 -0700592 // An accessibility service is on TOP or a RTT call is active
Eric Laurent1ff16a72019-03-14 18:35:04 -0700593 // AND the source is VOICE_RECOGNITION or HOTWORD
Eric Laurenta171e352019-05-07 13:04:45 -0700594 // OR is on TOP AND uses VOICE_RECOGNITION
Eric Laurent1ff16a72019-03-14 18:35:04 -0700595 // OR uses HOTWORD
596 // AND there is no active privacy sensitive capture or call
597 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent6ede98f2019-06-11 14:50:30 -0700598 if (isA11yOnTop || rttCallActive) {
Eric Laurent4eb58f12018-12-07 16:41:02 -0800599 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700600 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800601 }
602 } else {
Eric Laurenta171e352019-05-07 13:04:45 -0700603 if (((isAssistantOnTop && source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
Eric Laurentc21d5692020-02-25 10:24:36 -0800604 source == AUDIO_SOURCE_HOTWORD)
Ricardo Correa57a37692020-03-23 17:27:25 -0700605 && !(isSensitiveActive && !current->canCaptureOutput)
Eric Laurentc21d5692020-02-25 10:24:36 -0800606 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700607 allowCapture = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -0800608 }
609 }
610 } else if (mUidPolicy->isA11yUid(current->uid)) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700611 // For accessibility service allow capture if:
Eric Laurent47670c92019-08-28 16:59:05 -0700612 // The assistant is not on TOP
613 // AND there is no active privacy sensitive capture or call
Eric Laurent589171c2019-07-25 18:04:29 -0700614 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurent47670c92019-08-28 16:59:05 -0700615 // OR
616 // Is on TOP AND the source is VOICE_RECOGNITION or HOTWORD
617 if (!isAssistantOnTop
Ricardo Correa57a37692020-03-23 17:27:25 -0700618 && !(isSensitiveActive && !current->canCaptureOutput)
Eric Laurentc21d5692020-02-25 10:24:36 -0800619 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent47670c92019-08-28 16:59:05 -0700620 allowCapture = true;
621 }
Eric Laurent589171c2019-07-25 18:04:29 -0700622 if (isA11yOnTop) {
623 if (source == AUDIO_SOURCE_VOICE_RECOGNITION || source == AUDIO_SOURCE_HOTWORD) {
624 allowCapture = true;
625 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800626 }
Eric Laurent4e947da2019-10-17 15:24:06 -0700627 } else if (source == AUDIO_SOURCE_HOTWORD) {
628 // For HOTWORD source allow capture when not on TOP if:
629 // All active clients are using HOTWORD source
630 // AND no call is active
631 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
Eric Laurentc21d5692020-02-25 10:24:36 -0800632 if (onlyHotwordActive
633 && canCaptureIfInCallOrCommunication(current)) {
Eric Laurent4e947da2019-10-17 15:24:06 -0700634 allowCapture = true;
635 }
Kohsuke Yatoha623a132020-03-24 20:10:26 -0700636 } else if (mUidPolicy->isCurrentImeUid(current->uid)) {
637 // For current InputMethodService allow capture if:
638 // A RTT call is active AND the source is VOICE_RECOGNITION
639 if (rttCallActive && source == AUDIO_SOURCE_VOICE_RECOGNITION) {
640 allowCapture = true;
641 }
Eric Laurent4eb58f12018-12-07 16:41:02 -0800642 }
Eric Laurent5ada82e2019-08-29 17:53:54 -0700643 setAppState_l(current->portId,
Eric Laurent1ff16a72019-03-14 18:35:04 -0700644 allowCapture ? apmStatFromAmState(mUidPolicy->getUidState(current->uid)) :
645 APP_STATE_IDLE);
Eric Laurente8c8b432018-10-17 10:08:02 -0700646 }
647}
648
Michael Groovercfd28302018-12-11 19:16:46 -0800649void AudioPolicyService::silenceAllRecordings_l() {
650 for (size_t i = 0; i < mAudioRecordClients.size(); i++) {
651 sp<AudioRecordClient> current = mAudioRecordClients[i];
Eric Laurent1ff16a72019-03-14 18:35:04 -0700652 if (!isVirtualSource(current->attributes.source)) {
Eric Laurent5ada82e2019-08-29 17:53:54 -0700653 setAppState_l(current->portId, APP_STATE_IDLE);
Eric Laurent1ff16a72019-03-14 18:35:04 -0700654 }
Michael Groovercfd28302018-12-11 19:16:46 -0800655 }
656}
657
Eric Laurente8c8b432018-10-17 10:08:02 -0700658/* static */
659app_state_t AudioPolicyService::apmStatFromAmState(int amState) {
Eric Laurent1ff16a72019-03-14 18:35:04 -0700660
661 if (amState == ActivityManager::PROCESS_STATE_UNKNOWN) {
Eric Laurente8c8b432018-10-17 10:08:02 -0700662 return APP_STATE_IDLE;
Eric Laurent1ff16a72019-03-14 18:35:04 -0700663 } else if (amState <= ActivityManager::PROCESS_STATE_TOP) {
664 // include persistent services
665 return APP_STATE_TOP;
Eric Laurente8c8b432018-10-17 10:08:02 -0700666 }
667 return APP_STATE_FOREGROUND;
668}
669
Eric Laurent4eb58f12018-12-07 16:41:02 -0800670/* static */
Eric Laurent2dc962b2019-03-01 08:25:25 -0800671bool AudioPolicyService::isVirtualSource(audio_source_t source)
Eric Laurent4eb58f12018-12-07 16:41:02 -0800672{
673 switch (source) {
674 case AUDIO_SOURCE_VOICE_UPLINK:
675 case AUDIO_SOURCE_VOICE_DOWNLINK:
676 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent2dc962b2019-03-01 08:25:25 -0800677 case AUDIO_SOURCE_REMOTE_SUBMIX:
678 case AUDIO_SOURCE_FM_TUNER:
Eric Laurent4eb58f12018-12-07 16:41:02 -0800679 return true;
680 default:
681 break;
682 }
683 return false;
684}
685
Eric Laurent5ada82e2019-08-29 17:53:54 -0700686void AudioPolicyService::setAppState_l(audio_port_handle_t portId, app_state_t state)
Eric Laurente8c8b432018-10-17 10:08:02 -0700687{
688 AutoCallerClear acc;
689
690 if (mAudioPolicyManager) {
Eric Laurent5ada82e2019-08-29 17:53:54 -0700691 mAudioPolicyManager->setAppState(portId, state);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700692 }
693 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
694 if (af) {
Eric Laurentf32108e2018-10-04 17:22:04 -0700695 bool silenced = state == APP_STATE_IDLE;
Eric Laurent5ada82e2019-08-29 17:53:54 -0700696 af->setRecordSilenced(portId, silenced);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700697 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800698}
699
Glenn Kasten0f11b512014-01-31 16:18:54 -0800700status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700701{
Glenn Kasten44deb052012-02-05 18:09:08 -0800702 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700703 dumpPermissionDenial(fd);
704 } else {
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000705 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700706 if (!locked) {
707 String8 result(kDeadlockedString);
708 write(fd, result.string(), result.size());
709 }
710
711 dumpInternals(fd);
Glenn Kasten9d1f02d2012-02-08 17:47:58 -0800712 if (mAudioCommandThread != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700713 mAudioCommandThread->dump(fd);
714 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700715
Eric Laurentdce54a12014-03-10 12:19:46 -0700716 if (mAudioPolicyManager) {
717 mAudioPolicyManager->dump(fd);
718 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700719
Kevin Rocard8be94972019-02-22 13:26:25 -0800720 mPackageManager.dump(fd);
721
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000722 dumpReleaseLock(mLock, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700723 }
724 return NO_ERROR;
725}
726
727status_t AudioPolicyService::dumpPermissionDenial(int fd)
728{
729 const size_t SIZE = 256;
730 char buffer[SIZE];
731 String8 result;
732 snprintf(buffer, SIZE, "Permission Denial: "
733 "can't dump AudioPolicyService from pid=%d, uid=%d\n",
734 IPCThreadState::self()->getCallingPid(),
735 IPCThreadState::self()->getCallingUid());
736 result.append(buffer);
737 write(fd, result.string(), result.size());
738 return NO_ERROR;
739}
740
741status_t AudioPolicyService::onTransact(
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800742 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
743 switch (code) {
744 case SHELL_COMMAND_TRANSACTION: {
745 int in = data.readFileDescriptor();
746 int out = data.readFileDescriptor();
747 int err = data.readFileDescriptor();
748 int argc = data.readInt32();
749 Vector<String16> args;
750 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
751 args.add(data.readString16());
752 }
753 sp<IBinder> unusedCallback;
754 sp<IResultReceiver> resultReceiver;
755 status_t status;
756 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
757 return status;
758 }
759 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
760 return status;
761 }
762 status = shellCommand(in, out, err, args);
763 if (resultReceiver != nullptr) {
764 resultReceiver->send(status);
765 }
766 return NO_ERROR;
767 }
768 }
769
Mathias Agopian65ab4712010-07-14 17:59:35 -0700770 return BnAudioPolicyService::onTransact(code, data, reply, flags);
771}
772
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800773// ------------------- Shell command implementation -------------------
774
775// NOTE: This is a remote API - make sure all args are validated
776status_t AudioPolicyService::shellCommand(int in, int out, int err, Vector<String16>& args) {
777 if (!checkCallingPermission(sManageAudioPolicyPermission, nullptr, nullptr)) {
778 return PERMISSION_DENIED;
779 }
780 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
781 return BAD_VALUE;
782 }
jovanakbe066e12019-09-02 11:54:39 -0700783 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800784 return handleSetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -0700785 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800786 return handleResetUidState(args, err);
jovanakbe066e12019-09-02 11:54:39 -0700787 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800788 return handleGetUidState(args, out, err);
789 } else if (args.size() == 1 && args[0] == String16("help")) {
790 printHelp(out);
791 return NO_ERROR;
792 }
793 printHelp(err);
794 return BAD_VALUE;
795}
796
jovanakbe066e12019-09-02 11:54:39 -0700797static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
798 if (userId < 0) {
799 ALOGE("Invalid user: %d", userId);
800 dprintf(err, "Invalid user: %d\n", userId);
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800801 return BAD_VALUE;
802 }
jovanakbe066e12019-09-02 11:54:39 -0700803
804 PermissionController pc;
805 uid = pc.getPackageUid(packageName, 0);
806 if (uid <= 0) {
807 ALOGE("Unknown package: '%s'", String8(packageName).string());
808 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
809 return BAD_VALUE;
810 }
811
812 uid = multiuser_get_uid(userId, uid);
813 return NO_ERROR;
814}
815
816status_t AudioPolicyService::handleSetUidState(Vector<String16>& args, int err) {
817 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
818 if (!(args.size() == 3 || args.size() == 5)) {
819 printHelp(err);
820 return BAD_VALUE;
821 }
822
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800823 bool active = false;
824 if (args[2] == String16("active")) {
825 active = true;
826 } else if ((args[2] != String16("idle"))) {
827 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
828 return BAD_VALUE;
829 }
jovanakbe066e12019-09-02 11:54:39 -0700830
831 int userId = 0;
832 if (args.size() >= 5 && args[3] == String16("--user")) {
833 userId = atoi(String8(args[4]));
834 }
835
836 uid_t uid;
837 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
838 return BAD_VALUE;
839 }
840
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000841 sp<UidPolicy> uidPolicy;
842 {
843 Mutex::Autolock _l(mLock);
844 uidPolicy = mUidPolicy;
845 }
846 if (uidPolicy) {
847 uidPolicy->addOverrideUid(uid, active);
848 return NO_ERROR;
849 }
850 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800851}
852
853status_t AudioPolicyService::handleResetUidState(Vector<String16>& args, int err) {
jovanakbe066e12019-09-02 11:54:39 -0700854 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
855 if (!(args.size() == 2 || args.size() == 4)) {
856 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800857 return BAD_VALUE;
858 }
jovanakbe066e12019-09-02 11:54:39 -0700859
860 int userId = 0;
861 if (args.size() >= 4 && args[2] == String16("--user")) {
862 userId = atoi(String8(args[3]));
863 }
864
865 uid_t uid;
866 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
867 return BAD_VALUE;
868 }
869
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000870 sp<UidPolicy> uidPolicy;
871 {
872 Mutex::Autolock _l(mLock);
873 uidPolicy = mUidPolicy;
874 }
875 if (uidPolicy) {
876 uidPolicy->removeOverrideUid(uid);
877 return NO_ERROR;
878 }
879 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800880}
881
882status_t AudioPolicyService::handleGetUidState(Vector<String16>& args, int out, int err) {
jovanakbe066e12019-09-02 11:54:39 -0700883 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
884 if (!(args.size() == 2 || args.size() == 4)) {
885 printHelp(err);
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800886 return BAD_VALUE;
887 }
jovanakbe066e12019-09-02 11:54:39 -0700888
889 int userId = 0;
890 if (args.size() >= 4 && args[2] == String16("--user")) {
891 userId = atoi(String8(args[3]));
892 }
893
894 uid_t uid;
895 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
896 return BAD_VALUE;
897 }
898
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000899 sp<UidPolicy> uidPolicy;
900 {
901 Mutex::Autolock _l(mLock);
902 uidPolicy = mUidPolicy;
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800903 }
Mikhail Naganov12b716c2020-04-30 22:37:43 +0000904 if (uidPolicy) {
905 return dprintf(out, uidPolicy->isUidActive(uid) ? "active\n" : "idle\n");
906 }
907 return NO_INIT;
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800908}
909
910status_t AudioPolicyService::printHelp(int out) {
911 return dprintf(out, "Audio policy service commands:\n"
jovanakbe066e12019-09-02 11:54:39 -0700912 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
913 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
914 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800915 " help print this message\n");
916}
917
918// ----------- AudioPolicyService::UidPolicy implementation ----------
919
920void AudioPolicyService::UidPolicy::registerSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -0700921 status_t res = mAm.linkToDeath(this);
922 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800923 | ActivityManager::UID_OBSERVER_IDLE
Eric Laurente8c8b432018-10-17 10:08:02 -0700924 | ActivityManager::UID_OBSERVER_ACTIVE
925 | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800926 ActivityManager::PROCESS_STATE_UNKNOWN,
927 String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700928 if (!res) {
929 Mutex::Autolock _l(mLock);
930 mObserverRegistered = true;
931 } else {
932 ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
Eric Laurent4eb58f12018-12-07 16:41:02 -0800933
Steven Moreland2f348142019-07-02 15:59:07 -0700934 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700935 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800936}
937
938void AudioPolicyService::UidPolicy::unregisterSelf() {
Steven Moreland2f348142019-07-02 15:59:07 -0700939 mAm.unlinkToDeath(this);
940 mAm.unregisterUidObserver(this);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700941 Mutex::Autolock _l(mLock);
942 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800943}
944
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700945void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
946 Mutex::Autolock _l(mLock);
947 mCachedUids.clear();
948 mObserverRegistered = false;
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800949}
950
Eric Laurente8c8b432018-10-17 10:08:02 -0700951void AudioPolicyService::UidPolicy::checkRegistered() {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700952 bool needToReregister = false;
953 {
954 Mutex::Autolock _l(mLock);
955 needToReregister = !mObserverRegistered;
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800956 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700957 if (needToReregister) {
958 // Looks like ActivityManager has died previously, attempt to re-register.
959 registerSelf();
960 }
Eric Laurente8c8b432018-10-17 10:08:02 -0700961}
962
963bool AudioPolicyService::UidPolicy::isUidActive(uid_t uid) {
964 if (isServiceUid(uid)) return true;
965 checkRegistered();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700966 {
967 Mutex::Autolock _l(mLock);
968 auto overrideIter = mOverrideUids.find(uid);
969 if (overrideIter != mOverrideUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -0700970 return overrideIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700971 }
972 // In an absense of the ActivityManager, assume everything to be active.
973 if (!mObserverRegistered) return true;
974 auto cacheIter = mCachedUids.find(uid);
Mikhail Naganoveba668a2018-04-05 08:13:15 -0700975 if (cacheIter != mCachedUids.end()) {
Eric Laurente8c8b432018-10-17 10:08:02 -0700976 return cacheIter->second.first;
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700977 }
978 }
979 ActivityManager am;
Hui Yuffffffc2020-03-24 16:13:59 -0700980 bool active = am.isUidActiveOrForeground(uid, String16("audioserver"));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700981 {
982 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -0700983 mCachedUids.insert(std::pair<uid_t,
984 std::pair<bool, int>>(uid, std::pair<bool, int>(active,
985 ActivityManager::PROCESS_STATE_UNKNOWN)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -0700986 }
987 return active;
Svet Ganovf4ddfef2018-01-16 07:37:58 -0800988}
989
Eric Laurente8c8b432018-10-17 10:08:02 -0700990int AudioPolicyService::UidPolicy::getUidState(uid_t uid) {
991 if (isServiceUid(uid)) {
992 return ActivityManager::PROCESS_STATE_TOP;
993 }
994 checkRegistered();
995 {
996 Mutex::Autolock _l(mLock);
997 auto overrideIter = mOverrideUids.find(uid);
998 if (overrideIter != mOverrideUids.end()) {
999 if (overrideIter->second.first) {
1000 if (overrideIter->second.second != ActivityManager::PROCESS_STATE_UNKNOWN) {
1001 return overrideIter->second.second;
1002 } else {
1003 auto cacheIter = mCachedUids.find(uid);
1004 if (cacheIter != mCachedUids.end()) {
1005 return cacheIter->second.second;
1006 }
1007 }
1008 }
1009 return ActivityManager::PROCESS_STATE_UNKNOWN;
1010 }
1011 // In an absense of the ActivityManager, assume everything to be active.
1012 if (!mObserverRegistered) {
1013 return ActivityManager::PROCESS_STATE_TOP;
1014 }
1015 auto cacheIter = mCachedUids.find(uid);
1016 if (cacheIter != mCachedUids.end()) {
1017 if (cacheIter->second.first) {
1018 return cacheIter->second.second;
1019 } else {
1020 return ActivityManager::PROCESS_STATE_UNKNOWN;
1021 }
1022 }
1023 }
1024 ActivityManager am;
Hui Yuffffffc2020-03-24 16:13:59 -07001025 bool active = am.isUidActiveOrForeground(uid, String16("audioserver"));
Eric Laurente8c8b432018-10-17 10:08:02 -07001026 int state = ActivityManager::PROCESS_STATE_UNKNOWN;
1027 if (active) {
1028 state = am.getUidProcessState(uid, String16("audioserver"));
1029 }
1030 {
1031 Mutex::Autolock _l(mLock);
1032 mCachedUids.insert(std::pair<uid_t,
1033 std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
1034 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08001035
Eric Laurente8c8b432018-10-17 10:08:02 -07001036 return state;
1037}
1038
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001039void AudioPolicyService::UidPolicy::onUidActive(uid_t uid) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001040 updateUid(&mCachedUids, uid, true, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001041}
1042
1043void AudioPolicyService::UidPolicy::onUidGone(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001044 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, false);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001045}
1046
1047void AudioPolicyService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001048 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001049}
1050
Eric Laurente8c8b432018-10-17 10:08:02 -07001051void AudioPolicyService::UidPolicy::onUidStateChanged(uid_t uid,
1052 int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07001053 int64_t procStateSeq __unused,
1054 int32_t capability __unused) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001055 if (procState != ActivityManager::PROCESS_STATE_UNKNOWN) {
1056 updateUid(&mCachedUids, uid, true, procState, true);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001057 }
1058}
1059
1060void AudioPolicyService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001061 updateUid(&mOverrideUids, uid, active, ActivityManager::PROCESS_STATE_UNKNOWN, insert);
1062}
1063
1064void AudioPolicyService::UidPolicy::notifyService() {
1065 sp<AudioPolicyService> service = mService.promote();
1066 if (service != nullptr) {
1067 service->updateUidStates();
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001068 }
1069}
1070
Eric Laurente8c8b432018-10-17 10:08:02 -07001071void AudioPolicyService::UidPolicy::updateUid(std::unordered_map<uid_t,
1072 std::pair<bool, int>> *uids,
1073 uid_t uid,
1074 bool active,
1075 int state,
1076 bool insert) {
1077 if (isServiceUid(uid)) {
1078 return;
1079 }
1080 bool wasActive = isUidActive(uid);
1081 int previousState = getUidState(uid);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001082 {
1083 Mutex::Autolock _l(mLock);
Eric Laurente8c8b432018-10-17 10:08:02 -07001084 updateUidLocked(uids, uid, active, state, insert);
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001085 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001086 if (wasActive != isUidActive(uid) || state != previousState) {
1087 notifyService();
1088 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001089}
1090
Eric Laurente8c8b432018-10-17 10:08:02 -07001091void AudioPolicyService::UidPolicy::updateUidLocked(std::unordered_map<uid_t,
1092 std::pair<bool, int>> *uids,
1093 uid_t uid,
1094 bool active,
1095 int state,
1096 bool insert) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001097 auto it = uids->find(uid);
1098 if (it != uids->end()) {
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001099 if (insert) {
Eric Laurente8c8b432018-10-17 10:08:02 -07001100 if (state == ActivityManager::PROCESS_STATE_UNKNOWN) {
1101 it->second.first = active;
1102 }
1103 if (it->second.first) {
1104 it->second.second = state;
1105 } else {
1106 it->second.second = ActivityManager::PROCESS_STATE_UNKNOWN;
1107 }
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001108 } else {
1109 uids->erase(it);
1110 }
Eric Laurente8c8b432018-10-17 10:08:02 -07001111 } else if (insert && (state == ActivityManager::PROCESS_STATE_UNKNOWN)) {
1112 uids->insert(std::pair<uid_t, std::pair<bool, int>>(uid,
1113 std::pair<bool, int>(active, state)));
Mikhail Naganoveae73eb2018-04-03 16:57:36 -07001114 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001115}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001116
Eric Laurent4eb58f12018-12-07 16:41:02 -08001117bool AudioPolicyService::UidPolicy::isA11yOnTop() {
1118 for (const auto &uid : mCachedUids) {
Eric Laurent47670c92019-08-28 16:59:05 -07001119 if (!isA11yUid(uid.first)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001120 continue;
1121 }
Amith Yamasanibcbb3002019-01-23 13:53:33 -08001122 if (uid.second.second >= ActivityManager::PROCESS_STATE_TOP
1123 && uid.second.second <= ActivityManager::PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001124 return true;
1125 }
1126 }
1127 return false;
1128}
1129
Eric Laurentb78763e2018-10-17 10:08:02 -07001130bool AudioPolicyService::UidPolicy::isA11yUid(uid_t uid)
1131{
1132 std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid);
1133 return it != mA11yUids.end();
1134}
1135
Michael Groovercfd28302018-12-11 19:16:46 -08001136// ----------- AudioPolicyService::SensorPrivacyService implementation ----------
1137void AudioPolicyService::SensorPrivacyPolicy::registerSelf() {
1138 SensorPrivacyManager spm;
1139 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1140 spm.addSensorPrivacyListener(this);
1141}
1142
1143void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
1144 SensorPrivacyManager spm;
1145 spm.removeSensorPrivacyListener(this);
1146}
1147
1148bool AudioPolicyService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1149 return mSensorPrivacyEnabled;
1150}
1151
1152binder::Status AudioPolicyService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
1153 mSensorPrivacyEnabled = enabled;
1154 sp<AudioPolicyService> service = mService.promote();
1155 if (service != nullptr) {
1156 service->updateUidStates();
1157 }
1158 return binder::Status::ok();
1159}
1160
Mathias Agopian65ab4712010-07-14 17:59:35 -07001161// ----------- AudioPolicyService::AudioCommandThread implementation ----------
1162
Eric Laurentbfb1b832013-01-07 09:53:42 -08001163AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
1164 const wp<AudioPolicyService>& service)
1165 : Thread(false), mName(name), mService(service)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001166{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001167}
1168
1169
1170AudioPolicyService::AudioCommandThread::~AudioCommandThread()
1171{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001172 if (!mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001173 release_wake_lock(mName.string());
1174 }
1175 mAudioCommands.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001176}
1177
1178void AudioPolicyService::AudioCommandThread::onFirstRef()
1179{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001180 run(mName.string(), ANDROID_PRIORITY_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001181}
1182
1183bool AudioPolicyService::AudioCommandThread::threadLoop()
1184{
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001185 nsecs_t waitTime = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001186
1187 mLock.lock();
1188 while (!exitPending())
1189 {
Eric Laurent59a89232014-06-08 14:14:17 -07001190 sp<AudioPolicyService> svc;
1191 while (!mAudioCommands.isEmpty() && !exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001192 nsecs_t curTime = systemTime();
1193 // commands are sorted by increasing time stamp: execute them from index 0 and up
1194 if (mAudioCommands[0]->mTime <= curTime) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001195 sp<AudioCommand> command = mAudioCommands[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001196 mAudioCommands.removeAt(0);
Eric Laurent0ede8922014-05-09 18:04:42 -07001197 mLastCommand = command;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001198
1199 switch (command->mCommand) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001200 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001201 VolumeData *data = (VolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001202 ALOGV("AudioCommandThread() processing set volume stream %d, \
Eric Laurentde070132010-07-13 04:45:46 -07001203 volume %f, output %d", data->mStream, data->mVolume, data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001204 mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07001205 command->mStatus = AudioSystem::setStreamVolume(data->mStream,
1206 data->mVolume,
1207 data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001208 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001209 }break;
1210 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001211 ParametersData *data = (ParametersData *)command->mParam.get();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001212 ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
1213 data->mKeyValuePairs.string(), data->mIO);
Andy Hungfe726a62018-09-27 15:17:25 -07001214 mLock.unlock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001215 command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
Andy Hungfe726a62018-09-27 15:17:25 -07001216 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001217 }break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001218 case SET_VOICE_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001219 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
Steve Block3856b092011-10-20 11:56:00 +01001220 ALOGV("AudioCommandThread() processing set voice volume volume %f",
Eric Laurentde070132010-07-13 04:45:46 -07001221 data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001222 mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001223 command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
Andy Hungfe726a62018-09-27 15:17:25 -07001224 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001225 }break;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001226 case STOP_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001227 StopOutputData *data = (StopOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001228 ALOGV("AudioCommandThread() processing stop output portId %d",
1229 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001230 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001231 if (svc == 0) {
1232 break;
1233 }
1234 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001235 svc->doStopOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001236 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001237 }break;
1238 case RELEASE_OUTPUT: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001239 ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001240 ALOGV("AudioCommandThread() processing release output portId %d",
1241 data->mPortId);
Eric Laurent59a89232014-06-08 14:14:17 -07001242 svc = mService.promote();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001243 if (svc == 0) {
1244 break;
1245 }
1246 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001247 svc->doReleaseOutput(data->mPortId);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001248 mLock.lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001249 }break;
Eric Laurent951f4552014-05-20 10:48:17 -07001250 case CREATE_AUDIO_PATCH: {
1251 CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
1252 ALOGV("AudioCommandThread() processing create audio patch");
1253 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1254 if (af == 0) {
1255 command->mStatus = PERMISSION_DENIED;
1256 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001257 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001258 command->mStatus = af->createAudioPatch(&data->mPatch, &data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001259 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001260 }
1261 } break;
1262 case RELEASE_AUDIO_PATCH: {
1263 ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
1264 ALOGV("AudioCommandThread() processing release audio patch");
1265 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1266 if (af == 0) {
1267 command->mStatus = PERMISSION_DENIED;
1268 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001269 mLock.unlock();
Eric Laurent951f4552014-05-20 10:48:17 -07001270 command->mStatus = af->releaseAudioPatch(data->mHandle);
Andy Hungfe726a62018-09-27 15:17:25 -07001271 mLock.lock();
Eric Laurent951f4552014-05-20 10:48:17 -07001272 }
1273 } break;
Eric Laurentb52c1522014-05-20 11:27:36 -07001274 case UPDATE_AUDIOPORT_LIST: {
1275 ALOGV("AudioCommandThread() processing update audio port list");
Eric Laurent59a89232014-06-08 14:14:17 -07001276 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001277 if (svc == 0) {
1278 break;
1279 }
1280 mLock.unlock();
1281 svc->doOnAudioPortListUpdate();
1282 mLock.lock();
1283 }break;
1284 case UPDATE_AUDIOPATCH_LIST: {
1285 ALOGV("AudioCommandThread() processing update audio patch list");
Eric Laurent59a89232014-06-08 14:14:17 -07001286 svc = mService.promote();
Eric Laurentb52c1522014-05-20 11:27:36 -07001287 if (svc == 0) {
1288 break;
1289 }
1290 mLock.unlock();
1291 svc->doOnAudioPatchListUpdate();
1292 mLock.lock();
1293 }break;
François Gaffiecfe17322018-11-07 13:41:29 +01001294 case CHANGED_AUDIOVOLUMEGROUP: {
1295 AudioVolumeGroupData *data =
1296 static_cast<AudioVolumeGroupData *>(command->mParam.get());
1297 ALOGV("AudioCommandThread() processing update audio volume group");
1298 svc = mService.promote();
1299 if (svc == 0) {
1300 break;
1301 }
1302 mLock.unlock();
1303 svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
1304 mLock.lock();
1305 }break;
Eric Laurente1715a42014-05-20 11:30:42 -07001306 case SET_AUDIOPORT_CONFIG: {
1307 SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
1308 ALOGV("AudioCommandThread() processing set port config");
1309 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1310 if (af == 0) {
1311 command->mStatus = PERMISSION_DENIED;
1312 } else {
Andy Hungfe726a62018-09-27 15:17:25 -07001313 mLock.unlock();
Eric Laurente1715a42014-05-20 11:30:42 -07001314 command->mStatus = af->setAudioPortConfig(&data->mConfig);
Andy Hungfe726a62018-09-27 15:17:25 -07001315 mLock.lock();
Eric Laurente1715a42014-05-20 11:30:42 -07001316 }
1317 } break;
Jean-Michel Trivide801052015-04-14 19:10:14 -07001318 case DYN_POLICY_MIX_STATE_UPDATE: {
1319 DynPolicyMixStateUpdateData *data =
1320 (DynPolicyMixStateUpdateData *)command->mParam.get();
Jean-Michel Trivide801052015-04-14 19:10:14 -07001321 ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
1322 data->mRegId.string(), data->mState);
1323 svc = mService.promote();
1324 if (svc == 0) {
1325 break;
1326 }
1327 mLock.unlock();
1328 svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
1329 mLock.lock();
1330 } break;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001331 case RECORDING_CONFIGURATION_UPDATE: {
1332 RecordingConfigurationUpdateData *data =
1333 (RecordingConfigurationUpdateData *)command->mParam.get();
1334 ALOGV("AudioCommandThread() processing recording configuration update");
1335 svc = mService.promote();
1336 if (svc == 0) {
1337 break;
1338 }
1339 mLock.unlock();
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001340 svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
Eric Laurenta9f86652018-11-28 17:23:11 -08001341 &data->mClientConfig, data->mClientEffects,
1342 &data->mDeviceConfig, data->mEffects,
1343 data->mPatchHandle, data->mSource);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001344 mLock.lock();
1345 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001346 case SET_EFFECT_SUSPENDED: {
1347 SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
1348 ALOGV("AudioCommandThread() processing set effect suspended");
1349 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1350 if (af != 0) {
1351 mLock.unlock();
1352 af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
1353 mLock.lock();
1354 }
1355 } break;
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001356 case AUDIO_MODULES_UPDATE: {
1357 ALOGV("AudioCommandThread() processing audio modules update");
1358 svc = mService.promote();
1359 if (svc == 0) {
1360 break;
1361 }
1362 mLock.unlock();
1363 svc->doOnNewAudioModulesAvailable();
1364 mLock.lock();
1365 } break;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001366
Mathias Agopian65ab4712010-07-14 17:59:35 -07001367 default:
Steve Block5ff1dd52012-01-05 23:22:43 +00001368 ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001369 }
Eric Laurent0ede8922014-05-09 18:04:42 -07001370 {
1371 Mutex::Autolock _l(command->mLock);
1372 if (command->mWaitStatus) {
1373 command->mWaitStatus = false;
1374 command->mCond.signal();
1375 }
1376 }
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001377 waitTime = -1;
Zach Janga754b4f2015-10-27 01:29:34 +00001378 // release mLock before releasing strong reference on the service as
1379 // AudioPolicyService destructor calls AudioCommandThread::exit() which
1380 // acquires mLock.
1381 mLock.unlock();
1382 svc.clear();
1383 mLock.lock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001384 } else {
1385 waitTime = mAudioCommands[0]->mTime - curTime;
1386 break;
1387 }
1388 }
Zach Janga754b4f2015-10-27 01:29:34 +00001389
1390 // release delayed commands wake lock if the queue is empty
1391 if (mAudioCommands.isEmpty()) {
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07001392 release_wake_lock(mName.string());
Zach Janga754b4f2015-10-27 01:29:34 +00001393 }
1394
1395 // At this stage we have either an empty command queue or the first command in the queue
1396 // has a finite delay. So unless we are exiting it is safe to wait.
1397 if (!exitPending()) {
Eric Laurent59a89232014-06-08 14:14:17 -07001398 ALOGV("AudioCommandThread() going to sleep");
Eric Laurentd7eda8d2016-02-02 17:18:39 -08001399 if (waitTime == -1) {
1400 mWaitWorkCV.wait(mLock);
1401 } else {
1402 mWaitWorkCV.waitRelative(mLock, waitTime);
1403 }
Eric Laurent59a89232014-06-08 14:14:17 -07001404 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001405 }
Ricardo Garcia05f2fdc2014-07-24 15:48:24 -07001406 // release delayed commands wake lock before quitting
1407 if (!mAudioCommands.isEmpty()) {
1408 release_wake_lock(mName.string());
1409 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001410 mLock.unlock();
1411 return false;
1412}
1413
1414status_t AudioPolicyService::AudioCommandThread::dump(int fd)
1415{
1416 const size_t SIZE = 256;
1417 char buffer[SIZE];
1418 String8 result;
1419
1420 snprintf(buffer, SIZE, "AudioCommandThread %p Dump\n", this);
1421 result.append(buffer);
1422 write(fd, result.string(), result.size());
1423
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001424 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001425 if (!locked) {
1426 String8 result2(kCmdDeadlockedString);
1427 write(fd, result2.string(), result2.size());
1428 }
1429
1430 snprintf(buffer, SIZE, "- Commands:\n");
1431 result = String8(buffer);
1432 result.append(" Command Time Wait pParam\n");
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001433 for (size_t i = 0; i < mAudioCommands.size(); i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001434 mAudioCommands[i]->dump(buffer, SIZE);
1435 result.append(buffer);
1436 }
1437 result.append(" Last Command\n");
Eric Laurent0ede8922014-05-09 18:04:42 -07001438 if (mLastCommand != 0) {
1439 mLastCommand->dump(buffer, SIZE);
1440 result.append(buffer);
1441 } else {
1442 result.append(" none\n");
1443 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001444
1445 write(fd, result.string(), result.size());
1446
Mikhail Naganov12b716c2020-04-30 22:37:43 +00001447 dumpReleaseLock(mLock, locked);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001448
1449 return NO_ERROR;
1450}
1451
Glenn Kastenfff6d712012-01-12 16:38:12 -08001452status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
Eric Laurentde070132010-07-13 04:45:46 -07001453 float volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001454 audio_io_handle_t output,
Eric Laurentde070132010-07-13 04:45:46 -07001455 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001456{
Eric Laurent0ede8922014-05-09 18:04:42 -07001457 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001458 command->mCommand = SET_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07001459 sp<VolumeData> data = new VolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001460 data->mStream = stream;
1461 data->mVolume = volume;
1462 data->mIO = output;
1463 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07001464 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01001465 ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
Eric Laurentde070132010-07-13 04:45:46 -07001466 stream, volume, output);
Eric Laurent0ede8922014-05-09 18:04:42 -07001467 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001468}
1469
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001470status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
Dima Zavinfce7a472011-04-19 22:30:36 -07001471 const char *keyValuePairs,
Eric Laurentde070132010-07-13 04:45:46 -07001472 int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001473{
Eric Laurent0ede8922014-05-09 18:04:42 -07001474 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001475 command->mCommand = SET_PARAMETERS;
Eric Laurent0ede8922014-05-09 18:04:42 -07001476 sp<ParametersData> data = new ParametersData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001477 data->mIO = ioHandle;
Dima Zavinfce7a472011-04-19 22:30:36 -07001478 data->mKeyValuePairs = String8(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001479 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07001480 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01001481 ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
Dima Zavinfce7a472011-04-19 22:30:36 -07001482 keyValuePairs, ioHandle, delayMs);
Eric Laurent0ede8922014-05-09 18:04:42 -07001483 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001484}
1485
1486status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
1487{
Eric Laurent0ede8922014-05-09 18:04:42 -07001488 sp<AudioCommand> command = new AudioCommand();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001489 command->mCommand = SET_VOICE_VOLUME;
Eric Laurent0ede8922014-05-09 18:04:42 -07001490 sp<VoiceVolumeData> data = new VoiceVolumeData();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001491 data->mVolume = volume;
1492 command->mParam = data;
Eric Laurent0ede8922014-05-09 18:04:42 -07001493 command->mWaitStatus = true;
Steve Block3856b092011-10-20 11:56:00 +01001494 ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
Eric Laurent0ede8922014-05-09 18:04:42 -07001495 return sendCommand(command, delayMs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001496}
1497
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001498void AudioPolicyService::AudioCommandThread::setEffectSuspendedCommand(int effectId,
1499 audio_session_t sessionId,
1500 bool suspended)
1501{
1502 sp<AudioCommand> command = new AudioCommand();
1503 command->mCommand = SET_EFFECT_SUSPENDED;
1504 sp<SetEffectSuspendedData> data = new SetEffectSuspendedData();
1505 data->mEffectId = effectId;
1506 data->mSessionId = sessionId;
1507 data->mSuspended = suspended;
1508 command->mParam = data;
1509 ALOGV("AudioCommandThread() adding set suspended effectId %d sessionId %d suspended %d",
1510 effectId, sessionId, suspended);
1511 sendCommand(command);
1512}
1513
1514
Eric Laurentd7fe0862018-07-14 16:48:01 -07001515void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001516{
Eric Laurent0ede8922014-05-09 18:04:42 -07001517 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001518 command->mCommand = STOP_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07001519 sp<StopOutputData> data = new StopOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001520 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01001521 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07001522 ALOGV("AudioCommandThread() adding stop output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07001523 sendCommand(command);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001524}
1525
Eric Laurentd7fe0862018-07-14 16:48:01 -07001526void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_port_handle_t portId)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001527{
Eric Laurent0ede8922014-05-09 18:04:42 -07001528 sp<AudioCommand> command = new AudioCommand();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001529 command->mCommand = RELEASE_OUTPUT;
Eric Laurent0ede8922014-05-09 18:04:42 -07001530 sp<ReleaseOutputData> data = new ReleaseOutputData();
Eric Laurentd7fe0862018-07-14 16:48:01 -07001531 data->mPortId = portId;
Jesper Tragardh48412dc2014-03-24 14:12:43 +01001532 command->mParam = data;
Eric Laurentd7fe0862018-07-14 16:48:01 -07001533 ALOGV("AudioCommandThread() adding release output portId %d", portId);
Eric Laurent0ede8922014-05-09 18:04:42 -07001534 sendCommand(command);
1535}
1536
Eric Laurent951f4552014-05-20 10:48:17 -07001537status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
1538 const struct audio_patch *patch,
1539 audio_patch_handle_t *handle,
1540 int delayMs)
1541{
1542 status_t status = NO_ERROR;
1543
1544 sp<AudioCommand> command = new AudioCommand();
1545 command->mCommand = CREATE_AUDIO_PATCH;
1546 CreateAudioPatchData *data = new CreateAudioPatchData();
1547 data->mPatch = *patch;
1548 data->mHandle = *handle;
1549 command->mParam = data;
1550 command->mWaitStatus = true;
1551 ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
1552 status = sendCommand(command, delayMs);
1553 if (status == NO_ERROR) {
1554 *handle = data->mHandle;
1555 }
1556 return status;
1557}
1558
1559status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
1560 int delayMs)
1561{
1562 sp<AudioCommand> command = new AudioCommand();
1563 command->mCommand = RELEASE_AUDIO_PATCH;
1564 ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
1565 data->mHandle = handle;
1566 command->mParam = data;
1567 command->mWaitStatus = true;
1568 ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
1569 return sendCommand(command, delayMs);
1570}
1571
Eric Laurentb52c1522014-05-20 11:27:36 -07001572void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
1573{
1574 sp<AudioCommand> command = new AudioCommand();
1575 command->mCommand = UPDATE_AUDIOPORT_LIST;
1576 ALOGV("AudioCommandThread() adding update audio port list");
1577 sendCommand(command);
1578}
1579
1580void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
1581{
1582 sp<AudioCommand>command = new AudioCommand();
1583 command->mCommand = UPDATE_AUDIOPATCH_LIST;
1584 ALOGV("AudioCommandThread() adding update audio patch list");
1585 sendCommand(command);
1586}
1587
François Gaffiecfe17322018-11-07 13:41:29 +01001588void AudioPolicyService::AudioCommandThread::changeAudioVolumeGroupCommand(volume_group_t group,
1589 int flags)
1590{
1591 sp<AudioCommand>command = new AudioCommand();
1592 command->mCommand = CHANGED_AUDIOVOLUMEGROUP;
1593 AudioVolumeGroupData *data= new AudioVolumeGroupData();
1594 data->mGroup = group;
1595 data->mFlags = flags;
1596 command->mParam = data;
1597 ALOGV("AudioCommandThread() adding audio volume group changed");
1598 sendCommand(command);
1599}
1600
Eric Laurente1715a42014-05-20 11:30:42 -07001601status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
1602 const struct audio_port_config *config, int delayMs)
1603{
1604 sp<AudioCommand> command = new AudioCommand();
1605 command->mCommand = SET_AUDIOPORT_CONFIG;
1606 SetAudioPortConfigData *data = new SetAudioPortConfigData();
1607 data->mConfig = *config;
1608 command->mParam = data;
1609 command->mWaitStatus = true;
1610 ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
1611 return sendCommand(command, delayMs);
1612}
1613
Jean-Michel Trivide801052015-04-14 19:10:14 -07001614void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001615 const String8& regId, int32_t state)
Jean-Michel Trivide801052015-04-14 19:10:14 -07001616{
1617 sp<AudioCommand> command = new AudioCommand();
1618 command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
1619 DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
1620 data->mRegId = regId;
1621 data->mState = state;
1622 command->mParam = data;
1623 ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
1624 regId.string(), state);
1625 sendCommand(command);
1626}
1627
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001628void AudioPolicyService::AudioCommandThread::recordingConfigurationUpdateCommand(
Eric Laurenta9f86652018-11-28 17:23:11 -08001629 int event,
1630 const record_client_info_t *clientInfo,
1631 const audio_config_base_t *clientConfig,
1632 std::vector<effect_descriptor_t> clientEffects,
1633 const audio_config_base_t *deviceConfig,
1634 std::vector<effect_descriptor_t> effects,
1635 audio_patch_handle_t patchHandle,
1636 audio_source_t source)
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001637{
1638 sp<AudioCommand>command = new AudioCommand();
1639 command->mCommand = RECORDING_CONFIGURATION_UPDATE;
1640 RecordingConfigurationUpdateData *data = new RecordingConfigurationUpdateData();
1641 data->mEvent = event;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001642 data->mClientInfo = *clientInfo;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08001643 data->mClientConfig = *clientConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08001644 data->mClientEffects = clientEffects;
Jean-Michel Trivi7281aa92016-02-17 15:33:40 -08001645 data->mDeviceConfig = *deviceConfig;
Eric Laurenta9f86652018-11-28 17:23:11 -08001646 data->mEffects = effects;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08001647 data->mPatchHandle = patchHandle;
Eric Laurenta9f86652018-11-28 17:23:11 -08001648 data->mSource = source;
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001649 command->mParam = data;
Jean-Michel Triviac4e4292016-12-22 11:39:31 -08001650 ALOGV("AudioCommandThread() adding recording configuration update event %d, source %d uid %u",
1651 event, clientInfo->source, clientInfo->uid);
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001652 sendCommand(command);
1653}
1654
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001655void AudioPolicyService::AudioCommandThread::audioModulesUpdateCommand()
1656{
1657 sp<AudioCommand> command = new AudioCommand();
1658 command->mCommand = AUDIO_MODULES_UPDATE;
1659 sendCommand(command);
1660}
1661
Eric Laurent0ede8922014-05-09 18:04:42 -07001662status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
1663{
1664 {
1665 Mutex::Autolock _l(mLock);
1666 insertCommand_l(command, delayMs);
1667 mWaitWorkCV.signal();
1668 }
1669 Mutex::Autolock _l(command->mLock);
1670 while (command->mWaitStatus) {
1671 nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
1672 if (command->mCond.waitRelative(command->mLock, timeOutNs) != NO_ERROR) {
1673 command->mStatus = TIMED_OUT;
1674 command->mWaitStatus = false;
1675 }
1676 }
1677 return command->mStatus;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001678}
1679
Mathias Agopian65ab4712010-07-14 17:59:35 -07001680// insertCommand_l() must be called with mLock held
Eric Laurent0ede8922014-05-09 18:04:42 -07001681void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001682{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001683 ssize_t i; // not size_t because i will count down to -1
Eric Laurent0ede8922014-05-09 18:04:42 -07001684 Vector < sp<AudioCommand> > removedCommands;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001685 command->mTime = systemTime() + milliseconds(delayMs);
1686
1687 // acquire wake lock to make sure delayed commands are processed
Eric Laurentbfb1b832013-01-07 09:53:42 -08001688 if (mAudioCommands.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001689 acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.string());
1690 }
1691
1692 // check same pending commands with later time stamps and eliminate them
Ivan Lozano5ff158f2017-10-30 09:06:24 -07001693 for (i = (ssize_t)mAudioCommands.size()-1; i >= 0; i--) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001694 sp<AudioCommand> command2 = mAudioCommands[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001695 // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
1696 if (command2->mTime <= command->mTime) break;
Eric Laurente45b48a2014-09-04 16:40:57 -07001697
1698 // create audio patch or release audio patch commands are equivalent
1699 // with regard to filtering
1700 if ((command->mCommand == CREATE_AUDIO_PATCH) ||
1701 (command->mCommand == RELEASE_AUDIO_PATCH)) {
1702 if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
1703 (command2->mCommand != RELEASE_AUDIO_PATCH)) {
1704 continue;
1705 }
1706 } else if (command2->mCommand != command->mCommand) continue;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001707
1708 switch (command->mCommand) {
1709 case SET_PARAMETERS: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001710 ParametersData *data = (ParametersData *)command->mParam.get();
1711 ParametersData *data2 = (ParametersData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001712 if (data->mIO != data2->mIO) break;
Steve Block3856b092011-10-20 11:56:00 +01001713 ALOGV("Comparing parameter command %s to new command %s",
Eric Laurentde070132010-07-13 04:45:46 -07001714 data2->mKeyValuePairs.string(), data->mKeyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001715 AudioParameter param = AudioParameter(data->mKeyValuePairs);
1716 AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
1717 for (size_t j = 0; j < param.size(); j++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001718 String8 key;
1719 String8 value;
1720 param.getAt(j, key, value);
1721 for (size_t k = 0; k < param2.size(); k++) {
1722 String8 key2;
1723 String8 value2;
1724 param2.getAt(k, key2, value2);
1725 if (key2 == key) {
1726 param2.remove(key2);
1727 ALOGV("Filtering out parameter %s", key2.string());
1728 break;
1729 }
1730 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001731 }
1732 // if all keys have been filtered out, remove the command.
1733 // otherwise, update the key value pairs
1734 if (param2.size() == 0) {
1735 removedCommands.add(command2);
1736 } else {
1737 data2->mKeyValuePairs = param2.toString();
1738 }
Eric Laurent21e54562013-09-23 12:08:05 -07001739 command->mTime = command2->mTime;
1740 // force delayMs to non 0 so that code below does not request to wait for
1741 // command status as the command is now delayed
1742 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001743 } break;
1744
1745 case SET_VOLUME: {
Eric Laurent0ede8922014-05-09 18:04:42 -07001746 VolumeData *data = (VolumeData *)command->mParam.get();
1747 VolumeData *data2 = (VolumeData *)command2->mParam.get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001748 if (data->mIO != data2->mIO) break;
1749 if (data->mStream != data2->mStream) break;
Steve Block3856b092011-10-20 11:56:00 +01001750 ALOGV("Filtering out volume command on output %d for stream %d",
Eric Laurentde070132010-07-13 04:45:46 -07001751 data->mIO, data->mStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001752 removedCommands.add(command2);
Eric Laurent21e54562013-09-23 12:08:05 -07001753 command->mTime = command2->mTime;
1754 // force delayMs to non 0 so that code below does not request to wait for
1755 // command status as the command is now delayed
1756 delayMs = 1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001757 } break;
Eric Laurente45b48a2014-09-04 16:40:57 -07001758
Eric Laurentbaf35fe2016-07-27 15:36:53 -07001759 case SET_VOICE_VOLUME: {
1760 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
1761 VoiceVolumeData *data2 = (VoiceVolumeData *)command2->mParam.get();
1762 ALOGV("Filtering out voice volume command value %f replaced by %f",
1763 data2->mVolume, data->mVolume);
1764 removedCommands.add(command2);
1765 command->mTime = command2->mTime;
1766 // force delayMs to non 0 so that code below does not request to wait for
1767 // command status as the command is now delayed
1768 delayMs = 1;
1769 } break;
1770
Eric Laurente45b48a2014-09-04 16:40:57 -07001771 case CREATE_AUDIO_PATCH:
1772 case RELEASE_AUDIO_PATCH: {
1773 audio_patch_handle_t handle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07001774 struct audio_patch patch;
Eric Laurente45b48a2014-09-04 16:40:57 -07001775 if (command->mCommand == CREATE_AUDIO_PATCH) {
1776 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07001777 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07001778 } else {
1779 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
Mikhail Naganov7be71d22018-05-23 16:51:46 -07001780 memset(&patch, 0, sizeof(patch));
Eric Laurente45b48a2014-09-04 16:40:57 -07001781 }
1782 audio_patch_handle_t handle2;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07001783 struct audio_patch patch2;
Eric Laurente45b48a2014-09-04 16:40:57 -07001784 if (command2->mCommand == CREATE_AUDIO_PATCH) {
1785 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07001786 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
Eric Laurente45b48a2014-09-04 16:40:57 -07001787 } else {
1788 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
Glenn Kastenf60b6b62015-07-06 10:53:26 -07001789 memset(&patch2, 0, sizeof(patch2));
Eric Laurente45b48a2014-09-04 16:40:57 -07001790 }
1791 if (handle != handle2) break;
Haynes Mathew Georgea2d4a6d2014-10-13 13:05:22 -07001792 /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
1793 same output. */
1794 if( (command->mCommand == CREATE_AUDIO_PATCH) &&
1795 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
1796 bool isOutputDiff = false;
1797 if (patch.num_sources == patch2.num_sources) {
1798 for (unsigned count = 0; count < patch.num_sources; count++) {
1799 if (patch.sources[count].id != patch2.sources[count].id) {
1800 isOutputDiff = true;
1801 break;
1802 }
1803 }
1804 if (isOutputDiff)
1805 break;
1806 }
1807 }
Eric Laurente45b48a2014-09-04 16:40:57 -07001808 ALOGV("Filtering out %s audio patch command for handle %d",
1809 (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
1810 removedCommands.add(command2);
1811 command->mTime = command2->mTime;
1812 // force delayMs to non 0 so that code below does not request to wait for
1813 // command status as the command is now delayed
1814 delayMs = 1;
1815 } break;
1816
Jean-Michel Trivide801052015-04-14 19:10:14 -07001817 case DYN_POLICY_MIX_STATE_UPDATE: {
1818
1819 } break;
1820
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001821 case RECORDING_CONFIGURATION_UPDATE: {
1822
1823 } break;
1824
Mathias Agopian65ab4712010-07-14 17:59:35 -07001825 default:
1826 break;
1827 }
1828 }
1829
1830 // remove filtered commands
1831 for (size_t j = 0; j < removedCommands.size(); j++) {
1832 // removed commands always have time stamps greater than current command
1833 for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
Eric Laurent0ede8922014-05-09 18:04:42 -07001834 if (mAudioCommands[k].get() == removedCommands[j].get()) {
Steve Block3856b092011-10-20 11:56:00 +01001835 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001836 mAudioCommands.removeAt(k);
1837 break;
1838 }
1839 }
1840 }
1841 removedCommands.clear();
1842
Eric Laurentaa79bef2015-01-15 14:33:51 -08001843 // Disable wait for status if delay is not 0.
1844 // Except for create audio patch command because the returned patch handle
1845 // is needed by audio policy manager
1846 if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
Eric Laurentcec4abb2012-07-03 12:23:02 -07001847 command->mWaitStatus = false;
1848 }
Eric Laurentcec4abb2012-07-03 12:23:02 -07001849
Mathias Agopian65ab4712010-07-14 17:59:35 -07001850 // insert command at the right place according to its time stamp
Eric Laurent1e693b52014-07-09 15:03:28 -07001851 ALOGV("inserting command: %d at index %zd, num commands %zu",
1852 command->mCommand, i+1, mAudioCommands.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001853 mAudioCommands.insertAt(command, i + 1);
1854}
1855
1856void AudioPolicyService::AudioCommandThread::exit()
1857{
Steve Block3856b092011-10-20 11:56:00 +01001858 ALOGV("AudioCommandThread::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001859 {
1860 AutoMutex _l(mLock);
1861 requestExit();
1862 mWaitWorkCV.signal();
1863 }
Zach Janga754b4f2015-10-27 01:29:34 +00001864 // Note that we can call it from the thread loop if all other references have been released
1865 // but it will safely return WOULD_BLOCK in this case
Mathias Agopian65ab4712010-07-14 17:59:35 -07001866 requestExitAndWait();
1867}
1868
1869void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
1870{
1871 snprintf(buffer, size, " %02d %06d.%03d %01u %p\n",
1872 mCommand,
1873 (int)ns2s(mTime),
1874 (int)ns2ms(mTime)%1000,
1875 mWaitStatus,
Eric Laurent0ede8922014-05-09 18:04:42 -07001876 mParam.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001877}
1878
Dima Zavinfce7a472011-04-19 22:30:36 -07001879/******* helpers for the service_ops callbacks defined below *********/
1880void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
1881 const char *keyValuePairs,
1882 int delayMs)
1883{
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001884 mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
Dima Zavinfce7a472011-04-19 22:30:36 -07001885 delayMs);
1886}
1887
1888int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
1889 float volume,
1890 audio_io_handle_t output,
1891 int delayMs)
1892{
Glenn Kastenfff6d712012-01-12 16:38:12 -08001893 return (int)mAudioCommandThread->volumeCommand(stream, volume,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001894 output, delayMs);
Dima Zavinfce7a472011-04-19 22:30:36 -07001895}
1896
Dima Zavinfce7a472011-04-19 22:30:36 -07001897int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
1898{
1899 return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
1900}
1901
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001902void AudioPolicyService::setEffectSuspended(int effectId,
1903 audio_session_t sessionId,
1904 bool suspended)
1905{
1906 mAudioCommandThread->setEffectSuspendedCommand(effectId, sessionId, suspended);
1907}
1908
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001909void AudioPolicyService::onNewAudioModulesAvailable()
1910{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07001911 mOutputCommandThread->audioModulesUpdateCommand();
Mikhail Naganov88b30d22020-03-09 19:43:13 +00001912}
1913
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001914
Dima Zavinfce7a472011-04-19 22:30:36 -07001915extern "C" {
Eric Laurent2d388ec2014-03-07 13:25:54 -08001916audio_module_handle_t aps_load_hw_module(void *service __unused,
1917 const char *name);
1918audio_io_handle_t aps_open_output(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07001919 audio_devices_t *pDevices,
1920 uint32_t *pSamplingRate,
1921 audio_format_t *pFormat,
1922 audio_channel_mask_t *pChannelMask,
1923 uint32_t *pLatencyMs,
Eric Laurent2d388ec2014-03-07 13:25:54 -08001924 audio_output_flags_t flags);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001925
Eric Laurent2d388ec2014-03-07 13:25:54 -08001926audio_io_handle_t aps_open_output_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07001927 audio_module_handle_t module,
1928 audio_devices_t *pDevices,
1929 uint32_t *pSamplingRate,
1930 audio_format_t *pFormat,
1931 audio_channel_mask_t *pChannelMask,
1932 uint32_t *pLatencyMs,
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001933 audio_output_flags_t flags,
Eric Laurent2d388ec2014-03-07 13:25:54 -08001934 const audio_offload_info_t *offloadInfo);
1935audio_io_handle_t aps_open_dup_output(void *service __unused,
Dima Zavinfce7a472011-04-19 22:30:36 -07001936 audio_io_handle_t output1,
Eric Laurent2d388ec2014-03-07 13:25:54 -08001937 audio_io_handle_t output2);
1938int aps_close_output(void *service __unused, audio_io_handle_t output);
1939int aps_suspend_output(void *service __unused, audio_io_handle_t output);
1940int aps_restore_output(void *service __unused, audio_io_handle_t output);
1941audio_io_handle_t aps_open_input(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07001942 audio_devices_t *pDevices,
1943 uint32_t *pSamplingRate,
1944 audio_format_t *pFormat,
1945 audio_channel_mask_t *pChannelMask,
Eric Laurent2d388ec2014-03-07 13:25:54 -08001946 audio_in_acoustics_t acoustics __unused);
1947audio_io_handle_t aps_open_input_on_module(void *service __unused,
Eric Laurenta4c5a552012-03-29 10:12:40 -07001948 audio_module_handle_t module,
1949 audio_devices_t *pDevices,
1950 uint32_t *pSamplingRate,
1951 audio_format_t *pFormat,
Eric Laurent2d388ec2014-03-07 13:25:54 -08001952 audio_channel_mask_t *pChannelMask);
1953int aps_close_input(void *service __unused, audio_io_handle_t input);
1954int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
Glenn Kastend848eb42016-03-08 13:42:11 -08001955int aps_move_effects(void *service __unused, audio_session_t session,
Dima Zavinfce7a472011-04-19 22:30:36 -07001956 audio_io_handle_t src_output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08001957 audio_io_handle_t dst_output);
1958char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
1959 const char *keys);
1960void aps_set_parameters(void *service, audio_io_handle_t io_handle,
1961 const char *kv_pairs, int delay_ms);
1962int aps_set_stream_volume(void *service, audio_stream_type_t stream,
Dima Zavinfce7a472011-04-19 22:30:36 -07001963 float volume, audio_io_handle_t output,
Eric Laurent2d388ec2014-03-07 13:25:54 -08001964 int delay_ms);
Eric Laurent2d388ec2014-03-07 13:25:54 -08001965int aps_set_voice_volume(void *service, float volume, int delay_ms);
1966};
Dima Zavinfce7a472011-04-19 22:30:36 -07001967
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08001968} // namespace android