1 /*
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
20 #include "Configuration.h"
21 #undef __STRICT_ANSI__
22 #define __STDINT_LIMITS
23 #define __STDC_LIMIT_MACROS
24 #include <stdint.h>
25 #include <sys/time.h>
26
27 #include <audio_utils/clock.h>
28 #include <binder/IServiceManager.h>
29 #include <utils/Log.h>
30 #include <cutils/properties.h>
31 #include <binder/IPCThreadState.h>
32 #include <binder/PermissionController.h>
33 #include <binder/IResultReceiver.h>
34 #include <utils/String16.h>
35 #include <utils/threads.h>
36 #include "AudioPolicyService.h"
37 #include <hardware_legacy/power.h>
38 #include <media/AudioEffect.h>
39 #include <media/AudioParameter.h>
40 #include <mediautils/ServiceUtilities.h>
41 #include <sensorprivacy/SensorPrivacyManager.h>
42
43 #include <system/audio.h>
44 #include <system/audio_policy.h>
45
46 namespace android {
47
48 static const char kDeadlockedString[] = "AudioPolicyService may be deadlocked\n";
49 static const char kCmdDeadlockedString[] = "AudioPolicyService command thread may be deadlocked\n";
50
51 static const int kDumpLockTimeoutNs = 1 * NANOS_PER_SECOND;
52
53 static const nsecs_t kAudioCommandTimeoutNs = seconds(3); // 3 seconds
54
55 static const String16 sManageAudioPolicyPermission("android.permission.MANAGE_AUDIO_POLICY");
56
57 // ----------------------------------------------------------------------------
58
AudioPolicyService()59 AudioPolicyService::AudioPolicyService()
60 : BnAudioPolicyService(), mpAudioPolicyDev(NULL), mpAudioPolicy(NULL),
61 mAudioPolicyManager(NULL), mAudioPolicyClient(NULL), mPhoneState(AUDIO_MODE_INVALID)
62 {
63 }
64
onFirstRef()65 void AudioPolicyService::onFirstRef()
66 {
67 {
68 Mutex::Autolock _l(mLock);
69
70 // start audio commands thread
71 mAudioCommandThread = new AudioCommandThread(String8("ApmAudio"), this);
72 // start output activity command thread
73 mOutputCommandThread = new AudioCommandThread(String8("ApmOutput"), this);
74
75 mAudioPolicyClient = new AudioPolicyClient(this);
76 mAudioPolicyManager = createAudioPolicyManager(mAudioPolicyClient);
77 }
78 // load audio processing modules
79 sp<AudioPolicyEffects>audioPolicyEffects = new AudioPolicyEffects();
80 {
81 Mutex::Autolock _l(mLock);
82 mAudioPolicyEffects = audioPolicyEffects;
83 }
84
85 mUidPolicy = new UidPolicy(this);
86 mUidPolicy->registerSelf();
87
88 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
89 mSensorPrivacyPolicy->registerSelf();
90 }
91
~AudioPolicyService()92 AudioPolicyService::~AudioPolicyService()
93 {
94 mAudioCommandThread->exit();
95 mOutputCommandThread->exit();
96
97 destroyAudioPolicyManager(mAudioPolicyManager);
98 delete mAudioPolicyClient;
99
100 mNotificationClients.clear();
101 mAudioPolicyEffects.clear();
102
103 mUidPolicy->unregisterSelf();
104 mUidPolicy.clear();
105
106 mSensorPrivacyPolicy->unregisterSelf();
107 mSensorPrivacyPolicy.clear();
108 }
109
110 // A notification client is always registered by AudioSystem when the client process
111 // connects to AudioPolicyService.
registerClient(const sp<IAudioPolicyServiceClient> & client)112 void AudioPolicyService::registerClient(const sp<IAudioPolicyServiceClient>& client)
113 {
114 if (client == 0) {
115 ALOGW("%s got NULL client", __FUNCTION__);
116 return;
117 }
118 Mutex::Autolock _l(mNotificationClientsLock);
119
120 uid_t uid = IPCThreadState::self()->getCallingUid();
121 pid_t pid = IPCThreadState::self()->getCallingPid();
122 int64_t token = ((int64_t)uid<<32) | pid;
123
124 if (mNotificationClients.indexOfKey(token) < 0) {
125 sp<NotificationClient> notificationClient = new NotificationClient(this,
126 client,
127 uid,
128 pid);
129 ALOGV("registerClient() client %p, uid %d pid %d", client.get(), uid, pid);
130
131 mNotificationClients.add(token, notificationClient);
132
133 sp<IBinder> binder = IInterface::asBinder(client);
134 binder->linkToDeath(notificationClient);
135 }
136 }
137
setAudioPortCallbacksEnabled(bool enabled)138 void AudioPolicyService::setAudioPortCallbacksEnabled(bool enabled)
139 {
140 Mutex::Autolock _l(mNotificationClientsLock);
141
142 uid_t uid = IPCThreadState::self()->getCallingUid();
143 pid_t pid = IPCThreadState::self()->getCallingPid();
144 int64_t token = ((int64_t)uid<<32) | pid;
145
146 if (mNotificationClients.indexOfKey(token) < 0) {
147 return;
148 }
149 mNotificationClients.valueFor(token)->setAudioPortCallbacksEnabled(enabled);
150 }
151
setAudioVolumeGroupCallbacksEnabled(bool enabled)152 void AudioPolicyService::setAudioVolumeGroupCallbacksEnabled(bool enabled)
153 {
154 Mutex::Autolock _l(mNotificationClientsLock);
155
156 uid_t uid = IPCThreadState::self()->getCallingUid();
157 pid_t pid = IPCThreadState::self()->getCallingPid();
158 int64_t token = ((int64_t)uid<<32) | pid;
159
160 if (mNotificationClients.indexOfKey(token) < 0) {
161 return;
162 }
163 mNotificationClients.valueFor(token)->setAudioVolumeGroupCallbacksEnabled(enabled);
164 }
165
166 // removeNotificationClient() is called when the client process dies.
removeNotificationClient(uid_t uid,pid_t pid)167 void AudioPolicyService::removeNotificationClient(uid_t uid, pid_t pid)
168 {
169 {
170 Mutex::Autolock _l(mNotificationClientsLock);
171 int64_t token = ((int64_t)uid<<32) | pid;
172 mNotificationClients.removeItem(token);
173 }
174 {
175 Mutex::Autolock _l(mLock);
176 bool hasSameUid = false;
177 for (size_t i = 0; i < mNotificationClients.size(); i++) {
178 if (mNotificationClients.valueAt(i)->uid() == uid) {
179 hasSameUid = true;
180 break;
181 }
182 }
183 if (mAudioPolicyManager && !hasSameUid) {
184 // called from binder death notification: no need to clear caller identity
185 mAudioPolicyManager->releaseResourcesForUid(uid);
186 }
187 }
188 }
189
onAudioPortListUpdate()190 void AudioPolicyService::onAudioPortListUpdate()
191 {
192 mOutputCommandThread->updateAudioPortListCommand();
193 }
194
doOnAudioPortListUpdate()195 void AudioPolicyService::doOnAudioPortListUpdate()
196 {
197 Mutex::Autolock _l(mNotificationClientsLock);
198 for (size_t i = 0; i < mNotificationClients.size(); i++) {
199 mNotificationClients.valueAt(i)->onAudioPortListUpdate();
200 }
201 }
202
onAudioPatchListUpdate()203 void AudioPolicyService::onAudioPatchListUpdate()
204 {
205 mOutputCommandThread->updateAudioPatchListCommand();
206 }
207
doOnAudioPatchListUpdate()208 void AudioPolicyService::doOnAudioPatchListUpdate()
209 {
210 Mutex::Autolock _l(mNotificationClientsLock);
211 for (size_t i = 0; i < mNotificationClients.size(); i++) {
212 mNotificationClients.valueAt(i)->onAudioPatchListUpdate();
213 }
214 }
215
onAudioVolumeGroupChanged(volume_group_t group,int flags)216 void AudioPolicyService::onAudioVolumeGroupChanged(volume_group_t group, int flags)
217 {
218 mOutputCommandThread->changeAudioVolumeGroupCommand(group, flags);
219 }
220
doOnAudioVolumeGroupChanged(volume_group_t group,int flags)221 void AudioPolicyService::doOnAudioVolumeGroupChanged(volume_group_t group, int flags)
222 {
223 Mutex::Autolock _l(mNotificationClientsLock);
224 for (size_t i = 0; i < mNotificationClients.size(); i++) {
225 mNotificationClients.valueAt(i)->onAudioVolumeGroupChanged(group, flags);
226 }
227 }
228
onDynamicPolicyMixStateUpdate(const String8 & regId,int32_t state)229 void AudioPolicyService::onDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
230 {
231 ALOGV("AudioPolicyService::onDynamicPolicyMixStateUpdate(%s, %d)",
232 regId.string(), state);
233 mOutputCommandThread->dynamicPolicyMixStateUpdateCommand(regId, state);
234 }
235
doOnDynamicPolicyMixStateUpdate(const String8 & regId,int32_t state)236 void AudioPolicyService::doOnDynamicPolicyMixStateUpdate(const String8& regId, int32_t state)
237 {
238 Mutex::Autolock _l(mNotificationClientsLock);
239 for (size_t i = 0; i < mNotificationClients.size(); i++) {
240 mNotificationClients.valueAt(i)->onDynamicPolicyMixStateUpdate(regId, state);
241 }
242 }
243
onRecordingConfigurationUpdate(int event,const record_client_info_t * clientInfo,const audio_config_base_t * clientConfig,std::vector<effect_descriptor_t> clientEffects,const audio_config_base_t * deviceConfig,std::vector<effect_descriptor_t> effects,audio_patch_handle_t patchHandle,audio_source_t source)244 void AudioPolicyService::onRecordingConfigurationUpdate(
245 int event,
246 const record_client_info_t *clientInfo,
247 const audio_config_base_t *clientConfig,
248 std::vector<effect_descriptor_t> clientEffects,
249 const audio_config_base_t *deviceConfig,
250 std::vector<effect_descriptor_t> effects,
251 audio_patch_handle_t patchHandle,
252 audio_source_t source)
253 {
254 mOutputCommandThread->recordingConfigurationUpdateCommand(event, clientInfo,
255 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
256 }
257
doOnRecordingConfigurationUpdate(int event,const record_client_info_t * clientInfo,const audio_config_base_t * clientConfig,std::vector<effect_descriptor_t> clientEffects,const audio_config_base_t * deviceConfig,std::vector<effect_descriptor_t> effects,audio_patch_handle_t patchHandle,audio_source_t source)258 void AudioPolicyService::doOnRecordingConfigurationUpdate(
259 int event,
260 const record_client_info_t *clientInfo,
261 const audio_config_base_t *clientConfig,
262 std::vector<effect_descriptor_t> clientEffects,
263 const audio_config_base_t *deviceConfig,
264 std::vector<effect_descriptor_t> effects,
265 audio_patch_handle_t patchHandle,
266 audio_source_t source)
267 {
268 Mutex::Autolock _l(mNotificationClientsLock);
269 for (size_t i = 0; i < mNotificationClients.size(); i++) {
270 mNotificationClients.valueAt(i)->onRecordingConfigurationUpdate(event, clientInfo,
271 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
272 }
273 }
274
clientCreateAudioPatch(const struct audio_patch * patch,audio_patch_handle_t * handle,int delayMs)275 status_t AudioPolicyService::clientCreateAudioPatch(const struct audio_patch *patch,
276 audio_patch_handle_t *handle,
277 int delayMs)
278 {
279 return mAudioCommandThread->createAudioPatchCommand(patch, handle, delayMs);
280 }
281
clientReleaseAudioPatch(audio_patch_handle_t handle,int delayMs)282 status_t AudioPolicyService::clientReleaseAudioPatch(audio_patch_handle_t handle,
283 int delayMs)
284 {
285 return mAudioCommandThread->releaseAudioPatchCommand(handle, delayMs);
286 }
287
clientSetAudioPortConfig(const struct audio_port_config * config,int delayMs)288 status_t AudioPolicyService::clientSetAudioPortConfig(const struct audio_port_config *config,
289 int delayMs)
290 {
291 return mAudioCommandThread->setAudioPortConfigCommand(config, delayMs);
292 }
293
NotificationClient(const sp<AudioPolicyService> & service,const sp<IAudioPolicyServiceClient> & client,uid_t uid,pid_t pid)294 AudioPolicyService::NotificationClient::NotificationClient(const sp<AudioPolicyService>& service,
295 const sp<IAudioPolicyServiceClient>& client,
296 uid_t uid,
297 pid_t pid)
298 : mService(service), mUid(uid), mPid(pid), mAudioPolicyServiceClient(client),
299 mAudioPortCallbacksEnabled(false), mAudioVolumeGroupCallbacksEnabled(false)
300 {
301 }
302
~NotificationClient()303 AudioPolicyService::NotificationClient::~NotificationClient()
304 {
305 }
306
binderDied(const wp<IBinder> & who __unused)307 void AudioPolicyService::NotificationClient::binderDied(const wp<IBinder>& who __unused)
308 {
309 sp<NotificationClient> keep(this);
310 sp<AudioPolicyService> service = mService.promote();
311 if (service != 0) {
312 service->removeNotificationClient(mUid, mPid);
313 }
314 }
315
onAudioPortListUpdate()316 void AudioPolicyService::NotificationClient::onAudioPortListUpdate()
317 {
318 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
319 mAudioPolicyServiceClient->onAudioPortListUpdate();
320 }
321 }
322
onAudioPatchListUpdate()323 void AudioPolicyService::NotificationClient::onAudioPatchListUpdate()
324 {
325 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
326 mAudioPolicyServiceClient->onAudioPatchListUpdate();
327 }
328 }
329
onAudioVolumeGroupChanged(volume_group_t group,int flags)330 void AudioPolicyService::NotificationClient::onAudioVolumeGroupChanged(volume_group_t group,
331 int flags)
332 {
333 if (mAudioPolicyServiceClient != 0 && mAudioVolumeGroupCallbacksEnabled) {
334 mAudioPolicyServiceClient->onAudioVolumeGroupChanged(group, flags);
335 }
336 }
337
338
onDynamicPolicyMixStateUpdate(const String8 & regId,int32_t state)339 void AudioPolicyService::NotificationClient::onDynamicPolicyMixStateUpdate(
340 const String8& regId, int32_t state)
341 {
342 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
343 mAudioPolicyServiceClient->onDynamicPolicyMixStateUpdate(regId, state);
344 }
345 }
346
onRecordingConfigurationUpdate(int event,const record_client_info_t * clientInfo,const audio_config_base_t * clientConfig,std::vector<effect_descriptor_t> clientEffects,const audio_config_base_t * deviceConfig,std::vector<effect_descriptor_t> effects,audio_patch_handle_t patchHandle,audio_source_t source)347 void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate(
348 int event,
349 const record_client_info_t *clientInfo,
350 const audio_config_base_t *clientConfig,
351 std::vector<effect_descriptor_t> clientEffects,
352 const audio_config_base_t *deviceConfig,
353 std::vector<effect_descriptor_t> effects,
354 audio_patch_handle_t patchHandle,
355 audio_source_t source)
356 {
357 if (mAudioPolicyServiceClient != 0 && isServiceUid(mUid)) {
358 mAudioPolicyServiceClient->onRecordingConfigurationUpdate(event, clientInfo,
359 clientConfig, clientEffects, deviceConfig, effects, patchHandle, source);
360 }
361 }
362
setAudioPortCallbacksEnabled(bool enabled)363 void AudioPolicyService::NotificationClient::setAudioPortCallbacksEnabled(bool enabled)
364 {
365 mAudioPortCallbacksEnabled = enabled;
366 }
367
setAudioVolumeGroupCallbacksEnabled(bool enabled)368 void AudioPolicyService::NotificationClient::setAudioVolumeGroupCallbacksEnabled(bool enabled)
369 {
370 mAudioVolumeGroupCallbacksEnabled = enabled;
371 }
372
binderDied(const wp<IBinder> & who)373 void AudioPolicyService::binderDied(const wp<IBinder>& who) {
374 ALOGW("binderDied() %p, calling pid %d", who.unsafe_get(),
375 IPCThreadState::self()->getCallingPid());
376 }
377
dumpTryLock(Mutex & mutex)378 static bool dumpTryLock(Mutex& mutex)
379 {
380 status_t err = mutex.timedLock(kDumpLockTimeoutNs);
381 return err == NO_ERROR;
382 }
383
dumpInternals(int fd)384 status_t AudioPolicyService::dumpInternals(int fd)
385 {
386 const size_t SIZE = 256;
387 char buffer[SIZE];
388 String8 result;
389
390 snprintf(buffer, SIZE, "AudioPolicyManager: %p\n", mAudioPolicyManager);
391 result.append(buffer);
392 snprintf(buffer, SIZE, "Command Thread: %p\n", mAudioCommandThread.get());
393 result.append(buffer);
394
395 write(fd, result.string(), result.size());
396 return NO_ERROR;
397 }
398
updateUidStates()399 void AudioPolicyService::updateUidStates()
400 {
401 Mutex::Autolock _l(mLock);
402 updateUidStates_l();
403 }
404
updateUidStates_l()405 void AudioPolicyService::updateUidStates_l()
406 {
407 // Go over all active clients and allow capture (does not force silence) in the
408 // following cases:
409 // Another client in the same UID has already been allowed to capture
410 // OR The client is the assistant
411 // AND an accessibility service is on TOP or a RTT call is active
412 // AND the source is VOICE_RECOGNITION or HOTWORD
413 // OR uses VOICE_RECOGNITION AND is on TOP
414 // OR uses HOTWORD
415 // AND there is no active privacy sensitive capture or call
416 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
417 // OR The client is an accessibility service
418 // AND Is on TOP
419 // AND the source is VOICE_RECOGNITION or HOTWORD
420 // OR The assistant is not on TOP
421 // AND there is no active privacy sensitive capture or call
422 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
423 // AND is on TOP
424 // AND the source is VOICE_RECOGNITION or HOTWORD
425 // OR the client source is virtual (remote submix, call audio TX or RX...)
426 // OR Any client
427 // AND The assistant is not on TOP
428 // AND is on TOP or latest started
429 // AND there is no active privacy sensitive capture or call
430 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
431
432 sp<AudioRecordClient> topActive;
433 sp<AudioRecordClient> latestActive;
434 sp<AudioRecordClient> latestSensitiveActive;
435
436 nsecs_t topStartNs = 0;
437 nsecs_t latestStartNs = 0;
438 nsecs_t latestSensitiveStartNs = 0;
439 bool isA11yOnTop = mUidPolicy->isA11yOnTop();
440 bool isAssistantOnTop = false;
441 bool isSensitiveActive = false;
442 bool isInCall = mPhoneState == AUDIO_MODE_IN_CALL;
443 bool rttCallActive =
444 (mPhoneState == AUDIO_MODE_IN_CALL || mPhoneState == AUDIO_MODE_IN_COMMUNICATION)
445 && mUidPolicy->isRttEnabled();
446
447 // if Sensor Privacy is enabled then all recordings should be silenced.
448 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
449 silenceAllRecordings_l();
450 return;
451 }
452
453 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
454 sp<AudioRecordClient> current = mAudioRecordClients[i];
455 if (!current->active) {
456 continue;
457 }
458
459 app_state_t appState = apmStatFromAmState(mUidPolicy->getUidState(current->uid));
460 // clients which app is in IDLE state are not eligible for top active or
461 // latest active
462 if (appState == APP_STATE_IDLE) {
463 continue;
464 }
465
466 bool isAssistant = mUidPolicy->isAssistantUid(current->uid);
467 bool isAccessibility = mUidPolicy->isA11yUid(current->uid);
468 if (appState == APP_STATE_TOP && !isAccessibility) {
469 if (current->startTimeNs > topStartNs) {
470 topActive = current;
471 topStartNs = current->startTimeNs;
472 }
473 if (isAssistant) {
474 isAssistantOnTop = true;
475 }
476 }
477 // Assistant capturing for HOTWORD or Accessibility services not considered
478 // for latest active to avoid masking regular clients started before
479 if (current->startTimeNs > latestStartNs
480 && !((current->attributes.source == AUDIO_SOURCE_HOTWORD
481 || isA11yOnTop || rttCallActive)
482 && isAssistant)
483 && !isAccessibility) {
484 latestActive = current;
485 latestStartNs = current->startTimeNs;
486 }
487 if (isPrivacySensitiveSource(current->attributes.source)) {
488 if (current->startTimeNs > latestSensitiveStartNs) {
489 latestSensitiveActive = current;
490 latestSensitiveStartNs = current->startTimeNs;
491 }
492 isSensitiveActive = true;
493 }
494 }
495
496 // if no active client with UI on Top, consider latest active as top
497 if (topActive == nullptr) {
498 topActive = latestActive;
499 }
500
501 std::vector<uid_t> enabledUids;
502
503 for (size_t i =0; i < mAudioRecordClients.size(); i++) {
504 sp<AudioRecordClient> current = mAudioRecordClients[i];
505 if (!current->active) {
506 continue;
507 }
508
509 // keep capture allowed if another client with the same UID has already
510 // been allowed to capture
511 if (std::find(enabledUids.begin(), enabledUids.end(), current->uid)
512 != enabledUids.end()) {
513 continue;
514 }
515
516 audio_source_t source = current->attributes.source;
517 bool isTopOrLatestActive = topActive == nullptr ? false : current->uid == topActive->uid;
518 bool isLatestSensitive = latestSensitiveActive == nullptr ?
519 false : current->uid == latestSensitiveActive->uid;
520
521 // By default allow capture if:
522 // The assistant is not on TOP
523 // AND is on TOP or latest started
524 // AND there is no active privacy sensitive capture or call
525 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
526 bool allowCapture = !isAssistantOnTop
527 && ((isTopOrLatestActive && !isLatestSensitive) || isLatestSensitive)
528 && !(isSensitiveActive && !(isLatestSensitive || current->canCaptureOutput))
529 && !(isInCall && !current->canCaptureOutput);
530
531 if (isVirtualSource(source)) {
532 // Allow capture for virtual (remote submix, call audio TX or RX...) sources
533 allowCapture = true;
534 } else if (mUidPolicy->isAssistantUid(current->uid)) {
535 // For assistant allow capture if:
536 // An accessibility service is on TOP or a RTT call is active
537 // AND the source is VOICE_RECOGNITION or HOTWORD
538 // OR is on TOP AND uses VOICE_RECOGNITION
539 // OR uses HOTWORD
540 // AND there is no active privacy sensitive capture or call
541 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
542 if (isA11yOnTop || rttCallActive) {
543 if (source == AUDIO_SOURCE_HOTWORD || source == AUDIO_SOURCE_VOICE_RECOGNITION) {
544 allowCapture = true;
545 }
546 } else {
547 if (((isAssistantOnTop && source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
548 source == AUDIO_SOURCE_HOTWORD) &&
549 (!(isSensitiveActive || isInCall) || current->canCaptureOutput)) {
550 allowCapture = true;
551 }
552 }
553 } else if (mUidPolicy->isA11yUid(current->uid)) {
554 // For accessibility service allow capture if:
555 // Is on TOP
556 // AND the source is VOICE_RECOGNITION or HOTWORD
557 // Or
558 // The assistant is not on TOP
559 // AND there is no active privacy sensitive capture or call
560 // OR client has CAPTURE_AUDIO_OUTPUT privileged permission
561 if (isA11yOnTop) {
562 if (source == AUDIO_SOURCE_VOICE_RECOGNITION || source == AUDIO_SOURCE_HOTWORD) {
563 allowCapture = true;
564 }
565 } else {
566 if (!isAssistantOnTop
567 && (!(isSensitiveActive || isInCall) || current->canCaptureOutput)) {
568 allowCapture = true;
569 }
570 }
571 }
572 setAppState_l(current->uid,
573 allowCapture ? apmStatFromAmState(mUidPolicy->getUidState(current->uid)) :
574 APP_STATE_IDLE);
575 if (allowCapture) {
576 enabledUids.push_back(current->uid);
577 }
578 }
579 }
580
silenceAllRecordings_l()581 void AudioPolicyService::silenceAllRecordings_l() {
582 for (size_t i = 0; i < mAudioRecordClients.size(); i++) {
583 sp<AudioRecordClient> current = mAudioRecordClients[i];
584 if (!isVirtualSource(current->attributes.source)) {
585 setAppState_l(current->uid, APP_STATE_IDLE);
586 }
587 }
588 }
589
590 /* static */
apmStatFromAmState(int amState)591 app_state_t AudioPolicyService::apmStatFromAmState(int amState) {
592
593 if (amState == ActivityManager::PROCESS_STATE_UNKNOWN) {
594 return APP_STATE_IDLE;
595 } else if (amState <= ActivityManager::PROCESS_STATE_TOP) {
596 // include persistent services
597 return APP_STATE_TOP;
598 }
599 return APP_STATE_FOREGROUND;
600 }
601
602 /* static */
isPrivacySensitiveSource(audio_source_t source)603 bool AudioPolicyService::isPrivacySensitiveSource(audio_source_t source)
604 {
605 switch (source) {
606 case AUDIO_SOURCE_CAMCORDER:
607 case AUDIO_SOURCE_VOICE_COMMUNICATION:
608 return true;
609 default:
610 break;
611 }
612 return false;
613 }
614
615 /* static */
isVirtualSource(audio_source_t source)616 bool AudioPolicyService::isVirtualSource(audio_source_t source)
617 {
618 switch (source) {
619 case AUDIO_SOURCE_VOICE_UPLINK:
620 case AUDIO_SOURCE_VOICE_DOWNLINK:
621 case AUDIO_SOURCE_VOICE_CALL:
622 case AUDIO_SOURCE_REMOTE_SUBMIX:
623 case AUDIO_SOURCE_FM_TUNER:
624 return true;
625 default:
626 break;
627 }
628 return false;
629 }
630
setAppState_l(uid_t uid,app_state_t state)631 void AudioPolicyService::setAppState_l(uid_t uid, app_state_t state)
632 {
633 AutoCallerClear acc;
634
635 if (mAudioPolicyManager) {
636 mAudioPolicyManager->setAppState(uid, state);
637 }
638 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
639 if (af) {
640 bool silenced = state == APP_STATE_IDLE;
641 af->setRecordSilenced(uid, silenced);
642 }
643 }
644
dump(int fd,const Vector<String16> & args __unused)645 status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
646 {
647 if (!dumpAllowed()) {
648 dumpPermissionDenial(fd);
649 } else {
650 bool locked = dumpTryLock(mLock);
651 if (!locked) {
652 String8 result(kDeadlockedString);
653 write(fd, result.string(), result.size());
654 }
655
656 dumpInternals(fd);
657 if (mAudioCommandThread != 0) {
658 mAudioCommandThread->dump(fd);
659 }
660
661 if (mAudioPolicyManager) {
662 mAudioPolicyManager->dump(fd);
663 }
664
665 mPackageManager.dump(fd);
666
667 if (locked) mLock.unlock();
668 }
669 return NO_ERROR;
670 }
671
dumpPermissionDenial(int fd)672 status_t AudioPolicyService::dumpPermissionDenial(int fd)
673 {
674 const size_t SIZE = 256;
675 char buffer[SIZE];
676 String8 result;
677 snprintf(buffer, SIZE, "Permission Denial: "
678 "can't dump AudioPolicyService from pid=%d, uid=%d\n",
679 IPCThreadState::self()->getCallingPid(),
680 IPCThreadState::self()->getCallingUid());
681 result.append(buffer);
682 write(fd, result.string(), result.size());
683 return NO_ERROR;
684 }
685
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)686 status_t AudioPolicyService::onTransact(
687 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
688 switch (code) {
689 case SHELL_COMMAND_TRANSACTION: {
690 int in = data.readFileDescriptor();
691 int out = data.readFileDescriptor();
692 int err = data.readFileDescriptor();
693 int argc = data.readInt32();
694 Vector<String16> args;
695 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
696 args.add(data.readString16());
697 }
698 sp<IBinder> unusedCallback;
699 sp<IResultReceiver> resultReceiver;
700 status_t status;
701 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
702 return status;
703 }
704 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
705 return status;
706 }
707 status = shellCommand(in, out, err, args);
708 if (resultReceiver != nullptr) {
709 resultReceiver->send(status);
710 }
711 return NO_ERROR;
712 }
713 }
714
715 return BnAudioPolicyService::onTransact(code, data, reply, flags);
716 }
717
718 // ------------------- Shell command implementation -------------------
719
720 // NOTE: This is a remote API - make sure all args are validated
shellCommand(int in,int out,int err,Vector<String16> & args)721 status_t AudioPolicyService::shellCommand(int in, int out, int err, Vector<String16>& args) {
722 if (!checkCallingPermission(sManageAudioPolicyPermission, nullptr, nullptr)) {
723 return PERMISSION_DENIED;
724 }
725 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
726 return BAD_VALUE;
727 }
728 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
729 return handleSetUidState(args, err);
730 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
731 return handleResetUidState(args, err);
732 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
733 return handleGetUidState(args, out, err);
734 } else if (args.size() == 1 && args[0] == String16("help")) {
735 printHelp(out);
736 return NO_ERROR;
737 }
738 printHelp(err);
739 return BAD_VALUE;
740 }
741
getUidForPackage(String16 packageName,int userId,uid_t & uid,int err)742 static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
743 if (userId < 0) {
744 ALOGE("Invalid user: %d", userId);
745 dprintf(err, "Invalid user: %d\n", userId);
746 return BAD_VALUE;
747 }
748
749 PermissionController pc;
750 uid = pc.getPackageUid(packageName, 0);
751 if (uid <= 0) {
752 ALOGE("Unknown package: '%s'", String8(packageName).string());
753 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
754 return BAD_VALUE;
755 }
756
757 uid = multiuser_get_uid(userId, uid);
758 return NO_ERROR;
759 }
760
handleSetUidState(Vector<String16> & args,int err)761 status_t AudioPolicyService::handleSetUidState(Vector<String16>& args, int err) {
762 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
763 if (!(args.size() == 3 || args.size() == 5)) {
764 printHelp(err);
765 return BAD_VALUE;
766 }
767
768 bool active = false;
769 if (args[2] == String16("active")) {
770 active = true;
771 } else if ((args[2] != String16("idle"))) {
772 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
773 return BAD_VALUE;
774 }
775
776 int userId = 0;
777 if (args.size() >= 5 && args[3] == String16("--user")) {
778 userId = atoi(String8(args[4]));
779 }
780
781 uid_t uid;
782 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
783 return BAD_VALUE;
784 }
785
786 mUidPolicy->addOverrideUid(uid, active);
787 return NO_ERROR;
788 }
789
handleResetUidState(Vector<String16> & args,int err)790 status_t AudioPolicyService::handleResetUidState(Vector<String16>& args, int err) {
791 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
792 if (!(args.size() == 2 || args.size() == 4)) {
793 printHelp(err);
794 return BAD_VALUE;
795 }
796
797 int userId = 0;
798 if (args.size() >= 4 && args[2] == String16("--user")) {
799 userId = atoi(String8(args[3]));
800 }
801
802 uid_t uid;
803 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
804 return BAD_VALUE;
805 }
806
807 mUidPolicy->removeOverrideUid(uid);
808 return NO_ERROR;
809 }
810
handleGetUidState(Vector<String16> & args,int out,int err)811 status_t AudioPolicyService::handleGetUidState(Vector<String16>& args, int out, int err) {
812 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
813 if (!(args.size() == 2 || args.size() == 4)) {
814 printHelp(err);
815 return BAD_VALUE;
816 }
817
818 int userId = 0;
819 if (args.size() >= 4 && args[2] == String16("--user")) {
820 userId = atoi(String8(args[3]));
821 }
822
823 uid_t uid;
824 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
825 return BAD_VALUE;
826 }
827
828 if (mUidPolicy->isUidActive(uid)) {
829 return dprintf(out, "active\n");
830 } else {
831 return dprintf(out, "idle\n");
832 }
833 }
834
printHelp(int out)835 status_t AudioPolicyService::printHelp(int out) {
836 return dprintf(out, "Audio policy service commands:\n"
837 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
838 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
839 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
840 " help print this message\n");
841 }
842
843 // ----------- AudioPolicyService::UidPolicy implementation ----------
844
registerSelf()845 void AudioPolicyService::UidPolicy::registerSelf() {
846 status_t res = mAm.linkToDeath(this);
847 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
848 | ActivityManager::UID_OBSERVER_IDLE
849 | ActivityManager::UID_OBSERVER_ACTIVE
850 | ActivityManager::UID_OBSERVER_PROCSTATE,
851 ActivityManager::PROCESS_STATE_UNKNOWN,
852 String16("audioserver"));
853 if (!res) {
854 Mutex::Autolock _l(mLock);
855 mObserverRegistered = true;
856 } else {
857 ALOGE("UidPolicy::registerSelf linkToDeath failed: %d", res);
858
859 mAm.unregisterUidObserver(this);
860 }
861 }
862
unregisterSelf()863 void AudioPolicyService::UidPolicy::unregisterSelf() {
864 mAm.unlinkToDeath(this);
865 mAm.unregisterUidObserver(this);
866 Mutex::Autolock _l(mLock);
867 mObserverRegistered = false;
868 }
869
binderDied(__unused const wp<IBinder> & who)870 void AudioPolicyService::UidPolicy::binderDied(__unused const wp<IBinder> &who) {
871 Mutex::Autolock _l(mLock);
872 mCachedUids.clear();
873 mObserverRegistered = false;
874 }
875
checkRegistered()876 void AudioPolicyService::UidPolicy::checkRegistered() {
877 bool needToReregister = false;
878 {
879 Mutex::Autolock _l(mLock);
880 needToReregister = !mObserverRegistered;
881 }
882 if (needToReregister) {
883 // Looks like ActivityManager has died previously, attempt to re-register.
884 registerSelf();
885 }
886 }
887
isUidActive(uid_t uid)888 bool AudioPolicyService::UidPolicy::isUidActive(uid_t uid) {
889 if (isServiceUid(uid)) return true;
890 checkRegistered();
891 {
892 Mutex::Autolock _l(mLock);
893 auto overrideIter = mOverrideUids.find(uid);
894 if (overrideIter != mOverrideUids.end()) {
895 return overrideIter->second.first;
896 }
897 // In an absense of the ActivityManager, assume everything to be active.
898 if (!mObserverRegistered) return true;
899 auto cacheIter = mCachedUids.find(uid);
900 if (cacheIter != mCachedUids.end()) {
901 return cacheIter->second.first;
902 }
903 }
904 ActivityManager am;
905 bool active = am.isUidActive(uid, String16("audioserver"));
906 {
907 Mutex::Autolock _l(mLock);
908 mCachedUids.insert(std::pair<uid_t,
909 std::pair<bool, int>>(uid, std::pair<bool, int>(active,
910 ActivityManager::PROCESS_STATE_UNKNOWN)));
911 }
912 return active;
913 }
914
getUidState(uid_t uid)915 int AudioPolicyService::UidPolicy::getUidState(uid_t uid) {
916 if (isServiceUid(uid)) {
917 return ActivityManager::PROCESS_STATE_TOP;
918 }
919 checkRegistered();
920 {
921 Mutex::Autolock _l(mLock);
922 auto overrideIter = mOverrideUids.find(uid);
923 if (overrideIter != mOverrideUids.end()) {
924 if (overrideIter->second.first) {
925 if (overrideIter->second.second != ActivityManager::PROCESS_STATE_UNKNOWN) {
926 return overrideIter->second.second;
927 } else {
928 auto cacheIter = mCachedUids.find(uid);
929 if (cacheIter != mCachedUids.end()) {
930 return cacheIter->second.second;
931 }
932 }
933 }
934 return ActivityManager::PROCESS_STATE_UNKNOWN;
935 }
936 // In an absense of the ActivityManager, assume everything to be active.
937 if (!mObserverRegistered) {
938 return ActivityManager::PROCESS_STATE_TOP;
939 }
940 auto cacheIter = mCachedUids.find(uid);
941 if (cacheIter != mCachedUids.end()) {
942 if (cacheIter->second.first) {
943 return cacheIter->second.second;
944 } else {
945 return ActivityManager::PROCESS_STATE_UNKNOWN;
946 }
947 }
948 }
949 ActivityManager am;
950 bool active = am.isUidActive(uid, String16("audioserver"));
951 int state = ActivityManager::PROCESS_STATE_UNKNOWN;
952 if (active) {
953 state = am.getUidProcessState(uid, String16("audioserver"));
954 }
955 {
956 Mutex::Autolock _l(mLock);
957 mCachedUids.insert(std::pair<uid_t,
958 std::pair<bool, int>>(uid, std::pair<bool, int>(active, state)));
959 }
960
961 return state;
962 }
963
onUidActive(uid_t uid)964 void AudioPolicyService::UidPolicy::onUidActive(uid_t uid) {
965 updateUid(&mCachedUids, uid, true, ActivityManager::PROCESS_STATE_UNKNOWN, true);
966 }
967
onUidGone(uid_t uid,__unused bool disabled)968 void AudioPolicyService::UidPolicy::onUidGone(uid_t uid, __unused bool disabled) {
969 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, false);
970 }
971
onUidIdle(uid_t uid,__unused bool disabled)972 void AudioPolicyService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
973 updateUid(&mCachedUids, uid, false, ActivityManager::PROCESS_STATE_UNKNOWN, true);
974 }
975
onUidStateChanged(uid_t uid,int32_t procState,int64_t procStateSeq __unused)976 void AudioPolicyService::UidPolicy::onUidStateChanged(uid_t uid,
977 int32_t procState,
978 int64_t procStateSeq __unused) {
979 if (procState != ActivityManager::PROCESS_STATE_UNKNOWN) {
980 updateUid(&mCachedUids, uid, true, procState, true);
981 }
982 }
983
updateOverrideUid(uid_t uid,bool active,bool insert)984 void AudioPolicyService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
985 updateUid(&mOverrideUids, uid, active, ActivityManager::PROCESS_STATE_UNKNOWN, insert);
986 }
987
notifyService()988 void AudioPolicyService::UidPolicy::notifyService() {
989 sp<AudioPolicyService> service = mService.promote();
990 if (service != nullptr) {
991 service->updateUidStates();
992 }
993 }
994
updateUid(std::unordered_map<uid_t,std::pair<bool,int>> * uids,uid_t uid,bool active,int state,bool insert)995 void AudioPolicyService::UidPolicy::updateUid(std::unordered_map<uid_t,
996 std::pair<bool, int>> *uids,
997 uid_t uid,
998 bool active,
999 int state,
1000 bool insert) {
1001 if (isServiceUid(uid)) {
1002 return;
1003 }
1004 bool wasActive = isUidActive(uid);
1005 int previousState = getUidState(uid);
1006 {
1007 Mutex::Autolock _l(mLock);
1008 updateUidLocked(uids, uid, active, state, insert);
1009 }
1010 if (wasActive != isUidActive(uid) || state != previousState) {
1011 notifyService();
1012 }
1013 }
1014
updateUidLocked(std::unordered_map<uid_t,std::pair<bool,int>> * uids,uid_t uid,bool active,int state,bool insert)1015 void AudioPolicyService::UidPolicy::updateUidLocked(std::unordered_map<uid_t,
1016 std::pair<bool, int>> *uids,
1017 uid_t uid,
1018 bool active,
1019 int state,
1020 bool insert) {
1021 auto it = uids->find(uid);
1022 if (it != uids->end()) {
1023 if (insert) {
1024 if (state == ActivityManager::PROCESS_STATE_UNKNOWN) {
1025 it->second.first = active;
1026 }
1027 if (it->second.first) {
1028 it->second.second = state;
1029 } else {
1030 it->second.second = ActivityManager::PROCESS_STATE_UNKNOWN;
1031 }
1032 } else {
1033 uids->erase(it);
1034 }
1035 } else if (insert && (state == ActivityManager::PROCESS_STATE_UNKNOWN)) {
1036 uids->insert(std::pair<uid_t, std::pair<bool, int>>(uid,
1037 std::pair<bool, int>(active, state)));
1038 }
1039 }
1040
isA11yOnTop()1041 bool AudioPolicyService::UidPolicy::isA11yOnTop() {
1042 for (const auto &uid : mCachedUids) {
1043 std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid.first);
1044 if (it == mA11yUids.end()) {
1045 continue;
1046 }
1047 if (uid.second.second >= ActivityManager::PROCESS_STATE_TOP
1048 && uid.second.second <= ActivityManager::PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
1049 return true;
1050 }
1051 }
1052 return false;
1053 }
1054
isA11yUid(uid_t uid)1055 bool AudioPolicyService::UidPolicy::isA11yUid(uid_t uid)
1056 {
1057 std::vector<uid_t>::iterator it = find(mA11yUids.begin(), mA11yUids.end(), uid);
1058 return it != mA11yUids.end();
1059 }
1060
1061 // ----------- AudioPolicyService::SensorPrivacyService implementation ----------
registerSelf()1062 void AudioPolicyService::SensorPrivacyPolicy::registerSelf() {
1063 SensorPrivacyManager spm;
1064 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1065 spm.addSensorPrivacyListener(this);
1066 }
1067
unregisterSelf()1068 void AudioPolicyService::SensorPrivacyPolicy::unregisterSelf() {
1069 SensorPrivacyManager spm;
1070 spm.removeSensorPrivacyListener(this);
1071 }
1072
isSensorPrivacyEnabled()1073 bool AudioPolicyService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1074 return mSensorPrivacyEnabled;
1075 }
1076
onSensorPrivacyChanged(bool enabled)1077 binder::Status AudioPolicyService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
1078 mSensorPrivacyEnabled = enabled;
1079 sp<AudioPolicyService> service = mService.promote();
1080 if (service != nullptr) {
1081 service->updateUidStates();
1082 }
1083 return binder::Status::ok();
1084 }
1085
1086 // ----------- AudioPolicyService::AudioCommandThread implementation ----------
1087
AudioCommandThread(String8 name,const wp<AudioPolicyService> & service)1088 AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
1089 const wp<AudioPolicyService>& service)
1090 : Thread(false), mName(name), mService(service)
1091 {
1092 }
1093
1094
~AudioCommandThread()1095 AudioPolicyService::AudioCommandThread::~AudioCommandThread()
1096 {
1097 if (!mAudioCommands.isEmpty()) {
1098 release_wake_lock(mName.string());
1099 }
1100 mAudioCommands.clear();
1101 }
1102
onFirstRef()1103 void AudioPolicyService::AudioCommandThread::onFirstRef()
1104 {
1105 run(mName.string(), ANDROID_PRIORITY_AUDIO);
1106 }
1107
threadLoop()1108 bool AudioPolicyService::AudioCommandThread::threadLoop()
1109 {
1110 nsecs_t waitTime = -1;
1111
1112 mLock.lock();
1113 while (!exitPending())
1114 {
1115 sp<AudioPolicyService> svc;
1116 while (!mAudioCommands.isEmpty() && !exitPending()) {
1117 nsecs_t curTime = systemTime();
1118 // commands are sorted by increasing time stamp: execute them from index 0 and up
1119 if (mAudioCommands[0]->mTime <= curTime) {
1120 sp<AudioCommand> command = mAudioCommands[0];
1121 mAudioCommands.removeAt(0);
1122 mLastCommand = command;
1123
1124 switch (command->mCommand) {
1125 case SET_VOLUME: {
1126 VolumeData *data = (VolumeData *)command->mParam.get();
1127 ALOGV("AudioCommandThread() processing set volume stream %d, \
1128 volume %f, output %d", data->mStream, data->mVolume, data->mIO);
1129 mLock.unlock();
1130 command->mStatus = AudioSystem::setStreamVolume(data->mStream,
1131 data->mVolume,
1132 data->mIO);
1133 mLock.lock();
1134 }break;
1135 case SET_PARAMETERS: {
1136 ParametersData *data = (ParametersData *)command->mParam.get();
1137 ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
1138 data->mKeyValuePairs.string(), data->mIO);
1139 mLock.unlock();
1140 command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
1141 mLock.lock();
1142 }break;
1143 case SET_VOICE_VOLUME: {
1144 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
1145 ALOGV("AudioCommandThread() processing set voice volume volume %f",
1146 data->mVolume);
1147 mLock.unlock();
1148 command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
1149 mLock.lock();
1150 }break;
1151 case STOP_OUTPUT: {
1152 StopOutputData *data = (StopOutputData *)command->mParam.get();
1153 ALOGV("AudioCommandThread() processing stop output portId %d",
1154 data->mPortId);
1155 svc = mService.promote();
1156 if (svc == 0) {
1157 break;
1158 }
1159 mLock.unlock();
1160 svc->doStopOutput(data->mPortId);
1161 mLock.lock();
1162 }break;
1163 case RELEASE_OUTPUT: {
1164 ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
1165 ALOGV("AudioCommandThread() processing release output portId %d",
1166 data->mPortId);
1167 svc = mService.promote();
1168 if (svc == 0) {
1169 break;
1170 }
1171 mLock.unlock();
1172 svc->doReleaseOutput(data->mPortId);
1173 mLock.lock();
1174 }break;
1175 case CREATE_AUDIO_PATCH: {
1176 CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
1177 ALOGV("AudioCommandThread() processing create audio patch");
1178 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1179 if (af == 0) {
1180 command->mStatus = PERMISSION_DENIED;
1181 } else {
1182 mLock.unlock();
1183 command->mStatus = af->createAudioPatch(&data->mPatch, &data->mHandle);
1184 mLock.lock();
1185 }
1186 } break;
1187 case RELEASE_AUDIO_PATCH: {
1188 ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
1189 ALOGV("AudioCommandThread() processing release audio patch");
1190 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1191 if (af == 0) {
1192 command->mStatus = PERMISSION_DENIED;
1193 } else {
1194 mLock.unlock();
1195 command->mStatus = af->releaseAudioPatch(data->mHandle);
1196 mLock.lock();
1197 }
1198 } break;
1199 case UPDATE_AUDIOPORT_LIST: {
1200 ALOGV("AudioCommandThread() processing update audio port list");
1201 svc = mService.promote();
1202 if (svc == 0) {
1203 break;
1204 }
1205 mLock.unlock();
1206 svc->doOnAudioPortListUpdate();
1207 mLock.lock();
1208 }break;
1209 case UPDATE_AUDIOPATCH_LIST: {
1210 ALOGV("AudioCommandThread() processing update audio patch list");
1211 svc = mService.promote();
1212 if (svc == 0) {
1213 break;
1214 }
1215 mLock.unlock();
1216 svc->doOnAudioPatchListUpdate();
1217 mLock.lock();
1218 }break;
1219 case CHANGED_AUDIOVOLUMEGROUP: {
1220 AudioVolumeGroupData *data =
1221 static_cast<AudioVolumeGroupData *>(command->mParam.get());
1222 ALOGV("AudioCommandThread() processing update audio volume group");
1223 svc = mService.promote();
1224 if (svc == 0) {
1225 break;
1226 }
1227 mLock.unlock();
1228 svc->doOnAudioVolumeGroupChanged(data->mGroup, data->mFlags);
1229 mLock.lock();
1230 }break;
1231 case SET_AUDIOPORT_CONFIG: {
1232 SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
1233 ALOGV("AudioCommandThread() processing set port config");
1234 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1235 if (af == 0) {
1236 command->mStatus = PERMISSION_DENIED;
1237 } else {
1238 mLock.unlock();
1239 command->mStatus = af->setAudioPortConfig(&data->mConfig);
1240 mLock.lock();
1241 }
1242 } break;
1243 case DYN_POLICY_MIX_STATE_UPDATE: {
1244 DynPolicyMixStateUpdateData *data =
1245 (DynPolicyMixStateUpdateData *)command->mParam.get();
1246 ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
1247 data->mRegId.string(), data->mState);
1248 svc = mService.promote();
1249 if (svc == 0) {
1250 break;
1251 }
1252 mLock.unlock();
1253 svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
1254 mLock.lock();
1255 } break;
1256 case RECORDING_CONFIGURATION_UPDATE: {
1257 RecordingConfigurationUpdateData *data =
1258 (RecordingConfigurationUpdateData *)command->mParam.get();
1259 ALOGV("AudioCommandThread() processing recording configuration update");
1260 svc = mService.promote();
1261 if (svc == 0) {
1262 break;
1263 }
1264 mLock.unlock();
1265 svc->doOnRecordingConfigurationUpdate(data->mEvent, &data->mClientInfo,
1266 &data->mClientConfig, data->mClientEffects,
1267 &data->mDeviceConfig, data->mEffects,
1268 data->mPatchHandle, data->mSource);
1269 mLock.lock();
1270 } break;
1271 case SET_EFFECT_SUSPENDED: {
1272 SetEffectSuspendedData *data = (SetEffectSuspendedData *)command->mParam.get();
1273 ALOGV("AudioCommandThread() processing set effect suspended");
1274 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1275 if (af != 0) {
1276 mLock.unlock();
1277 af->setEffectSuspended(data->mEffectId, data->mSessionId, data->mSuspended);
1278 mLock.lock();
1279 }
1280 } break;
1281 case AUDIO_MODULES_UPDATE: {
1282 ALOGV("AudioCommandThread() processing audio modules update");
1283 svc = mService.promote();
1284 if (svc == 0) {
1285 break;
1286 }
1287 mLock.unlock();
1288 svc->doOnNewAudioModulesAvailable();
1289 mLock.lock();
1290 } break;
1291
1292 default:
1293 ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
1294 }
1295 {
1296 Mutex::Autolock _l(command->mLock);
1297 if (command->mWaitStatus) {
1298 command->mWaitStatus = false;
1299 command->mCond.signal();
1300 }
1301 }
1302 waitTime = -1;
1303 // release mLock before releasing strong reference on the service as
1304 // AudioPolicyService destructor calls AudioCommandThread::exit() which
1305 // acquires mLock.
1306 mLock.unlock();
1307 svc.clear();
1308 mLock.lock();
1309 } else {
1310 waitTime = mAudioCommands[0]->mTime - curTime;
1311 break;
1312 }
1313 }
1314
1315 // release delayed commands wake lock if the queue is empty
1316 if (mAudioCommands.isEmpty()) {
1317 release_wake_lock(mName.string());
1318 }
1319
1320 // At this stage we have either an empty command queue or the first command in the queue
1321 // has a finite delay. So unless we are exiting it is safe to wait.
1322 if (!exitPending()) {
1323 ALOGV("AudioCommandThread() going to sleep");
1324 if (waitTime == -1) {
1325 mWaitWorkCV.wait(mLock);
1326 } else {
1327 mWaitWorkCV.waitRelative(mLock, waitTime);
1328 }
1329 }
1330 }
1331 // release delayed commands wake lock before quitting
1332 if (!mAudioCommands.isEmpty()) {
1333 release_wake_lock(mName.string());
1334 }
1335 mLock.unlock();
1336 return false;
1337 }
1338
dump(int fd)1339 status_t AudioPolicyService::AudioCommandThread::dump(int fd)
1340 {
1341 const size_t SIZE = 256;
1342 char buffer[SIZE];
1343 String8 result;
1344
1345 snprintf(buffer, SIZE, "AudioCommandThread %p Dump\n", this);
1346 result.append(buffer);
1347 write(fd, result.string(), result.size());
1348
1349 bool locked = dumpTryLock(mLock);
1350 if (!locked) {
1351 String8 result2(kCmdDeadlockedString);
1352 write(fd, result2.string(), result2.size());
1353 }
1354
1355 snprintf(buffer, SIZE, "- Commands:\n");
1356 result = String8(buffer);
1357 result.append(" Command Time Wait pParam\n");
1358 for (size_t i = 0; i < mAudioCommands.size(); i++) {
1359 mAudioCommands[i]->dump(buffer, SIZE);
1360 result.append(buffer);
1361 }
1362 result.append(" Last Command\n");
1363 if (mLastCommand != 0) {
1364 mLastCommand->dump(buffer, SIZE);
1365 result.append(buffer);
1366 } else {
1367 result.append(" none\n");
1368 }
1369
1370 write(fd, result.string(), result.size());
1371
1372 if (locked) mLock.unlock();
1373
1374 return NO_ERROR;
1375 }
1376
volumeCommand(audio_stream_type_t stream,float volume,audio_io_handle_t output,int delayMs)1377 status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
1378 float volume,
1379 audio_io_handle_t output,
1380 int delayMs)
1381 {
1382 sp<AudioCommand> command = new AudioCommand();
1383 command->mCommand = SET_VOLUME;
1384 sp<VolumeData> data = new VolumeData();
1385 data->mStream = stream;
1386 data->mVolume = volume;
1387 data->mIO = output;
1388 command->mParam = data;
1389 command->mWaitStatus = true;
1390 ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
1391 stream, volume, output);
1392 return sendCommand(command, delayMs);
1393 }
1394
parametersCommand(audio_io_handle_t ioHandle,const char * keyValuePairs,int delayMs)1395 status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
1396 const char *keyValuePairs,
1397 int delayMs)
1398 {
1399 sp<AudioCommand> command = new AudioCommand();
1400 command->mCommand = SET_PARAMETERS;
1401 sp<ParametersData> data = new ParametersData();
1402 data->mIO = ioHandle;
1403 data->mKeyValuePairs = String8(keyValuePairs);
1404 command->mParam = data;
1405 command->mWaitStatus = true;
1406 ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
1407 keyValuePairs, ioHandle, delayMs);
1408 return sendCommand(command, delayMs);
1409 }
1410
voiceVolumeCommand(float volume,int delayMs)1411 status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
1412 {
1413 sp<AudioCommand> command = new AudioCommand();
1414 command->mCommand = SET_VOICE_VOLUME;
1415 sp<VoiceVolumeData> data = new VoiceVolumeData();
1416 data->mVolume = volume;
1417 command->mParam = data;
1418 command->mWaitStatus = true;
1419 ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
1420 return sendCommand(command, delayMs);
1421 }
1422
setEffectSuspendedCommand(int effectId,audio_session_t sessionId,bool suspended)1423 void AudioPolicyService::AudioCommandThread::setEffectSuspendedCommand(int effectId,
1424 audio_session_t sessionId,
1425 bool suspended)
1426 {
1427 sp<AudioCommand> command = new AudioCommand();
1428 command->mCommand = SET_EFFECT_SUSPENDED;
1429 sp<SetEffectSuspendedData> data = new SetEffectSuspendedData();
1430 data->mEffectId = effectId;
1431 data->mSessionId = sessionId;
1432 data->mSuspended = suspended;
1433 command->mParam = data;
1434 ALOGV("AudioCommandThread() adding set suspended effectId %d sessionId %d suspended %d",
1435 effectId, sessionId, suspended);
1436 sendCommand(command);
1437 }
1438
1439
stopOutputCommand(audio_port_handle_t portId)1440 void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_port_handle_t portId)
1441 {
1442 sp<AudioCommand> command = new AudioCommand();
1443 command->mCommand = STOP_OUTPUT;
1444 sp<StopOutputData> data = new StopOutputData();
1445 data->mPortId = portId;
1446 command->mParam = data;
1447 ALOGV("AudioCommandThread() adding stop output portId %d", portId);
1448 sendCommand(command);
1449 }
1450
releaseOutputCommand(audio_port_handle_t portId)1451 void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_port_handle_t portId)
1452 {
1453 sp<AudioCommand> command = new AudioCommand();
1454 command->mCommand = RELEASE_OUTPUT;
1455 sp<ReleaseOutputData> data = new ReleaseOutputData();
1456 data->mPortId = portId;
1457 command->mParam = data;
1458 ALOGV("AudioCommandThread() adding release output portId %d", portId);
1459 sendCommand(command);
1460 }
1461
createAudioPatchCommand(const struct audio_patch * patch,audio_patch_handle_t * handle,int delayMs)1462 status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
1463 const struct audio_patch *patch,
1464 audio_patch_handle_t *handle,
1465 int delayMs)
1466 {
1467 status_t status = NO_ERROR;
1468
1469 sp<AudioCommand> command = new AudioCommand();
1470 command->mCommand = CREATE_AUDIO_PATCH;
1471 CreateAudioPatchData *data = new CreateAudioPatchData();
1472 data->mPatch = *patch;
1473 data->mHandle = *handle;
1474 command->mParam = data;
1475 command->mWaitStatus = true;
1476 ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
1477 status = sendCommand(command, delayMs);
1478 if (status == NO_ERROR) {
1479 *handle = data->mHandle;
1480 }
1481 return status;
1482 }
1483
releaseAudioPatchCommand(audio_patch_handle_t handle,int delayMs)1484 status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
1485 int delayMs)
1486 {
1487 sp<AudioCommand> command = new AudioCommand();
1488 command->mCommand = RELEASE_AUDIO_PATCH;
1489 ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
1490 data->mHandle = handle;
1491 command->mParam = data;
1492 command->mWaitStatus = true;
1493 ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
1494 return sendCommand(command, delayMs);
1495 }
1496
updateAudioPortListCommand()1497 void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
1498 {
1499 sp<AudioCommand> command = new AudioCommand();
1500 command->mCommand = UPDATE_AUDIOPORT_LIST;
1501 ALOGV("AudioCommandThread() adding update audio port list");
1502 sendCommand(command);
1503 }
1504
updateAudioPatchListCommand()1505 void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
1506 {
1507 sp<AudioCommand>command = new AudioCommand();
1508 command->mCommand = UPDATE_AUDIOPATCH_LIST;
1509 ALOGV("AudioCommandThread() adding update audio patch list");
1510 sendCommand(command);
1511 }
1512
changeAudioVolumeGroupCommand(volume_group_t group,int flags)1513 void AudioPolicyService::AudioCommandThread::changeAudioVolumeGroupCommand(volume_group_t group,
1514 int flags)
1515 {
1516 sp<AudioCommand>command = new AudioCommand();
1517 command->mCommand = CHANGED_AUDIOVOLUMEGROUP;
1518 AudioVolumeGroupData *data= new AudioVolumeGroupData();
1519 data->mGroup = group;
1520 data->mFlags = flags;
1521 command->mParam = data;
1522 ALOGV("AudioCommandThread() adding audio volume group changed");
1523 sendCommand(command);
1524 }
1525
setAudioPortConfigCommand(const struct audio_port_config * config,int delayMs)1526 status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
1527 const struct audio_port_config *config, int delayMs)
1528 {
1529 sp<AudioCommand> command = new AudioCommand();
1530 command->mCommand = SET_AUDIOPORT_CONFIG;
1531 SetAudioPortConfigData *data = new SetAudioPortConfigData();
1532 data->mConfig = *config;
1533 command->mParam = data;
1534 command->mWaitStatus = true;
1535 ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
1536 return sendCommand(command, delayMs);
1537 }
1538
dynamicPolicyMixStateUpdateCommand(const String8 & regId,int32_t state)1539 void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
1540 const String8& regId, int32_t state)
1541 {
1542 sp<AudioCommand> command = new AudioCommand();
1543 command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
1544 DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
1545 data->mRegId = regId;
1546 data->mState = state;
1547 command->mParam = data;
1548 ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
1549 regId.string(), state);
1550 sendCommand(command);
1551 }
1552
recordingConfigurationUpdateCommand(int event,const record_client_info_t * clientInfo,const audio_config_base_t * clientConfig,std::vector<effect_descriptor_t> clientEffects,const audio_config_base_t * deviceConfig,std::vector<effect_descriptor_t> effects,audio_patch_handle_t patchHandle,audio_source_t source)1553 void AudioPolicyService::AudioCommandThread::recordingConfigurationUpdateCommand(
1554 int event,
1555 const record_client_info_t *clientInfo,
1556 const audio_config_base_t *clientConfig,
1557 std::vector<effect_descriptor_t> clientEffects,
1558 const audio_config_base_t *deviceConfig,
1559 std::vector<effect_descriptor_t> effects,
1560 audio_patch_handle_t patchHandle,
1561 audio_source_t source)
1562 {
1563 sp<AudioCommand>command = new AudioCommand();
1564 command->mCommand = RECORDING_CONFIGURATION_UPDATE;
1565 RecordingConfigurationUpdateData *data = new RecordingConfigurationUpdateData();
1566 data->mEvent = event;
1567 data->mClientInfo = *clientInfo;
1568 data->mClientConfig = *clientConfig;
1569 data->mClientEffects = clientEffects;
1570 data->mDeviceConfig = *deviceConfig;
1571 data->mEffects = effects;
1572 data->mPatchHandle = patchHandle;
1573 data->mSource = source;
1574 command->mParam = data;
1575 ALOGV("AudioCommandThread() adding recording configuration update event %d, source %d uid %u",
1576 event, clientInfo->source, clientInfo->uid);
1577 sendCommand(command);
1578 }
1579
audioModulesUpdateCommand()1580 void AudioPolicyService::AudioCommandThread::audioModulesUpdateCommand()
1581 {
1582 sp<AudioCommand> command = new AudioCommand();
1583 command->mCommand = AUDIO_MODULES_UPDATE;
1584 sendCommand(command);
1585 }
1586
sendCommand(sp<AudioCommand> & command,int delayMs)1587 status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
1588 {
1589 {
1590 Mutex::Autolock _l(mLock);
1591 insertCommand_l(command, delayMs);
1592 mWaitWorkCV.signal();
1593 }
1594 Mutex::Autolock _l(command->mLock);
1595 while (command->mWaitStatus) {
1596 nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
1597 if (command->mCond.waitRelative(command->mLock, timeOutNs) != NO_ERROR) {
1598 command->mStatus = TIMED_OUT;
1599 command->mWaitStatus = false;
1600 }
1601 }
1602 return command->mStatus;
1603 }
1604
1605 // insertCommand_l() must be called with mLock held
insertCommand_l(sp<AudioCommand> & command,int delayMs)1606 void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
1607 {
1608 ssize_t i; // not size_t because i will count down to -1
1609 Vector < sp<AudioCommand> > removedCommands;
1610 command->mTime = systemTime() + milliseconds(delayMs);
1611
1612 // acquire wake lock to make sure delayed commands are processed
1613 if (mAudioCommands.isEmpty()) {
1614 acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.string());
1615 }
1616
1617 // check same pending commands with later time stamps and eliminate them
1618 for (i = (ssize_t)mAudioCommands.size()-1; i >= 0; i--) {
1619 sp<AudioCommand> command2 = mAudioCommands[i];
1620 // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
1621 if (command2->mTime <= command->mTime) break;
1622
1623 // create audio patch or release audio patch commands are equivalent
1624 // with regard to filtering
1625 if ((command->mCommand == CREATE_AUDIO_PATCH) ||
1626 (command->mCommand == RELEASE_AUDIO_PATCH)) {
1627 if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
1628 (command2->mCommand != RELEASE_AUDIO_PATCH)) {
1629 continue;
1630 }
1631 } else if (command2->mCommand != command->mCommand) continue;
1632
1633 switch (command->mCommand) {
1634 case SET_PARAMETERS: {
1635 ParametersData *data = (ParametersData *)command->mParam.get();
1636 ParametersData *data2 = (ParametersData *)command2->mParam.get();
1637 if (data->mIO != data2->mIO) break;
1638 ALOGV("Comparing parameter command %s to new command %s",
1639 data2->mKeyValuePairs.string(), data->mKeyValuePairs.string());
1640 AudioParameter param = AudioParameter(data->mKeyValuePairs);
1641 AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
1642 for (size_t j = 0; j < param.size(); j++) {
1643 String8 key;
1644 String8 value;
1645 param.getAt(j, key, value);
1646 for (size_t k = 0; k < param2.size(); k++) {
1647 String8 key2;
1648 String8 value2;
1649 param2.getAt(k, key2, value2);
1650 if (key2 == key) {
1651 param2.remove(key2);
1652 ALOGV("Filtering out parameter %s", key2.string());
1653 break;
1654 }
1655 }
1656 }
1657 // if all keys have been filtered out, remove the command.
1658 // otherwise, update the key value pairs
1659 if (param2.size() == 0) {
1660 removedCommands.add(command2);
1661 } else {
1662 data2->mKeyValuePairs = param2.toString();
1663 }
1664 command->mTime = command2->mTime;
1665 // force delayMs to non 0 so that code below does not request to wait for
1666 // command status as the command is now delayed
1667 delayMs = 1;
1668 } break;
1669
1670 case SET_VOLUME: {
1671 VolumeData *data = (VolumeData *)command->mParam.get();
1672 VolumeData *data2 = (VolumeData *)command2->mParam.get();
1673 if (data->mIO != data2->mIO) break;
1674 if (data->mStream != data2->mStream) break;
1675 ALOGV("Filtering out volume command on output %d for stream %d",
1676 data->mIO, data->mStream);
1677 removedCommands.add(command2);
1678 command->mTime = command2->mTime;
1679 // force delayMs to non 0 so that code below does not request to wait for
1680 // command status as the command is now delayed
1681 delayMs = 1;
1682 } break;
1683
1684 case SET_VOICE_VOLUME: {
1685 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
1686 VoiceVolumeData *data2 = (VoiceVolumeData *)command2->mParam.get();
1687 ALOGV("Filtering out voice volume command value %f replaced by %f",
1688 data2->mVolume, data->mVolume);
1689 removedCommands.add(command2);
1690 command->mTime = command2->mTime;
1691 // force delayMs to non 0 so that code below does not request to wait for
1692 // command status as the command is now delayed
1693 delayMs = 1;
1694 } break;
1695
1696 case CREATE_AUDIO_PATCH:
1697 case RELEASE_AUDIO_PATCH: {
1698 audio_patch_handle_t handle;
1699 struct audio_patch patch;
1700 if (command->mCommand == CREATE_AUDIO_PATCH) {
1701 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
1702 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
1703 } else {
1704 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
1705 memset(&patch, 0, sizeof(patch));
1706 }
1707 audio_patch_handle_t handle2;
1708 struct audio_patch patch2;
1709 if (command2->mCommand == CREATE_AUDIO_PATCH) {
1710 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
1711 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
1712 } else {
1713 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
1714 memset(&patch2, 0, sizeof(patch2));
1715 }
1716 if (handle != handle2) break;
1717 /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
1718 same output. */
1719 if( (command->mCommand == CREATE_AUDIO_PATCH) &&
1720 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
1721 bool isOutputDiff = false;
1722 if (patch.num_sources == patch2.num_sources) {
1723 for (unsigned count = 0; count < patch.num_sources; count++) {
1724 if (patch.sources[count].id != patch2.sources[count].id) {
1725 isOutputDiff = true;
1726 break;
1727 }
1728 }
1729 if (isOutputDiff)
1730 break;
1731 }
1732 }
1733 ALOGV("Filtering out %s audio patch command for handle %d",
1734 (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
1735 removedCommands.add(command2);
1736 command->mTime = command2->mTime;
1737 // force delayMs to non 0 so that code below does not request to wait for
1738 // command status as the command is now delayed
1739 delayMs = 1;
1740 } break;
1741
1742 case DYN_POLICY_MIX_STATE_UPDATE: {
1743
1744 } break;
1745
1746 case RECORDING_CONFIGURATION_UPDATE: {
1747
1748 } break;
1749
1750 default:
1751 break;
1752 }
1753 }
1754
1755 // remove filtered commands
1756 for (size_t j = 0; j < removedCommands.size(); j++) {
1757 // removed commands always have time stamps greater than current command
1758 for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
1759 if (mAudioCommands[k].get() == removedCommands[j].get()) {
1760 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
1761 mAudioCommands.removeAt(k);
1762 break;
1763 }
1764 }
1765 }
1766 removedCommands.clear();
1767
1768 // Disable wait for status if delay is not 0.
1769 // Except for create audio patch command because the returned patch handle
1770 // is needed by audio policy manager
1771 if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
1772 command->mWaitStatus = false;
1773 }
1774
1775 // insert command at the right place according to its time stamp
1776 ALOGV("inserting command: %d at index %zd, num commands %zu",
1777 command->mCommand, i+1, mAudioCommands.size());
1778 mAudioCommands.insertAt(command, i + 1);
1779 }
1780
exit()1781 void AudioPolicyService::AudioCommandThread::exit()
1782 {
1783 ALOGV("AudioCommandThread::exit");
1784 {
1785 AutoMutex _l(mLock);
1786 requestExit();
1787 mWaitWorkCV.signal();
1788 }
1789 // Note that we can call it from the thread loop if all other references have been released
1790 // but it will safely return WOULD_BLOCK in this case
1791 requestExitAndWait();
1792 }
1793
dump(char * buffer,size_t size)1794 void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
1795 {
1796 snprintf(buffer, size, " %02d %06d.%03d %01u %p\n",
1797 mCommand,
1798 (int)ns2s(mTime),
1799 (int)ns2ms(mTime)%1000,
1800 mWaitStatus,
1801 mParam.get());
1802 }
1803
1804 /******* helpers for the service_ops callbacks defined below *********/
setParameters(audio_io_handle_t ioHandle,const char * keyValuePairs,int delayMs)1805 void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
1806 const char *keyValuePairs,
1807 int delayMs)
1808 {
1809 mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
1810 delayMs);
1811 }
1812
setStreamVolume(audio_stream_type_t stream,float volume,audio_io_handle_t output,int delayMs)1813 int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
1814 float volume,
1815 audio_io_handle_t output,
1816 int delayMs)
1817 {
1818 return (int)mAudioCommandThread->volumeCommand(stream, volume,
1819 output, delayMs);
1820 }
1821
setVoiceVolume(float volume,int delayMs)1822 int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
1823 {
1824 return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
1825 }
1826
setEffectSuspended(int effectId,audio_session_t sessionId,bool suspended)1827 void AudioPolicyService::setEffectSuspended(int effectId,
1828 audio_session_t sessionId,
1829 bool suspended)
1830 {
1831 mAudioCommandThread->setEffectSuspendedCommand(effectId, sessionId, suspended);
1832 }
1833
onNewAudioModulesAvailable()1834 void AudioPolicyService::onNewAudioModulesAvailable()
1835 {
1836 mOutputCommandThread->audioModulesUpdateCommand();
1837 }
1838
1839
1840 extern "C" {
1841 audio_module_handle_t aps_load_hw_module(void *service __unused,
1842 const char *name);
1843 audio_io_handle_t aps_open_output(void *service __unused,
1844 audio_devices_t *pDevices,
1845 uint32_t *pSamplingRate,
1846 audio_format_t *pFormat,
1847 audio_channel_mask_t *pChannelMask,
1848 uint32_t *pLatencyMs,
1849 audio_output_flags_t flags);
1850
1851 audio_io_handle_t aps_open_output_on_module(void *service __unused,
1852 audio_module_handle_t module,
1853 audio_devices_t *pDevices,
1854 uint32_t *pSamplingRate,
1855 audio_format_t *pFormat,
1856 audio_channel_mask_t *pChannelMask,
1857 uint32_t *pLatencyMs,
1858 audio_output_flags_t flags,
1859 const audio_offload_info_t *offloadInfo);
1860 audio_io_handle_t aps_open_dup_output(void *service __unused,
1861 audio_io_handle_t output1,
1862 audio_io_handle_t output2);
1863 int aps_close_output(void *service __unused, audio_io_handle_t output);
1864 int aps_suspend_output(void *service __unused, audio_io_handle_t output);
1865 int aps_restore_output(void *service __unused, audio_io_handle_t output);
1866 audio_io_handle_t aps_open_input(void *service __unused,
1867 audio_devices_t *pDevices,
1868 uint32_t *pSamplingRate,
1869 audio_format_t *pFormat,
1870 audio_channel_mask_t *pChannelMask,
1871 audio_in_acoustics_t acoustics __unused);
1872 audio_io_handle_t aps_open_input_on_module(void *service __unused,
1873 audio_module_handle_t module,
1874 audio_devices_t *pDevices,
1875 uint32_t *pSamplingRate,
1876 audio_format_t *pFormat,
1877 audio_channel_mask_t *pChannelMask);
1878 int aps_close_input(void *service __unused, audio_io_handle_t input);
1879 int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
1880 int aps_move_effects(void *service __unused, audio_session_t session,
1881 audio_io_handle_t src_output,
1882 audio_io_handle_t dst_output);
1883 char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
1884 const char *keys);
1885 void aps_set_parameters(void *service, audio_io_handle_t io_handle,
1886 const char *kv_pairs, int delay_ms);
1887 int aps_set_stream_volume(void *service, audio_stream_type_t stream,
1888 float volume, audio_io_handle_t output,
1889 int delay_ms);
1890 int aps_set_voice_volume(void *service, float volume, int delay_ms);
1891 };
1892
1893 } // namespace android
1894