AudioPolicyService.cpp revision 935752053ef2691dbb6d5a6d149e0e362c6e3c74
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#undef __STRICT_ANSI__
21#define __STDINT_LIMITS
22#define __STDC_LIMIT_MACROS
23#include <stdint.h>
24
25#include <sys/time.h>
26#include <binder/IServiceManager.h>
27#include <utils/Log.h>
28#include <cutils/properties.h>
29#include <binder/IPCThreadState.h>
30#include <utils/String16.h>
31#include <utils/threads.h>
32#include "AudioPolicyService.h"
33#include <hardware_legacy/AudioPolicyManagerBase.h>
34#include <cutils/properties.h>
35#include <dlfcn.h>
36#include <hardware_legacy/power.h>
37
38// ----------------------------------------------------------------------------
39// the sim build doesn't have gettid
40
41#ifndef HAVE_GETTID
42# define gettid getpid
43#endif
44
45namespace android {
46
47
48static const char *kDeadlockedString = "AudioPolicyService may be deadlocked\n";
49static const char *kCmdDeadlockedString = "AudioPolicyService command thread may be deadlocked\n";
50
51static const int kDumpLockRetries = 50;
52static const int kDumpLockSleep = 20000;
53
54static bool checkPermission() {
55#ifndef HAVE_ANDROID_OS
56    return true;
57#endif
58    if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
59    bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
60    if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
61    return ok;
62}
63
64// ----------------------------------------------------------------------------
65
66AudioPolicyService::AudioPolicyService()
67    : BnAudioPolicyService() , mpPolicyManager(NULL)
68{
69    char value[PROPERTY_VALUE_MAX];
70
71    Mutex::Autolock _l(mLock);
72
73    // start tone playback thread
74    mTonePlaybackThread = new AudioCommandThread(String8(""));
75    // start audio commands thread
76    mAudioCommandThread = new AudioCommandThread(String8("ApmCommandThread"));
77
78#if (defined GENERIC_AUDIO) || (defined AUDIO_POLICY_TEST)
79    mpPolicyManager = new AudioPolicyManagerBase(this);
80    LOGV("build for GENERIC_AUDIO - using generic audio policy");
81#else
82    // if running in emulation - use the emulator driver
83    if (property_get("ro.kernel.qemu", value, 0)) {
84        LOGV("Running in emulation - using generic audio policy");
85        mpPolicyManager = new AudioPolicyManagerBase(this);
86    }
87    else {
88        LOGV("Using hardware specific audio policy");
89        mpPolicyManager = createAudioPolicyManager(this);
90    }
91#endif
92
93    if ((mpPolicyManager != NULL) && (mpPolicyManager->initCheck() != NO_ERROR)) {
94        delete mpPolicyManager;
95        mpPolicyManager = NULL;
96    }
97
98    if (mpPolicyManager == NULL) {
99        LOGE("Could not create AudioPolicyManager");
100    } else {
101        // load properties
102        property_get("ro.camera.sound.forced", value, "0");
103        mpPolicyManager->setSystemProperty("ro.camera.sound.forced", value);
104    }
105}
106
107AudioPolicyService::~AudioPolicyService()
108{
109    mTonePlaybackThread->exit();
110    mTonePlaybackThread.clear();
111    mAudioCommandThread->exit();
112    mAudioCommandThread.clear();
113
114    if (mpPolicyManager) {
115        delete mpPolicyManager;
116    }
117}
118
119
120status_t AudioPolicyService::setDeviceConnectionState(AudioSystem::audio_devices device,
121                                                  AudioSystem::device_connection_state state,
122                                                  const char *device_address)
123{
124    if (mpPolicyManager == NULL) {
125        return NO_INIT;
126    }
127    if (!checkPermission()) {
128        return PERMISSION_DENIED;
129    }
130    if (!AudioSystem::isOutputDevice(device) && !AudioSystem::isInputDevice(device)) {
131        return BAD_VALUE;
132    }
133    if (state != AudioSystem::DEVICE_STATE_AVAILABLE &&
134            state != AudioSystem::DEVICE_STATE_UNAVAILABLE) {
135        return BAD_VALUE;
136    }
137
138    LOGV("setDeviceConnectionState() tid %d", gettid());
139    Mutex::Autolock _l(mLock);
140    return mpPolicyManager->setDeviceConnectionState(device, state, device_address);
141}
142
143AudioSystem::device_connection_state AudioPolicyService::getDeviceConnectionState(
144                                                              AudioSystem::audio_devices device,
145                                                              const char *device_address)
146{
147    if (mpPolicyManager == NULL) {
148        return AudioSystem::DEVICE_STATE_UNAVAILABLE;
149    }
150    if (!checkPermission()) {
151        return AudioSystem::DEVICE_STATE_UNAVAILABLE;
152    }
153    return mpPolicyManager->getDeviceConnectionState(device, device_address);
154}
155
156status_t AudioPolicyService::setPhoneState(int state)
157{
158    if (mpPolicyManager == NULL) {
159        return NO_INIT;
160    }
161    if (!checkPermission()) {
162        return PERMISSION_DENIED;
163    }
164    if (state < 0 || state >= AudioSystem::NUM_MODES) {
165        return BAD_VALUE;
166    }
167
168    LOGV("setPhoneState() tid %d", gettid());
169
170    // TODO: check if it is more appropriate to do it in platform specific policy manager
171    AudioSystem::setMode(state);
172
173    Mutex::Autolock _l(mLock);
174    mpPolicyManager->setPhoneState(state);
175    return NO_ERROR;
176}
177
178status_t AudioPolicyService::setRingerMode(uint32_t mode, uint32_t mask)
179{
180    if (mpPolicyManager == NULL) {
181        return NO_INIT;
182    }
183    if (!checkPermission()) {
184        return PERMISSION_DENIED;
185    }
186
187    mpPolicyManager->setRingerMode(mode, mask);
188    return NO_ERROR;
189}
190
191status_t AudioPolicyService::setForceUse(AudioSystem::force_use usage,
192                                         AudioSystem::forced_config config)
193{
194    if (mpPolicyManager == NULL) {
195        return NO_INIT;
196    }
197    if (!checkPermission()) {
198        return PERMISSION_DENIED;
199    }
200    if (usage < 0 || usage >= AudioSystem::NUM_FORCE_USE) {
201        return BAD_VALUE;
202    }
203    if (config < 0 || config >= AudioSystem::NUM_FORCE_CONFIG) {
204        return BAD_VALUE;
205    }
206    LOGV("setForceUse() tid %d", gettid());
207    Mutex::Autolock _l(mLock);
208    mpPolicyManager->setForceUse(usage, config);
209    return NO_ERROR;
210}
211
212AudioSystem::forced_config AudioPolicyService::getForceUse(AudioSystem::force_use usage)
213{
214    if (mpPolicyManager == NULL) {
215        return AudioSystem::FORCE_NONE;
216    }
217    if (!checkPermission()) {
218        return AudioSystem::FORCE_NONE;
219    }
220    if (usage < 0 || usage >= AudioSystem::NUM_FORCE_USE) {
221        return AudioSystem::FORCE_NONE;
222    }
223    return mpPolicyManager->getForceUse(usage);
224}
225
226audio_io_handle_t AudioPolicyService::getOutput(AudioSystem::stream_type stream,
227                                    uint32_t samplingRate,
228                                    uint32_t format,
229                                    uint32_t channels,
230                                    AudioSystem::output_flags flags)
231{
232    if (mpPolicyManager == NULL) {
233        return 0;
234    }
235    LOGV("getOutput() tid %d", gettid());
236    Mutex::Autolock _l(mLock);
237    return mpPolicyManager->getOutput(stream, samplingRate, format, channels, flags);
238}
239
240status_t AudioPolicyService::startOutput(audio_io_handle_t output,
241                                         AudioSystem::stream_type stream,
242                                         int session)
243{
244    if (mpPolicyManager == NULL) {
245        return NO_INIT;
246    }
247    LOGV("startOutput() tid %d", gettid());
248    Mutex::Autolock _l(mLock);
249    return mpPolicyManager->startOutput(output, stream, session);
250}
251
252status_t AudioPolicyService::stopOutput(audio_io_handle_t output,
253                                        AudioSystem::stream_type stream,
254                                        int session)
255{
256    if (mpPolicyManager == NULL) {
257        return NO_INIT;
258    }
259    LOGV("stopOutput() tid %d", gettid());
260    Mutex::Autolock _l(mLock);
261    return mpPolicyManager->stopOutput(output, stream, session);
262}
263
264void AudioPolicyService::releaseOutput(audio_io_handle_t output)
265{
266    if (mpPolicyManager == NULL) {
267        return;
268    }
269    LOGV("releaseOutput() tid %d", gettid());
270    Mutex::Autolock _l(mLock);
271    mpPolicyManager->releaseOutput(output);
272}
273
274audio_io_handle_t AudioPolicyService::getInput(int inputSource,
275                                    uint32_t samplingRate,
276                                    uint32_t format,
277                                    uint32_t channels,
278                                    AudioSystem::audio_in_acoustics acoustics)
279{
280    if (mpPolicyManager == NULL) {
281        return 0;
282    }
283    Mutex::Autolock _l(mLock);
284    return mpPolicyManager->getInput(inputSource, samplingRate, format, channels, acoustics);
285}
286
287status_t AudioPolicyService::startInput(audio_io_handle_t input)
288{
289    if (mpPolicyManager == NULL) {
290        return NO_INIT;
291    }
292    Mutex::Autolock _l(mLock);
293    return mpPolicyManager->startInput(input);
294}
295
296status_t AudioPolicyService::stopInput(audio_io_handle_t input)
297{
298    if (mpPolicyManager == NULL) {
299        return NO_INIT;
300    }
301    Mutex::Autolock _l(mLock);
302    return mpPolicyManager->stopInput(input);
303}
304
305void AudioPolicyService::releaseInput(audio_io_handle_t input)
306{
307    if (mpPolicyManager == NULL) {
308        return;
309    }
310    Mutex::Autolock _l(mLock);
311    mpPolicyManager->releaseInput(input);
312}
313
314status_t AudioPolicyService::initStreamVolume(AudioSystem::stream_type stream,
315                                            int indexMin,
316                                            int indexMax)
317{
318    if (mpPolicyManager == NULL) {
319        return NO_INIT;
320    }
321    if (!checkPermission()) {
322        return PERMISSION_DENIED;
323    }
324    if (stream < 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
325        return BAD_VALUE;
326    }
327    mpPolicyManager->initStreamVolume(stream, indexMin, indexMax);
328    return NO_ERROR;
329}
330
331status_t AudioPolicyService::setStreamVolumeIndex(AudioSystem::stream_type stream, int index)
332{
333    if (mpPolicyManager == NULL) {
334        return NO_INIT;
335    }
336    if (!checkPermission()) {
337        return PERMISSION_DENIED;
338    }
339    if (stream < 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
340        return BAD_VALUE;
341    }
342
343    return mpPolicyManager->setStreamVolumeIndex(stream, index);
344}
345
346status_t AudioPolicyService::getStreamVolumeIndex(AudioSystem::stream_type stream, int *index)
347{
348    if (mpPolicyManager == NULL) {
349        return NO_INIT;
350    }
351    if (!checkPermission()) {
352        return PERMISSION_DENIED;
353    }
354    if (stream < 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
355        return BAD_VALUE;
356    }
357    return mpPolicyManager->getStreamVolumeIndex(stream, index);
358}
359
360uint32_t AudioPolicyService::getStrategyForStream(AudioSystem::stream_type stream)
361{
362    if (mpPolicyManager == NULL) {
363        return 0;
364    }
365    return mpPolicyManager->getStrategyForStream(stream);
366}
367
368audio_io_handle_t AudioPolicyService::getOutputForEffect(effect_descriptor_t *desc)
369{
370    if (mpPolicyManager == NULL) {
371        return NO_INIT;
372    }
373    Mutex::Autolock _l(mLock);
374    return mpPolicyManager->getOutputForEffect(desc);
375}
376
377status_t AudioPolicyService::registerEffect(effect_descriptor_t *desc,
378                                audio_io_handle_t output,
379                                uint32_t strategy,
380                                int session,
381                                int id)
382{
383    if (mpPolicyManager == NULL) {
384        return NO_INIT;
385    }
386    return mpPolicyManager->registerEffect(desc, output, strategy, session, id);
387}
388
389status_t AudioPolicyService::unregisterEffect(int id)
390{
391    if (mpPolicyManager == NULL) {
392        return NO_INIT;
393    }
394    return mpPolicyManager->unregisterEffect(id);
395}
396
397void AudioPolicyService::binderDied(const wp<IBinder>& who) {
398    LOGW("binderDied() %p, tid %d, calling tid %d", who.unsafe_get(), gettid(),
399            IPCThreadState::self()->getCallingPid());
400}
401
402static bool tryLock(Mutex& mutex)
403{
404    bool locked = false;
405    for (int i = 0; i < kDumpLockRetries; ++i) {
406        if (mutex.tryLock() == NO_ERROR) {
407            locked = true;
408            break;
409        }
410        usleep(kDumpLockSleep);
411    }
412    return locked;
413}
414
415status_t AudioPolicyService::dumpInternals(int fd)
416{
417    const size_t SIZE = 256;
418    char buffer[SIZE];
419    String8 result;
420
421    snprintf(buffer, SIZE, "PolicyManager Interface: %p\n", mpPolicyManager);
422    result.append(buffer);
423    snprintf(buffer, SIZE, "Command Thread: %p\n", mAudioCommandThread.get());
424    result.append(buffer);
425    snprintf(buffer, SIZE, "Tones Thread: %p\n", mTonePlaybackThread.get());
426    result.append(buffer);
427
428    write(fd, result.string(), result.size());
429    return NO_ERROR;
430}
431
432status_t AudioPolicyService::dump(int fd, const Vector<String16>& args)
433{
434    if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
435        dumpPermissionDenial(fd);
436    } else {
437        bool locked = tryLock(mLock);
438        if (!locked) {
439            String8 result(kDeadlockedString);
440            write(fd, result.string(), result.size());
441        }
442
443        dumpInternals(fd);
444        if (mAudioCommandThread != NULL) {
445            mAudioCommandThread->dump(fd);
446        }
447        if (mTonePlaybackThread != NULL) {
448            mTonePlaybackThread->dump(fd);
449        }
450
451        if (mpPolicyManager) {
452            mpPolicyManager->dump(fd);
453        }
454
455        if (locked) mLock.unlock();
456    }
457    return NO_ERROR;
458}
459
460status_t AudioPolicyService::dumpPermissionDenial(int fd)
461{
462    const size_t SIZE = 256;
463    char buffer[SIZE];
464    String8 result;
465    snprintf(buffer, SIZE, "Permission Denial: "
466            "can't dump AudioPolicyService from pid=%d, uid=%d\n",
467            IPCThreadState::self()->getCallingPid(),
468            IPCThreadState::self()->getCallingUid());
469    result.append(buffer);
470    write(fd, result.string(), result.size());
471    return NO_ERROR;
472}
473
474status_t AudioPolicyService::onTransact(
475        uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
476{
477    return BnAudioPolicyService::onTransact(code, data, reply, flags);
478}
479
480
481// ----------------------------------------------------------------------------
482void AudioPolicyService::instantiate() {
483    defaultServiceManager()->addService(
484            String16("media.audio_policy"), new AudioPolicyService());
485}
486
487
488// ----------------------------------------------------------------------------
489// AudioPolicyClientInterface implementation
490// ----------------------------------------------------------------------------
491
492
493audio_io_handle_t AudioPolicyService::openOutput(uint32_t *pDevices,
494                                uint32_t *pSamplingRate,
495                                uint32_t *pFormat,
496                                uint32_t *pChannels,
497                                uint32_t *pLatencyMs,
498                                AudioSystem::output_flags flags)
499{
500    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
501    if (af == 0) {
502        LOGW("openOutput() could not get AudioFlinger");
503        return 0;
504    }
505
506    return af->openOutput(pDevices,
507                          pSamplingRate,
508                          (uint32_t *)pFormat,
509                          pChannels,
510                          pLatencyMs,
511                          flags);
512}
513
514audio_io_handle_t AudioPolicyService::openDuplicateOutput(audio_io_handle_t output1,
515                                                          audio_io_handle_t output2)
516{
517    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
518    if (af == 0) {
519        LOGW("openDuplicateOutput() could not get AudioFlinger");
520        return 0;
521    }
522    return af->openDuplicateOutput(output1, output2);
523}
524
525status_t AudioPolicyService::closeOutput(audio_io_handle_t output)
526{
527    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
528    if (af == 0) return PERMISSION_DENIED;
529
530    return af->closeOutput(output);
531}
532
533
534status_t AudioPolicyService::suspendOutput(audio_io_handle_t output)
535{
536    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
537    if (af == 0) {
538        LOGW("suspendOutput() could not get AudioFlinger");
539        return PERMISSION_DENIED;
540    }
541
542    return af->suspendOutput(output);
543}
544
545status_t AudioPolicyService::restoreOutput(audio_io_handle_t output)
546{
547    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
548    if (af == 0) {
549        LOGW("restoreOutput() could not get AudioFlinger");
550        return PERMISSION_DENIED;
551    }
552
553    return af->restoreOutput(output);
554}
555
556audio_io_handle_t AudioPolicyService::openInput(uint32_t *pDevices,
557                                uint32_t *pSamplingRate,
558                                uint32_t *pFormat,
559                                uint32_t *pChannels,
560                                uint32_t acoustics)
561{
562    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
563    if (af == 0) {
564        LOGW("openInput() could not get AudioFlinger");
565        return 0;
566    }
567
568    return af->openInput(pDevices, pSamplingRate, (uint32_t *)pFormat, pChannels, acoustics);
569}
570
571status_t AudioPolicyService::closeInput(audio_io_handle_t input)
572{
573    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
574    if (af == 0) return PERMISSION_DENIED;
575
576    return af->closeInput(input);
577}
578
579status_t AudioPolicyService::setStreamVolume(AudioSystem::stream_type stream,
580                                             float volume,
581                                             audio_io_handle_t output,
582                                             int delayMs)
583{
584    return mAudioCommandThread->volumeCommand((int)stream, volume, (int)output, delayMs);
585}
586
587status_t AudioPolicyService::setStreamOutput(AudioSystem::stream_type stream,
588                                             audio_io_handle_t output)
589{
590    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
591    if (af == 0) return PERMISSION_DENIED;
592
593    return af->setStreamOutput(stream, output);
594}
595
596status_t AudioPolicyService::moveEffects(int session, audio_io_handle_t srcOutput,
597                                               audio_io_handle_t dstOutput)
598{
599    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
600    if (af == 0) return PERMISSION_DENIED;
601
602    return af->moveEffects(session, (int)srcOutput, (int)dstOutput);
603}
604
605void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
606                                       const String8& keyValuePairs,
607                                       int delayMs)
608{
609    mAudioCommandThread->parametersCommand((int)ioHandle, keyValuePairs, delayMs);
610}
611
612String8 AudioPolicyService::getParameters(audio_io_handle_t ioHandle, const String8& keys)
613{
614    String8 result = AudioSystem::getParameters(ioHandle, keys);
615    return result;
616}
617
618status_t AudioPolicyService::startTone(ToneGenerator::tone_type tone,
619                                       AudioSystem::stream_type stream)
620{
621    mTonePlaybackThread->startToneCommand(tone, stream);
622    return NO_ERROR;
623}
624
625status_t AudioPolicyService::stopTone()
626{
627    mTonePlaybackThread->stopToneCommand();
628    return NO_ERROR;
629}
630
631status_t AudioPolicyService::setVoiceVolume(float volume, int delayMs)
632{
633    return mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
634}
635
636// -----------  AudioPolicyService::AudioCommandThread implementation ----------
637
638AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name)
639    : Thread(false), mName(name)
640{
641    mpToneGenerator = NULL;
642}
643
644
645AudioPolicyService::AudioCommandThread::~AudioCommandThread()
646{
647    if (mName != "" && !mAudioCommands.isEmpty()) {
648        release_wake_lock(mName.string());
649    }
650    mAudioCommands.clear();
651    if (mpToneGenerator != NULL) delete mpToneGenerator;
652}
653
654void AudioPolicyService::AudioCommandThread::onFirstRef()
655{
656    if (mName != "") {
657        run(mName.string(), ANDROID_PRIORITY_AUDIO);
658    } else {
659        run("AudioCommandThread", ANDROID_PRIORITY_AUDIO);
660    }
661}
662
663bool AudioPolicyService::AudioCommandThread::threadLoop()
664{
665    nsecs_t waitTime = INT64_MAX;
666
667    mLock.lock();
668    while (!exitPending())
669    {
670        while(!mAudioCommands.isEmpty()) {
671            nsecs_t curTime = systemTime();
672            // commands are sorted by increasing time stamp: execute them from index 0 and up
673            if (mAudioCommands[0]->mTime <= curTime) {
674                AudioCommand *command = mAudioCommands[0];
675                mAudioCommands.removeAt(0);
676                mLastCommand = *command;
677
678                switch (command->mCommand) {
679                case START_TONE: {
680                    mLock.unlock();
681                    ToneData *data = (ToneData *)command->mParam;
682                    LOGV("AudioCommandThread() processing start tone %d on stream %d",
683                            data->mType, data->mStream);
684                    if (mpToneGenerator != NULL)
685                        delete mpToneGenerator;
686                    mpToneGenerator = new ToneGenerator(data->mStream, 1.0);
687                    mpToneGenerator->startTone(data->mType);
688                    delete data;
689                    mLock.lock();
690                    }break;
691                case STOP_TONE: {
692                    mLock.unlock();
693                    LOGV("AudioCommandThread() processing stop tone");
694                    if (mpToneGenerator != NULL) {
695                        mpToneGenerator->stopTone();
696                        delete mpToneGenerator;
697                        mpToneGenerator = NULL;
698                    }
699                    mLock.lock();
700                    }break;
701                case SET_VOLUME: {
702                    VolumeData *data = (VolumeData *)command->mParam;
703                    LOGV("AudioCommandThread() processing set volume stream %d, \
704                            volume %f, output %d", data->mStream, data->mVolume, data->mIO);
705                    command->mStatus = AudioSystem::setStreamVolume(data->mStream,
706                                                                    data->mVolume,
707                                                                    data->mIO);
708                    if (command->mWaitStatus) {
709                        command->mCond.signal();
710                        mWaitWorkCV.wait(mLock);
711                    }
712                    delete data;
713                    }break;
714                case SET_PARAMETERS: {
715                     ParametersData *data = (ParametersData *)command->mParam;
716                     LOGV("AudioCommandThread() processing set parameters string %s, io %d",
717                             data->mKeyValuePairs.string(), data->mIO);
718                     command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
719                     if (command->mWaitStatus) {
720                         command->mCond.signal();
721                         mWaitWorkCV.wait(mLock);
722                     }
723                     delete data;
724                     }break;
725                case SET_VOICE_VOLUME: {
726                    VoiceVolumeData *data = (VoiceVolumeData *)command->mParam;
727                    LOGV("AudioCommandThread() processing set voice volume volume %f",
728                            data->mVolume);
729                    command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
730                    if (command->mWaitStatus) {
731                        command->mCond.signal();
732                        mWaitWorkCV.wait(mLock);
733                    }
734                    delete data;
735                    }break;
736                default:
737                    LOGW("AudioCommandThread() unknown command %d", command->mCommand);
738                }
739                delete command;
740                waitTime = INT64_MAX;
741            } else {
742                waitTime = mAudioCommands[0]->mTime - curTime;
743                break;
744            }
745        }
746        // release delayed commands wake lock
747        if (mName != "" && mAudioCommands.isEmpty()) {
748            release_wake_lock(mName.string());
749        }
750        LOGV("AudioCommandThread() going to sleep");
751        mWaitWorkCV.waitRelative(mLock, waitTime);
752        LOGV("AudioCommandThread() waking up");
753    }
754    mLock.unlock();
755    return false;
756}
757
758status_t AudioPolicyService::AudioCommandThread::dump(int fd)
759{
760    const size_t SIZE = 256;
761    char buffer[SIZE];
762    String8 result;
763
764    snprintf(buffer, SIZE, "AudioCommandThread %p Dump\n", this);
765    result.append(buffer);
766    write(fd, result.string(), result.size());
767
768    bool locked = tryLock(mLock);
769    if (!locked) {
770        String8 result2(kCmdDeadlockedString);
771        write(fd, result2.string(), result2.size());
772    }
773
774    snprintf(buffer, SIZE, "- Commands:\n");
775    result = String8(buffer);
776    result.append("   Command Time        Wait pParam\n");
777    for (int i = 0; i < (int)mAudioCommands.size(); i++) {
778        mAudioCommands[i]->dump(buffer, SIZE);
779        result.append(buffer);
780    }
781    result.append("  Last Command\n");
782    mLastCommand.dump(buffer, SIZE);
783    result.append(buffer);
784
785    write(fd, result.string(), result.size());
786
787    if (locked) mLock.unlock();
788
789    return NO_ERROR;
790}
791
792void AudioPolicyService::AudioCommandThread::startToneCommand(int type, int stream)
793{
794    AudioCommand *command = new AudioCommand();
795    command->mCommand = START_TONE;
796    ToneData *data = new ToneData();
797    data->mType = type;
798    data->mStream = stream;
799    command->mParam = (void *)data;
800    command->mWaitStatus = false;
801    Mutex::Autolock _l(mLock);
802    insertCommand_l(command);
803    LOGV("AudioCommandThread() adding tone start type %d, stream %d", type, stream);
804    mWaitWorkCV.signal();
805}
806
807void AudioPolicyService::AudioCommandThread::stopToneCommand()
808{
809    AudioCommand *command = new AudioCommand();
810    command->mCommand = STOP_TONE;
811    command->mParam = NULL;
812    command->mWaitStatus = false;
813    Mutex::Autolock _l(mLock);
814    insertCommand_l(command);
815    LOGV("AudioCommandThread() adding tone stop");
816    mWaitWorkCV.signal();
817}
818
819status_t AudioPolicyService::AudioCommandThread::volumeCommand(int stream,
820                                                               float volume,
821                                                               int output,
822                                                               int delayMs)
823{
824    status_t status = NO_ERROR;
825
826    AudioCommand *command = new AudioCommand();
827    command->mCommand = SET_VOLUME;
828    VolumeData *data = new VolumeData();
829    data->mStream = stream;
830    data->mVolume = volume;
831    data->mIO = output;
832    command->mParam = data;
833    if (delayMs == 0) {
834        command->mWaitStatus = true;
835    } else {
836        command->mWaitStatus = false;
837    }
838    Mutex::Autolock _l(mLock);
839    insertCommand_l(command, delayMs);
840    LOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
841            stream, volume, output);
842    mWaitWorkCV.signal();
843    if (command->mWaitStatus) {
844        command->mCond.wait(mLock);
845        status =  command->mStatus;
846        mWaitWorkCV.signal();
847    }
848    return status;
849}
850
851status_t AudioPolicyService::AudioCommandThread::parametersCommand(int ioHandle,
852                                                                   const String8& keyValuePairs,
853                                                                   int delayMs)
854{
855    status_t status = NO_ERROR;
856
857    AudioCommand *command = new AudioCommand();
858    command->mCommand = SET_PARAMETERS;
859    ParametersData *data = new ParametersData();
860    data->mIO = ioHandle;
861    data->mKeyValuePairs = keyValuePairs;
862    command->mParam = data;
863    if (delayMs == 0) {
864        command->mWaitStatus = true;
865    } else {
866        command->mWaitStatus = false;
867    }
868    Mutex::Autolock _l(mLock);
869    insertCommand_l(command, delayMs);
870    LOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
871            keyValuePairs.string(), ioHandle, delayMs);
872    mWaitWorkCV.signal();
873    if (command->mWaitStatus) {
874        command->mCond.wait(mLock);
875        status =  command->mStatus;
876        mWaitWorkCV.signal();
877    }
878    return status;
879}
880
881status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
882{
883    status_t status = NO_ERROR;
884
885    AudioCommand *command = new AudioCommand();
886    command->mCommand = SET_VOICE_VOLUME;
887    VoiceVolumeData *data = new VoiceVolumeData();
888    data->mVolume = volume;
889    command->mParam = data;
890    if (delayMs == 0) {
891        command->mWaitStatus = true;
892    } else {
893        command->mWaitStatus = false;
894    }
895    Mutex::Autolock _l(mLock);
896    insertCommand_l(command, delayMs);
897    LOGV("AudioCommandThread() adding set voice volume volume %f", volume);
898    mWaitWorkCV.signal();
899    if (command->mWaitStatus) {
900        command->mCond.wait(mLock);
901        status =  command->mStatus;
902        mWaitWorkCV.signal();
903    }
904    return status;
905}
906
907// insertCommand_l() must be called with mLock held
908void AudioPolicyService::AudioCommandThread::insertCommand_l(AudioCommand *command, int delayMs)
909{
910    ssize_t i;
911    Vector <AudioCommand *> removedCommands;
912
913    command->mTime = systemTime() + milliseconds(delayMs);
914
915    // acquire wake lock to make sure delayed commands are processed
916    if (mName != "" && mAudioCommands.isEmpty()) {
917        acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.string());
918    }
919
920    // check same pending commands with later time stamps and eliminate them
921    for (i = mAudioCommands.size()-1; i >= 0; i--) {
922        AudioCommand *command2 = mAudioCommands[i];
923        // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
924        if (command2->mTime <= command->mTime) break;
925        if (command2->mCommand != command->mCommand) continue;
926
927        switch (command->mCommand) {
928        case SET_PARAMETERS: {
929            ParametersData *data = (ParametersData *)command->mParam;
930            ParametersData *data2 = (ParametersData *)command2->mParam;
931            if (data->mIO != data2->mIO) break;
932            LOGV("Comparing parameter command %s to new command %s",
933                    data2->mKeyValuePairs.string(), data->mKeyValuePairs.string());
934            AudioParameter param = AudioParameter(data->mKeyValuePairs);
935            AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
936            for (size_t j = 0; j < param.size(); j++) {
937               String8 key;
938               String8 value;
939               param.getAt(j, key, value);
940               for (size_t k = 0; k < param2.size(); k++) {
941                  String8 key2;
942                  String8 value2;
943                  param2.getAt(k, key2, value2);
944                  if (key2 == key) {
945                      param2.remove(key2);
946                      LOGV("Filtering out parameter %s", key2.string());
947                      break;
948                  }
949               }
950            }
951            // if all keys have been filtered out, remove the command.
952            // otherwise, update the key value pairs
953            if (param2.size() == 0) {
954                removedCommands.add(command2);
955            } else {
956                data2->mKeyValuePairs = param2.toString();
957            }
958        } break;
959
960        case SET_VOLUME: {
961            VolumeData *data = (VolumeData *)command->mParam;
962            VolumeData *data2 = (VolumeData *)command2->mParam;
963            if (data->mIO != data2->mIO) break;
964            if (data->mStream != data2->mStream) break;
965            LOGV("Filtering out volume command on output %d for stream %d",
966                    data->mIO, data->mStream);
967            removedCommands.add(command2);
968        } break;
969        case START_TONE:
970        case STOP_TONE:
971        default:
972            break;
973        }
974    }
975
976    // remove filtered commands
977    for (size_t j = 0; j < removedCommands.size(); j++) {
978        // removed commands always have time stamps greater than current command
979        for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
980            if (mAudioCommands[k] == removedCommands[j]) {
981                LOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
982                mAudioCommands.removeAt(k);
983                break;
984            }
985        }
986    }
987    removedCommands.clear();
988
989    // insert command at the right place according to its time stamp
990    LOGV("inserting command: %d at index %d, num commands %d",
991            command->mCommand, (int)i+1, mAudioCommands.size());
992    mAudioCommands.insertAt(command, i + 1);
993}
994
995void AudioPolicyService::AudioCommandThread::exit()
996{
997    LOGV("AudioCommandThread::exit");
998    {
999        AutoMutex _l(mLock);
1000        requestExit();
1001        mWaitWorkCV.signal();
1002    }
1003    requestExitAndWait();
1004}
1005
1006void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
1007{
1008    snprintf(buffer, size, "   %02d      %06d.%03d  %01u    %p\n",
1009            mCommand,
1010            (int)ns2s(mTime),
1011            (int)ns2ms(mTime)%1000,
1012            mWaitStatus,
1013            mParam);
1014}
1015
1016}; // namespace android
1017