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
26 #include <sys/time.h>
27 #include <binder/IServiceManager.h>
28 #include <utils/Log.h>
29 #include <cutils/properties.h>
30 #include <binder/IPCThreadState.h>
31 #include <utils/String16.h>
32 #include <utils/threads.h>
33 #include "AudioPolicyService.h"
34 #include "ServiceUtilities.h"
35 #include <hardware_legacy/power.h>
36 #include <media/AudioEffect.h>
37 #include <media/EffectsFactoryApi.h>
38 #include <media/AudioParameter.h>
39
40 #include <hardware/hardware.h>
41 #include <system/audio.h>
42 #include <system/audio_policy.h>
43 #include <hardware/audio_policy.h>
44
45 namespace android {
46
47 static const char kDeadlockedString[] = "AudioPolicyService may be deadlocked\n";
48 static const char kCmdDeadlockedString[] = "AudioPolicyService command thread may be deadlocked\n";
49
50 static const int kDumpLockRetries = 50;
51 static const int kDumpLockSleepUs = 20000;
52
53 static const nsecs_t kAudioCommandTimeoutNs = seconds(3); // 3 seconds
54
55 namespace {
56 extern struct audio_policy_service_ops aps_ops;
57 };
58
59 // ----------------------------------------------------------------------------
60
AudioPolicyService()61 AudioPolicyService::AudioPolicyService()
62 : BnAudioPolicyService(), mpAudioPolicyDev(NULL), mpAudioPolicy(NULL),
63 mAudioPolicyManager(NULL), mAudioPolicyClient(NULL), mPhoneState(AUDIO_MODE_INVALID)
64 {
65 }
66
onFirstRef()67 void AudioPolicyService::onFirstRef()
68 {
69 char value[PROPERTY_VALUE_MAX];
70 const struct hw_module_t *module;
71 int forced_val;
72 int rc;
73
74 {
75 Mutex::Autolock _l(mLock);
76
77 // start tone playback thread
78 mTonePlaybackThread = new AudioCommandThread(String8("ApmTone"), this);
79 // start audio commands thread
80 mAudioCommandThread = new AudioCommandThread(String8("ApmAudio"), this);
81 // start output activity command thread
82 mOutputCommandThread = new AudioCommandThread(String8("ApmOutput"), this);
83
84 #ifdef USE_LEGACY_AUDIO_POLICY
85 ALOGI("AudioPolicyService CSTOR in legacy mode");
86
87 /* instantiate the audio policy manager */
88 rc = hw_get_module(AUDIO_POLICY_HARDWARE_MODULE_ID, &module);
89 if (rc) {
90 return;
91 }
92 rc = audio_policy_dev_open(module, &mpAudioPolicyDev);
93 ALOGE_IF(rc, "couldn't open audio policy device (%s)", strerror(-rc));
94 if (rc) {
95 return;
96 }
97
98 rc = mpAudioPolicyDev->create_audio_policy(mpAudioPolicyDev, &aps_ops, this,
99 &mpAudioPolicy);
100 ALOGE_IF(rc, "couldn't create audio policy (%s)", strerror(-rc));
101 if (rc) {
102 return;
103 }
104
105 rc = mpAudioPolicy->init_check(mpAudioPolicy);
106 ALOGE_IF(rc, "couldn't init_check the audio policy (%s)", strerror(-rc));
107 if (rc) {
108 return;
109 }
110 ALOGI("Loaded audio policy from %s (%s)", module->name, module->id);
111 #else
112 ALOGI("AudioPolicyService CSTOR in new mode");
113
114 mAudioPolicyClient = new AudioPolicyClient(this);
115 mAudioPolicyManager = createAudioPolicyManager(mAudioPolicyClient);
116 #endif
117 }
118 // load audio processing modules
119 sp<AudioPolicyEffects>audioPolicyEffects = new AudioPolicyEffects();
120 {
121 Mutex::Autolock _l(mLock);
122 mAudioPolicyEffects = audioPolicyEffects;
123 }
124 }
125
~AudioPolicyService()126 AudioPolicyService::~AudioPolicyService()
127 {
128 mTonePlaybackThread->exit();
129 mAudioCommandThread->exit();
130 mOutputCommandThread->exit();
131
132 #ifdef USE_LEGACY_AUDIO_POLICY
133 if (mpAudioPolicy != NULL && mpAudioPolicyDev != NULL) {
134 mpAudioPolicyDev->destroy_audio_policy(mpAudioPolicyDev, mpAudioPolicy);
135 }
136 if (mpAudioPolicyDev != NULL) {
137 audio_policy_dev_close(mpAudioPolicyDev);
138 }
139 #else
140 destroyAudioPolicyManager(mAudioPolicyManager);
141 delete mAudioPolicyClient;
142 #endif
143
144 mNotificationClients.clear();
145 mAudioPolicyEffects.clear();
146 }
147
148 // A notification client is always registered by AudioSystem when the client process
149 // connects to AudioPolicyService.
registerClient(const sp<IAudioPolicyServiceClient> & client)150 void AudioPolicyService::registerClient(const sp<IAudioPolicyServiceClient>& client)
151 {
152
153 Mutex::Autolock _l(mNotificationClientsLock);
154
155 uid_t uid = IPCThreadState::self()->getCallingUid();
156 if (mNotificationClients.indexOfKey(uid) < 0) {
157 sp<NotificationClient> notificationClient = new NotificationClient(this,
158 client,
159 uid);
160 ALOGV("registerClient() client %p, uid %d", client.get(), uid);
161
162 mNotificationClients.add(uid, notificationClient);
163
164 sp<IBinder> binder = IInterface::asBinder(client);
165 binder->linkToDeath(notificationClient);
166 }
167 }
168
setAudioPortCallbacksEnabled(bool enabled)169 void AudioPolicyService::setAudioPortCallbacksEnabled(bool enabled)
170 {
171 Mutex::Autolock _l(mNotificationClientsLock);
172
173 uid_t uid = IPCThreadState::self()->getCallingUid();
174 if (mNotificationClients.indexOfKey(uid) < 0) {
175 return;
176 }
177 mNotificationClients.valueFor(uid)->setAudioPortCallbacksEnabled(enabled);
178 }
179
180 // removeNotificationClient() is called when the client process dies.
removeNotificationClient(uid_t uid)181 void AudioPolicyService::removeNotificationClient(uid_t uid)
182 {
183 {
184 Mutex::Autolock _l(mNotificationClientsLock);
185 mNotificationClients.removeItem(uid);
186 }
187 #ifndef USE_LEGACY_AUDIO_POLICY
188 {
189 Mutex::Autolock _l(mLock);
190 if (mAudioPolicyManager) {
191 mAudioPolicyManager->releaseResourcesForUid(uid);
192 }
193 }
194 #endif
195 }
196
onAudioPortListUpdate()197 void AudioPolicyService::onAudioPortListUpdate()
198 {
199 mOutputCommandThread->updateAudioPortListCommand();
200 }
201
doOnAudioPortListUpdate()202 void AudioPolicyService::doOnAudioPortListUpdate()
203 {
204 Mutex::Autolock _l(mNotificationClientsLock);
205 for (size_t i = 0; i < mNotificationClients.size(); i++) {
206 mNotificationClients.valueAt(i)->onAudioPortListUpdate();
207 }
208 }
209
onAudioPatchListUpdate()210 void AudioPolicyService::onAudioPatchListUpdate()
211 {
212 mOutputCommandThread->updateAudioPatchListCommand();
213 }
214
clientCreateAudioPatch(const struct audio_patch * patch,audio_patch_handle_t * handle,int delayMs)215 status_t AudioPolicyService::clientCreateAudioPatch(const struct audio_patch *patch,
216 audio_patch_handle_t *handle,
217 int delayMs)
218 {
219 return mAudioCommandThread->createAudioPatchCommand(patch, handle, delayMs);
220 }
221
clientReleaseAudioPatch(audio_patch_handle_t handle,int delayMs)222 status_t AudioPolicyService::clientReleaseAudioPatch(audio_patch_handle_t handle,
223 int delayMs)
224 {
225 return mAudioCommandThread->releaseAudioPatchCommand(handle, delayMs);
226 }
227
doOnAudioPatchListUpdate()228 void AudioPolicyService::doOnAudioPatchListUpdate()
229 {
230 Mutex::Autolock _l(mNotificationClientsLock);
231 for (size_t i = 0; i < mNotificationClients.size(); i++) {
232 mNotificationClients.valueAt(i)->onAudioPatchListUpdate();
233 }
234 }
235
onDynamicPolicyMixStateUpdate(String8 regId,int32_t state)236 void AudioPolicyService::onDynamicPolicyMixStateUpdate(String8 regId, int32_t state)
237 {
238 ALOGV("AudioPolicyService::onDynamicPolicyMixStateUpdate(%s, %d)",
239 regId.string(), state);
240 mOutputCommandThread->dynamicPolicyMixStateUpdateCommand(regId, state);
241 }
242
doOnDynamicPolicyMixStateUpdate(String8 regId,int32_t state)243 void AudioPolicyService::doOnDynamicPolicyMixStateUpdate(String8 regId, int32_t state)
244 {
245 Mutex::Autolock _l(mNotificationClientsLock);
246 for (size_t i = 0; i < mNotificationClients.size(); i++) {
247 mNotificationClients.valueAt(i)->onDynamicPolicyMixStateUpdate(regId, state);
248 }
249 }
250
clientSetAudioPortConfig(const struct audio_port_config * config,int delayMs)251 status_t AudioPolicyService::clientSetAudioPortConfig(const struct audio_port_config *config,
252 int delayMs)
253 {
254 return mAudioCommandThread->setAudioPortConfigCommand(config, delayMs);
255 }
256
NotificationClient(const sp<AudioPolicyService> & service,const sp<IAudioPolicyServiceClient> & client,uid_t uid)257 AudioPolicyService::NotificationClient::NotificationClient(const sp<AudioPolicyService>& service,
258 const sp<IAudioPolicyServiceClient>& client,
259 uid_t uid)
260 : mService(service), mUid(uid), mAudioPolicyServiceClient(client),
261 mAudioPortCallbacksEnabled(false)
262 {
263 }
264
~NotificationClient()265 AudioPolicyService::NotificationClient::~NotificationClient()
266 {
267 }
268
binderDied(const wp<IBinder> & who __unused)269 void AudioPolicyService::NotificationClient::binderDied(const wp<IBinder>& who __unused)
270 {
271 sp<NotificationClient> keep(this);
272 sp<AudioPolicyService> service = mService.promote();
273 if (service != 0) {
274 service->removeNotificationClient(mUid);
275 }
276 }
277
onAudioPortListUpdate()278 void AudioPolicyService::NotificationClient::onAudioPortListUpdate()
279 {
280 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
281 mAudioPolicyServiceClient->onAudioPortListUpdate();
282 }
283 }
284
onAudioPatchListUpdate()285 void AudioPolicyService::NotificationClient::onAudioPatchListUpdate()
286 {
287 if (mAudioPolicyServiceClient != 0 && mAudioPortCallbacksEnabled) {
288 mAudioPolicyServiceClient->onAudioPatchListUpdate();
289 }
290 }
291
onDynamicPolicyMixStateUpdate(String8 regId,int32_t state)292 void AudioPolicyService::NotificationClient::onDynamicPolicyMixStateUpdate(
293 String8 regId, int32_t state)
294 {
295 if (mAudioPolicyServiceClient != 0) {
296 mAudioPolicyServiceClient->onDynamicPolicyMixStateUpdate(regId, state);
297 }
298 }
299
setAudioPortCallbacksEnabled(bool enabled)300 void AudioPolicyService::NotificationClient::setAudioPortCallbacksEnabled(bool enabled)
301 {
302 mAudioPortCallbacksEnabled = enabled;
303 }
304
305
binderDied(const wp<IBinder> & who)306 void AudioPolicyService::binderDied(const wp<IBinder>& who) {
307 ALOGW("binderDied() %p, calling pid %d", who.unsafe_get(),
308 IPCThreadState::self()->getCallingPid());
309 }
310
tryLock(Mutex & mutex)311 static bool tryLock(Mutex& mutex)
312 {
313 bool locked = false;
314 for (int i = 0; i < kDumpLockRetries; ++i) {
315 if (mutex.tryLock() == NO_ERROR) {
316 locked = true;
317 break;
318 }
319 usleep(kDumpLockSleepUs);
320 }
321 return locked;
322 }
323
dumpInternals(int fd)324 status_t AudioPolicyService::dumpInternals(int fd)
325 {
326 const size_t SIZE = 256;
327 char buffer[SIZE];
328 String8 result;
329
330 #ifdef USE_LEGACY_AUDIO_POLICY
331 snprintf(buffer, SIZE, "PolicyManager Interface: %p\n", mpAudioPolicy);
332 #else
333 snprintf(buffer, SIZE, "AudioPolicyManager: %p\n", mAudioPolicyManager);
334 #endif
335 result.append(buffer);
336 snprintf(buffer, SIZE, "Command Thread: %p\n", mAudioCommandThread.get());
337 result.append(buffer);
338 snprintf(buffer, SIZE, "Tones Thread: %p\n", mTonePlaybackThread.get());
339 result.append(buffer);
340
341 write(fd, result.string(), result.size());
342 return NO_ERROR;
343 }
344
dump(int fd,const Vector<String16> & args __unused)345 status_t AudioPolicyService::dump(int fd, const Vector<String16>& args __unused)
346 {
347 if (!dumpAllowed()) {
348 dumpPermissionDenial(fd);
349 } else {
350 bool locked = tryLock(mLock);
351 if (!locked) {
352 String8 result(kDeadlockedString);
353 write(fd, result.string(), result.size());
354 }
355
356 dumpInternals(fd);
357 if (mAudioCommandThread != 0) {
358 mAudioCommandThread->dump(fd);
359 }
360 if (mTonePlaybackThread != 0) {
361 mTonePlaybackThread->dump(fd);
362 }
363
364 #ifdef USE_LEGACY_AUDIO_POLICY
365 if (mpAudioPolicy) {
366 mpAudioPolicy->dump(mpAudioPolicy, fd);
367 }
368 #else
369 if (mAudioPolicyManager) {
370 mAudioPolicyManager->dump(fd);
371 }
372 #endif
373
374 if (locked) mLock.unlock();
375 }
376 return NO_ERROR;
377 }
378
dumpPermissionDenial(int fd)379 status_t AudioPolicyService::dumpPermissionDenial(int fd)
380 {
381 const size_t SIZE = 256;
382 char buffer[SIZE];
383 String8 result;
384 snprintf(buffer, SIZE, "Permission Denial: "
385 "can't dump AudioPolicyService from pid=%d, uid=%d\n",
386 IPCThreadState::self()->getCallingPid(),
387 IPCThreadState::self()->getCallingUid());
388 result.append(buffer);
389 write(fd, result.string(), result.size());
390 return NO_ERROR;
391 }
392
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)393 status_t AudioPolicyService::onTransact(
394 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
395 {
396 return BnAudioPolicyService::onTransact(code, data, reply, flags);
397 }
398
399
400 // ----------- AudioPolicyService::AudioCommandThread implementation ----------
401
AudioCommandThread(String8 name,const wp<AudioPolicyService> & service)402 AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name,
403 const wp<AudioPolicyService>& service)
404 : Thread(false), mName(name), mService(service)
405 {
406 mpToneGenerator = NULL;
407 }
408
409
~AudioCommandThread()410 AudioPolicyService::AudioCommandThread::~AudioCommandThread()
411 {
412 if (!mAudioCommands.isEmpty()) {
413 release_wake_lock(mName.string());
414 }
415 mAudioCommands.clear();
416 delete mpToneGenerator;
417 }
418
onFirstRef()419 void AudioPolicyService::AudioCommandThread::onFirstRef()
420 {
421 run(mName.string(), ANDROID_PRIORITY_AUDIO);
422 }
423
threadLoop()424 bool AudioPolicyService::AudioCommandThread::threadLoop()
425 {
426 nsecs_t waitTime = INT64_MAX;
427
428 mLock.lock();
429 while (!exitPending())
430 {
431 sp<AudioPolicyService> svc;
432 while (!mAudioCommands.isEmpty() && !exitPending()) {
433 nsecs_t curTime = systemTime();
434 // commands are sorted by increasing time stamp: execute them from index 0 and up
435 if (mAudioCommands[0]->mTime <= curTime) {
436 sp<AudioCommand> command = mAudioCommands[0];
437 mAudioCommands.removeAt(0);
438 mLastCommand = command;
439
440 switch (command->mCommand) {
441 case START_TONE: {
442 mLock.unlock();
443 ToneData *data = (ToneData *)command->mParam.get();
444 ALOGV("AudioCommandThread() processing start tone %d on stream %d",
445 data->mType, data->mStream);
446 delete mpToneGenerator;
447 mpToneGenerator = new ToneGenerator(data->mStream, 1.0);
448 mpToneGenerator->startTone(data->mType);
449 mLock.lock();
450 }break;
451 case STOP_TONE: {
452 mLock.unlock();
453 ALOGV("AudioCommandThread() processing stop tone");
454 if (mpToneGenerator != NULL) {
455 mpToneGenerator->stopTone();
456 delete mpToneGenerator;
457 mpToneGenerator = NULL;
458 }
459 mLock.lock();
460 }break;
461 case SET_VOLUME: {
462 VolumeData *data = (VolumeData *)command->mParam.get();
463 ALOGV("AudioCommandThread() processing set volume stream %d, \
464 volume %f, output %d", data->mStream, data->mVolume, data->mIO);
465 command->mStatus = AudioSystem::setStreamVolume(data->mStream,
466 data->mVolume,
467 data->mIO);
468 }break;
469 case SET_PARAMETERS: {
470 ParametersData *data = (ParametersData *)command->mParam.get();
471 ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
472 data->mKeyValuePairs.string(), data->mIO);
473 command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
474 }break;
475 case SET_VOICE_VOLUME: {
476 VoiceVolumeData *data = (VoiceVolumeData *)command->mParam.get();
477 ALOGV("AudioCommandThread() processing set voice volume volume %f",
478 data->mVolume);
479 command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
480 }break;
481 case STOP_OUTPUT: {
482 StopOutputData *data = (StopOutputData *)command->mParam.get();
483 ALOGV("AudioCommandThread() processing stop output %d",
484 data->mIO);
485 svc = mService.promote();
486 if (svc == 0) {
487 break;
488 }
489 mLock.unlock();
490 svc->doStopOutput(data->mIO, data->mStream, data->mSession);
491 mLock.lock();
492 }break;
493 case RELEASE_OUTPUT: {
494 ReleaseOutputData *data = (ReleaseOutputData *)command->mParam.get();
495 ALOGV("AudioCommandThread() processing release output %d",
496 data->mIO);
497 svc = mService.promote();
498 if (svc == 0) {
499 break;
500 }
501 mLock.unlock();
502 svc->doReleaseOutput(data->mIO, data->mStream, data->mSession);
503 mLock.lock();
504 }break;
505 case CREATE_AUDIO_PATCH: {
506 CreateAudioPatchData *data = (CreateAudioPatchData *)command->mParam.get();
507 ALOGV("AudioCommandThread() processing create audio patch");
508 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
509 if (af == 0) {
510 command->mStatus = PERMISSION_DENIED;
511 } else {
512 command->mStatus = af->createAudioPatch(&data->mPatch, &data->mHandle);
513 }
514 } break;
515 case RELEASE_AUDIO_PATCH: {
516 ReleaseAudioPatchData *data = (ReleaseAudioPatchData *)command->mParam.get();
517 ALOGV("AudioCommandThread() processing release audio patch");
518 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
519 if (af == 0) {
520 command->mStatus = PERMISSION_DENIED;
521 } else {
522 command->mStatus = af->releaseAudioPatch(data->mHandle);
523 }
524 } break;
525 case UPDATE_AUDIOPORT_LIST: {
526 ALOGV("AudioCommandThread() processing update audio port list");
527 svc = mService.promote();
528 if (svc == 0) {
529 break;
530 }
531 mLock.unlock();
532 svc->doOnAudioPortListUpdate();
533 mLock.lock();
534 }break;
535 case UPDATE_AUDIOPATCH_LIST: {
536 ALOGV("AudioCommandThread() processing update audio patch list");
537 svc = mService.promote();
538 if (svc == 0) {
539 break;
540 }
541 mLock.unlock();
542 svc->doOnAudioPatchListUpdate();
543 mLock.lock();
544 }break;
545 case SET_AUDIOPORT_CONFIG: {
546 SetAudioPortConfigData *data = (SetAudioPortConfigData *)command->mParam.get();
547 ALOGV("AudioCommandThread() processing set port config");
548 sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
549 if (af == 0) {
550 command->mStatus = PERMISSION_DENIED;
551 } else {
552 command->mStatus = af->setAudioPortConfig(&data->mConfig);
553 }
554 } break;
555 case DYN_POLICY_MIX_STATE_UPDATE: {
556 DynPolicyMixStateUpdateData *data =
557 (DynPolicyMixStateUpdateData *)command->mParam.get();
558 //###ALOGV("AudioCommandThread() processing dyn policy mix state update");
559 ALOGV("AudioCommandThread() processing dyn policy mix state update %s %d",
560 data->mRegId.string(), data->mState);
561 svc = mService.promote();
562 if (svc == 0) {
563 break;
564 }
565 mLock.unlock();
566 svc->doOnDynamicPolicyMixStateUpdate(data->mRegId, data->mState);
567 mLock.lock();
568 } break;
569 default:
570 ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
571 }
572 {
573 Mutex::Autolock _l(command->mLock);
574 if (command->mWaitStatus) {
575 command->mWaitStatus = false;
576 command->mCond.signal();
577 }
578 }
579 waitTime = INT64_MAX;
580 } else {
581 waitTime = mAudioCommands[0]->mTime - curTime;
582 break;
583 }
584 }
585 // release mLock before releasing strong reference on the service as
586 // AudioPolicyService destructor calls AudioCommandThread::exit() which acquires mLock.
587 mLock.unlock();
588 svc.clear();
589 mLock.lock();
590 if (!exitPending() && (mAudioCommands.isEmpty() || waitTime != INT64_MAX)) {
591 // release delayed commands wake lock
592 release_wake_lock(mName.string());
593 ALOGV("AudioCommandThread() going to sleep");
594 mWaitWorkCV.waitRelative(mLock, waitTime);
595 ALOGV("AudioCommandThread() waking up");
596 }
597 }
598 // release delayed commands wake lock before quitting
599 if (!mAudioCommands.isEmpty()) {
600 release_wake_lock(mName.string());
601 }
602 mLock.unlock();
603 return false;
604 }
605
dump(int fd)606 status_t AudioPolicyService::AudioCommandThread::dump(int fd)
607 {
608 const size_t SIZE = 256;
609 char buffer[SIZE];
610 String8 result;
611
612 snprintf(buffer, SIZE, "AudioCommandThread %p Dump\n", this);
613 result.append(buffer);
614 write(fd, result.string(), result.size());
615
616 bool locked = tryLock(mLock);
617 if (!locked) {
618 String8 result2(kCmdDeadlockedString);
619 write(fd, result2.string(), result2.size());
620 }
621
622 snprintf(buffer, SIZE, "- Commands:\n");
623 result = String8(buffer);
624 result.append(" Command Time Wait pParam\n");
625 for (size_t i = 0; i < mAudioCommands.size(); i++) {
626 mAudioCommands[i]->dump(buffer, SIZE);
627 result.append(buffer);
628 }
629 result.append(" Last Command\n");
630 if (mLastCommand != 0) {
631 mLastCommand->dump(buffer, SIZE);
632 result.append(buffer);
633 } else {
634 result.append(" none\n");
635 }
636
637 write(fd, result.string(), result.size());
638
639 if (locked) mLock.unlock();
640
641 return NO_ERROR;
642 }
643
startToneCommand(ToneGenerator::tone_type type,audio_stream_type_t stream)644 void AudioPolicyService::AudioCommandThread::startToneCommand(ToneGenerator::tone_type type,
645 audio_stream_type_t stream)
646 {
647 sp<AudioCommand> command = new AudioCommand();
648 command->mCommand = START_TONE;
649 sp<ToneData> data = new ToneData();
650 data->mType = type;
651 data->mStream = stream;
652 command->mParam = data;
653 ALOGV("AudioCommandThread() adding tone start type %d, stream %d", type, stream);
654 sendCommand(command);
655 }
656
stopToneCommand()657 void AudioPolicyService::AudioCommandThread::stopToneCommand()
658 {
659 sp<AudioCommand> command = new AudioCommand();
660 command->mCommand = STOP_TONE;
661 ALOGV("AudioCommandThread() adding tone stop");
662 sendCommand(command);
663 }
664
volumeCommand(audio_stream_type_t stream,float volume,audio_io_handle_t output,int delayMs)665 status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
666 float volume,
667 audio_io_handle_t output,
668 int delayMs)
669 {
670 sp<AudioCommand> command = new AudioCommand();
671 command->mCommand = SET_VOLUME;
672 sp<VolumeData> data = new VolumeData();
673 data->mStream = stream;
674 data->mVolume = volume;
675 data->mIO = output;
676 command->mParam = data;
677 command->mWaitStatus = true;
678 ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
679 stream, volume, output);
680 return sendCommand(command, delayMs);
681 }
682
parametersCommand(audio_io_handle_t ioHandle,const char * keyValuePairs,int delayMs)683 status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
684 const char *keyValuePairs,
685 int delayMs)
686 {
687 sp<AudioCommand> command = new AudioCommand();
688 command->mCommand = SET_PARAMETERS;
689 sp<ParametersData> data = new ParametersData();
690 data->mIO = ioHandle;
691 data->mKeyValuePairs = String8(keyValuePairs);
692 command->mParam = data;
693 command->mWaitStatus = true;
694 ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
695 keyValuePairs, ioHandle, delayMs);
696 return sendCommand(command, delayMs);
697 }
698
voiceVolumeCommand(float volume,int delayMs)699 status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
700 {
701 sp<AudioCommand> command = new AudioCommand();
702 command->mCommand = SET_VOICE_VOLUME;
703 sp<VoiceVolumeData> data = new VoiceVolumeData();
704 data->mVolume = volume;
705 command->mParam = data;
706 command->mWaitStatus = true;
707 ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
708 return sendCommand(command, delayMs);
709 }
710
stopOutputCommand(audio_io_handle_t output,audio_stream_type_t stream,audio_session_t session)711 void AudioPolicyService::AudioCommandThread::stopOutputCommand(audio_io_handle_t output,
712 audio_stream_type_t stream,
713 audio_session_t session)
714 {
715 sp<AudioCommand> command = new AudioCommand();
716 command->mCommand = STOP_OUTPUT;
717 sp<StopOutputData> data = new StopOutputData();
718 data->mIO = output;
719 data->mStream = stream;
720 data->mSession = session;
721 command->mParam = data;
722 ALOGV("AudioCommandThread() adding stop output %d", output);
723 sendCommand(command);
724 }
725
releaseOutputCommand(audio_io_handle_t output,audio_stream_type_t stream,audio_session_t session)726 void AudioPolicyService::AudioCommandThread::releaseOutputCommand(audio_io_handle_t output,
727 audio_stream_type_t stream,
728 audio_session_t session)
729 {
730 sp<AudioCommand> command = new AudioCommand();
731 command->mCommand = RELEASE_OUTPUT;
732 sp<ReleaseOutputData> data = new ReleaseOutputData();
733 data->mIO = output;
734 data->mStream = stream;
735 data->mSession = session;
736 command->mParam = data;
737 ALOGV("AudioCommandThread() adding release output %d", output);
738 sendCommand(command);
739 }
740
createAudioPatchCommand(const struct audio_patch * patch,audio_patch_handle_t * handle,int delayMs)741 status_t AudioPolicyService::AudioCommandThread::createAudioPatchCommand(
742 const struct audio_patch *patch,
743 audio_patch_handle_t *handle,
744 int delayMs)
745 {
746 status_t status = NO_ERROR;
747
748 sp<AudioCommand> command = new AudioCommand();
749 command->mCommand = CREATE_AUDIO_PATCH;
750 CreateAudioPatchData *data = new CreateAudioPatchData();
751 data->mPatch = *patch;
752 data->mHandle = *handle;
753 command->mParam = data;
754 command->mWaitStatus = true;
755 ALOGV("AudioCommandThread() adding create patch delay %d", delayMs);
756 status = sendCommand(command, delayMs);
757 if (status == NO_ERROR) {
758 *handle = data->mHandle;
759 }
760 return status;
761 }
762
releaseAudioPatchCommand(audio_patch_handle_t handle,int delayMs)763 status_t AudioPolicyService::AudioCommandThread::releaseAudioPatchCommand(audio_patch_handle_t handle,
764 int delayMs)
765 {
766 sp<AudioCommand> command = new AudioCommand();
767 command->mCommand = RELEASE_AUDIO_PATCH;
768 ReleaseAudioPatchData *data = new ReleaseAudioPatchData();
769 data->mHandle = handle;
770 command->mParam = data;
771 command->mWaitStatus = true;
772 ALOGV("AudioCommandThread() adding release patch delay %d", delayMs);
773 return sendCommand(command, delayMs);
774 }
775
updateAudioPortListCommand()776 void AudioPolicyService::AudioCommandThread::updateAudioPortListCommand()
777 {
778 sp<AudioCommand> command = new AudioCommand();
779 command->mCommand = UPDATE_AUDIOPORT_LIST;
780 ALOGV("AudioCommandThread() adding update audio port list");
781 sendCommand(command);
782 }
783
updateAudioPatchListCommand()784 void AudioPolicyService::AudioCommandThread::updateAudioPatchListCommand()
785 {
786 sp<AudioCommand>command = new AudioCommand();
787 command->mCommand = UPDATE_AUDIOPATCH_LIST;
788 ALOGV("AudioCommandThread() adding update audio patch list");
789 sendCommand(command);
790 }
791
setAudioPortConfigCommand(const struct audio_port_config * config,int delayMs)792 status_t AudioPolicyService::AudioCommandThread::setAudioPortConfigCommand(
793 const struct audio_port_config *config, int delayMs)
794 {
795 sp<AudioCommand> command = new AudioCommand();
796 command->mCommand = SET_AUDIOPORT_CONFIG;
797 SetAudioPortConfigData *data = new SetAudioPortConfigData();
798 data->mConfig = *config;
799 command->mParam = data;
800 command->mWaitStatus = true;
801 ALOGV("AudioCommandThread() adding set port config delay %d", delayMs);
802 return sendCommand(command, delayMs);
803 }
804
dynamicPolicyMixStateUpdateCommand(String8 regId,int32_t state)805 void AudioPolicyService::AudioCommandThread::dynamicPolicyMixStateUpdateCommand(
806 String8 regId, int32_t state)
807 {
808 sp<AudioCommand> command = new AudioCommand();
809 command->mCommand = DYN_POLICY_MIX_STATE_UPDATE;
810 DynPolicyMixStateUpdateData *data = new DynPolicyMixStateUpdateData();
811 data->mRegId = regId;
812 data->mState = state;
813 command->mParam = data;
814 ALOGV("AudioCommandThread() sending dynamic policy mix (id=%s) state update to %d",
815 regId.string(), state);
816 sendCommand(command);
817 }
818
sendCommand(sp<AudioCommand> & command,int delayMs)819 status_t AudioPolicyService::AudioCommandThread::sendCommand(sp<AudioCommand>& command, int delayMs)
820 {
821 {
822 Mutex::Autolock _l(mLock);
823 insertCommand_l(command, delayMs);
824 mWaitWorkCV.signal();
825 }
826 Mutex::Autolock _l(command->mLock);
827 while (command->mWaitStatus) {
828 nsecs_t timeOutNs = kAudioCommandTimeoutNs + milliseconds(delayMs);
829 if (command->mCond.waitRelative(command->mLock, timeOutNs) != NO_ERROR) {
830 command->mStatus = TIMED_OUT;
831 command->mWaitStatus = false;
832 }
833 }
834 return command->mStatus;
835 }
836
837 // insertCommand_l() must be called with mLock held
insertCommand_l(sp<AudioCommand> & command,int delayMs)838 void AudioPolicyService::AudioCommandThread::insertCommand_l(sp<AudioCommand>& command, int delayMs)
839 {
840 ssize_t i; // not size_t because i will count down to -1
841 Vector < sp<AudioCommand> > removedCommands;
842 command->mTime = systemTime() + milliseconds(delayMs);
843
844 // acquire wake lock to make sure delayed commands are processed
845 if (mAudioCommands.isEmpty()) {
846 acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.string());
847 }
848
849 // check same pending commands with later time stamps and eliminate them
850 for (i = mAudioCommands.size()-1; i >= 0; i--) {
851 sp<AudioCommand> command2 = mAudioCommands[i];
852 // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
853 if (command2->mTime <= command->mTime) break;
854
855 // create audio patch or release audio patch commands are equivalent
856 // with regard to filtering
857 if ((command->mCommand == CREATE_AUDIO_PATCH) ||
858 (command->mCommand == RELEASE_AUDIO_PATCH)) {
859 if ((command2->mCommand != CREATE_AUDIO_PATCH) &&
860 (command2->mCommand != RELEASE_AUDIO_PATCH)) {
861 continue;
862 }
863 } else if (command2->mCommand != command->mCommand) continue;
864
865 switch (command->mCommand) {
866 case SET_PARAMETERS: {
867 ParametersData *data = (ParametersData *)command->mParam.get();
868 ParametersData *data2 = (ParametersData *)command2->mParam.get();
869 if (data->mIO != data2->mIO) break;
870 ALOGV("Comparing parameter command %s to new command %s",
871 data2->mKeyValuePairs.string(), data->mKeyValuePairs.string());
872 AudioParameter param = AudioParameter(data->mKeyValuePairs);
873 AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
874 for (size_t j = 0; j < param.size(); j++) {
875 String8 key;
876 String8 value;
877 param.getAt(j, key, value);
878 for (size_t k = 0; k < param2.size(); k++) {
879 String8 key2;
880 String8 value2;
881 param2.getAt(k, key2, value2);
882 if (key2 == key) {
883 param2.remove(key2);
884 ALOGV("Filtering out parameter %s", key2.string());
885 break;
886 }
887 }
888 }
889 // if all keys have been filtered out, remove the command.
890 // otherwise, update the key value pairs
891 if (param2.size() == 0) {
892 removedCommands.add(command2);
893 } else {
894 data2->mKeyValuePairs = param2.toString();
895 }
896 command->mTime = command2->mTime;
897 // force delayMs to non 0 so that code below does not request to wait for
898 // command status as the command is now delayed
899 delayMs = 1;
900 } break;
901
902 case SET_VOLUME: {
903 VolumeData *data = (VolumeData *)command->mParam.get();
904 VolumeData *data2 = (VolumeData *)command2->mParam.get();
905 if (data->mIO != data2->mIO) break;
906 if (data->mStream != data2->mStream) break;
907 ALOGV("Filtering out volume command on output %d for stream %d",
908 data->mIO, data->mStream);
909 removedCommands.add(command2);
910 command->mTime = command2->mTime;
911 // force delayMs to non 0 so that code below does not request to wait for
912 // command status as the command is now delayed
913 delayMs = 1;
914 } break;
915
916 case CREATE_AUDIO_PATCH:
917 case RELEASE_AUDIO_PATCH: {
918 audio_patch_handle_t handle;
919 struct audio_patch patch;
920 if (command->mCommand == CREATE_AUDIO_PATCH) {
921 handle = ((CreateAudioPatchData *)command->mParam.get())->mHandle;
922 patch = ((CreateAudioPatchData *)command->mParam.get())->mPatch;
923 } else {
924 handle = ((ReleaseAudioPatchData *)command->mParam.get())->mHandle;
925 }
926 audio_patch_handle_t handle2;
927 struct audio_patch patch2;
928 if (command2->mCommand == CREATE_AUDIO_PATCH) {
929 handle2 = ((CreateAudioPatchData *)command2->mParam.get())->mHandle;
930 patch2 = ((CreateAudioPatchData *)command2->mParam.get())->mPatch;
931 } else {
932 handle2 = ((ReleaseAudioPatchData *)command2->mParam.get())->mHandle;
933 memset(&patch2, 0, sizeof(patch2));
934 }
935 if (handle != handle2) break;
936 /* Filter CREATE_AUDIO_PATCH commands only when they are issued for
937 same output. */
938 if( (command->mCommand == CREATE_AUDIO_PATCH) &&
939 (command2->mCommand == CREATE_AUDIO_PATCH) ) {
940 bool isOutputDiff = false;
941 if (patch.num_sources == patch2.num_sources) {
942 for (unsigned count = 0; count < patch.num_sources; count++) {
943 if (patch.sources[count].id != patch2.sources[count].id) {
944 isOutputDiff = true;
945 break;
946 }
947 }
948 if (isOutputDiff)
949 break;
950 }
951 }
952 ALOGV("Filtering out %s audio patch command for handle %d",
953 (command->mCommand == CREATE_AUDIO_PATCH) ? "create" : "release", handle);
954 removedCommands.add(command2);
955 command->mTime = command2->mTime;
956 // force delayMs to non 0 so that code below does not request to wait for
957 // command status as the command is now delayed
958 delayMs = 1;
959 } break;
960
961 case DYN_POLICY_MIX_STATE_UPDATE: {
962
963 } break;
964
965 case START_TONE:
966 case STOP_TONE:
967 default:
968 break;
969 }
970 }
971
972 // remove filtered commands
973 for (size_t j = 0; j < removedCommands.size(); j++) {
974 // removed commands always have time stamps greater than current command
975 for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
976 if (mAudioCommands[k].get() == removedCommands[j].get()) {
977 ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
978 mAudioCommands.removeAt(k);
979 break;
980 }
981 }
982 }
983 removedCommands.clear();
984
985 // Disable wait for status if delay is not 0.
986 // Except for create audio patch command because the returned patch handle
987 // is needed by audio policy manager
988 if (delayMs != 0 && command->mCommand != CREATE_AUDIO_PATCH) {
989 command->mWaitStatus = false;
990 }
991
992 // insert command at the right place according to its time stamp
993 ALOGV("inserting command: %d at index %zd, num commands %zu",
994 command->mCommand, i+1, mAudioCommands.size());
995 mAudioCommands.insertAt(command, i + 1);
996 }
997
exit()998 void AudioPolicyService::AudioCommandThread::exit()
999 {
1000 ALOGV("AudioCommandThread::exit");
1001 {
1002 AutoMutex _l(mLock);
1003 requestExit();
1004 mWaitWorkCV.signal();
1005 }
1006 requestExitAndWait();
1007 }
1008
dump(char * buffer,size_t size)1009 void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
1010 {
1011 snprintf(buffer, size, " %02d %06d.%03d %01u %p\n",
1012 mCommand,
1013 (int)ns2s(mTime),
1014 (int)ns2ms(mTime)%1000,
1015 mWaitStatus,
1016 mParam.get());
1017 }
1018
1019 /******* helpers for the service_ops callbacks defined below *********/
setParameters(audio_io_handle_t ioHandle,const char * keyValuePairs,int delayMs)1020 void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
1021 const char *keyValuePairs,
1022 int delayMs)
1023 {
1024 mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
1025 delayMs);
1026 }
1027
setStreamVolume(audio_stream_type_t stream,float volume,audio_io_handle_t output,int delayMs)1028 int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
1029 float volume,
1030 audio_io_handle_t output,
1031 int delayMs)
1032 {
1033 return (int)mAudioCommandThread->volumeCommand(stream, volume,
1034 output, delayMs);
1035 }
1036
startTone(audio_policy_tone_t tone,audio_stream_type_t stream)1037 int AudioPolicyService::startTone(audio_policy_tone_t tone,
1038 audio_stream_type_t stream)
1039 {
1040 if (tone != AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION) {
1041 ALOGE("startTone: illegal tone requested (%d)", tone);
1042 }
1043 if (stream != AUDIO_STREAM_VOICE_CALL) {
1044 ALOGE("startTone: illegal stream (%d) requested for tone %d", stream,
1045 tone);
1046 }
1047 mTonePlaybackThread->startToneCommand(ToneGenerator::TONE_SUP_CALL_WAITING,
1048 AUDIO_STREAM_VOICE_CALL);
1049 return 0;
1050 }
1051
stopTone()1052 int AudioPolicyService::stopTone()
1053 {
1054 mTonePlaybackThread->stopToneCommand();
1055 return 0;
1056 }
1057
setVoiceVolume(float volume,int delayMs)1058 int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
1059 {
1060 return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
1061 }
1062
1063 extern "C" {
1064 audio_module_handle_t aps_load_hw_module(void *service __unused,
1065 const char *name);
1066 audio_io_handle_t aps_open_output(void *service __unused,
1067 audio_devices_t *pDevices,
1068 uint32_t *pSamplingRate,
1069 audio_format_t *pFormat,
1070 audio_channel_mask_t *pChannelMask,
1071 uint32_t *pLatencyMs,
1072 audio_output_flags_t flags);
1073
1074 audio_io_handle_t aps_open_output_on_module(void *service __unused,
1075 audio_module_handle_t module,
1076 audio_devices_t *pDevices,
1077 uint32_t *pSamplingRate,
1078 audio_format_t *pFormat,
1079 audio_channel_mask_t *pChannelMask,
1080 uint32_t *pLatencyMs,
1081 audio_output_flags_t flags,
1082 const audio_offload_info_t *offloadInfo);
1083 audio_io_handle_t aps_open_dup_output(void *service __unused,
1084 audio_io_handle_t output1,
1085 audio_io_handle_t output2);
1086 int aps_close_output(void *service __unused, audio_io_handle_t output);
1087 int aps_suspend_output(void *service __unused, audio_io_handle_t output);
1088 int aps_restore_output(void *service __unused, audio_io_handle_t output);
1089 audio_io_handle_t aps_open_input(void *service __unused,
1090 audio_devices_t *pDevices,
1091 uint32_t *pSamplingRate,
1092 audio_format_t *pFormat,
1093 audio_channel_mask_t *pChannelMask,
1094 audio_in_acoustics_t acoustics __unused);
1095 audio_io_handle_t aps_open_input_on_module(void *service __unused,
1096 audio_module_handle_t module,
1097 audio_devices_t *pDevices,
1098 uint32_t *pSamplingRate,
1099 audio_format_t *pFormat,
1100 audio_channel_mask_t *pChannelMask);
1101 int aps_close_input(void *service __unused, audio_io_handle_t input);
1102 int aps_invalidate_stream(void *service __unused, audio_stream_type_t stream);
1103 int aps_move_effects(void *service __unused, int session,
1104 audio_io_handle_t src_output,
1105 audio_io_handle_t dst_output);
1106 char * aps_get_parameters(void *service __unused, audio_io_handle_t io_handle,
1107 const char *keys);
1108 void aps_set_parameters(void *service, audio_io_handle_t io_handle,
1109 const char *kv_pairs, int delay_ms);
1110 int aps_set_stream_volume(void *service, audio_stream_type_t stream,
1111 float volume, audio_io_handle_t output,
1112 int delay_ms);
1113 int aps_start_tone(void *service, audio_policy_tone_t tone,
1114 audio_stream_type_t stream);
1115 int aps_stop_tone(void *service);
1116 int aps_set_voice_volume(void *service, float volume, int delay_ms);
1117 };
1118
1119 namespace {
1120 struct audio_policy_service_ops aps_ops = {
1121 .open_output = aps_open_output,
1122 .open_duplicate_output = aps_open_dup_output,
1123 .close_output = aps_close_output,
1124 .suspend_output = aps_suspend_output,
1125 .restore_output = aps_restore_output,
1126 .open_input = aps_open_input,
1127 .close_input = aps_close_input,
1128 .set_stream_volume = aps_set_stream_volume,
1129 .invalidate_stream = aps_invalidate_stream,
1130 .set_parameters = aps_set_parameters,
1131 .get_parameters = aps_get_parameters,
1132 .start_tone = aps_start_tone,
1133 .stop_tone = aps_stop_tone,
1134 .set_voice_volume = aps_set_voice_volume,
1135 .move_effects = aps_move_effects,
1136 .load_hw_module = aps_load_hw_module,
1137 .open_output_on_module = aps_open_output_on_module,
1138 .open_input_on_module = aps_open_input_on_module,
1139 };
1140 }; // namespace <unnamed>
1141
1142 }; // namespace android
1143