AudioPolicyService.cpp revision 9fda4b87441fe17d90d8144639c9de6d9022c3c0
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 "ServiceUtilities.h"
34#include <cutils/properties.h>
35#include <hardware_legacy/power.h>
36#include <media/AudioEffect.h>
37#include <media/EffectsFactoryApi.h>
38
39#include <hardware/hardware.h>
40#include <system/audio.h>
41#include <system/audio_policy.h>
42#include <hardware/audio_policy.h>
43#include <audio_effects/audio_effects_conf.h>
44
45namespace android {
46
47static const char kDeadlockedString[] = "AudioPolicyService may be deadlocked\n";
48static const char kCmdDeadlockedString[] = "AudioPolicyService command thread may be deadlocked\n";
49
50static const int kDumpLockRetries = 50;
51static const int kDumpLockSleepUs = 20000;
52
53namespace {
54    extern struct audio_policy_service_ops aps_ops;
55};
56
57// ----------------------------------------------------------------------------
58
59AudioPolicyService::AudioPolicyService()
60    : BnAudioPolicyService() , mpAudioPolicyDev(NULL) , mpAudioPolicy(NULL)
61{
62    char value[PROPERTY_VALUE_MAX];
63    const struct hw_module_t *module;
64    int forced_val;
65    int rc;
66
67    Mutex::Autolock _l(mLock);
68
69    // start tone playback thread
70    mTonePlaybackThread = new AudioCommandThread(String8(""));
71    // start audio commands thread
72    mAudioCommandThread = new AudioCommandThread(String8("ApmCommandThread"));
73
74    /* instantiate the audio policy manager */
75    rc = hw_get_module(AUDIO_POLICY_HARDWARE_MODULE_ID, &module);
76    if (rc)
77        return;
78
79    rc = audio_policy_dev_open(module, &mpAudioPolicyDev);
80    ALOGE_IF(rc, "couldn't open audio policy device (%s)", strerror(-rc));
81    if (rc)
82        return;
83
84    rc = mpAudioPolicyDev->create_audio_policy(mpAudioPolicyDev, &aps_ops, this,
85                                               &mpAudioPolicy);
86    ALOGE_IF(rc, "couldn't create audio policy (%s)", strerror(-rc));
87    if (rc)
88        return;
89
90    rc = mpAudioPolicy->init_check(mpAudioPolicy);
91    ALOGE_IF(rc, "couldn't init_check the audio policy (%s)", strerror(-rc));
92    if (rc)
93        return;
94
95    property_get("ro.camera.sound.forced", value, "0");
96    forced_val = strtol(value, NULL, 0);
97    mpAudioPolicy->set_can_mute_enforced_audible(mpAudioPolicy, !forced_val);
98
99    ALOGI("Loaded audio policy from %s (%s)", module->name, module->id);
100
101    // load audio pre processing modules
102    if (access(AUDIO_EFFECT_VENDOR_CONFIG_FILE, R_OK) == 0) {
103        loadPreProcessorConfig(AUDIO_EFFECT_VENDOR_CONFIG_FILE);
104    } else if (access(AUDIO_EFFECT_DEFAULT_CONFIG_FILE, R_OK) == 0) {
105        loadPreProcessorConfig(AUDIO_EFFECT_DEFAULT_CONFIG_FILE);
106    }
107}
108
109AudioPolicyService::~AudioPolicyService()
110{
111    mTonePlaybackThread->exit();
112    mTonePlaybackThread.clear();
113    mAudioCommandThread->exit();
114    mAudioCommandThread.clear();
115
116
117    // release audio pre processing resources
118    for (size_t i = 0; i < mInputSources.size(); i++) {
119        delete mInputSources.valueAt(i);
120    }
121    mInputSources.clear();
122
123    for (size_t i = 0; i < mInputs.size(); i++) {
124        mInputs.valueAt(i)->mEffects.clear();
125        delete mInputs.valueAt(i);
126    }
127    mInputs.clear();
128
129    if (mpAudioPolicy != NULL && mpAudioPolicyDev != NULL)
130        mpAudioPolicyDev->destroy_audio_policy(mpAudioPolicyDev, mpAudioPolicy);
131    if (mpAudioPolicyDev != NULL)
132        audio_policy_dev_close(mpAudioPolicyDev);
133}
134
135status_t AudioPolicyService::setDeviceConnectionState(audio_devices_t device,
136                                                  audio_policy_dev_state_t state,
137                                                  const char *device_address)
138{
139    if (mpAudioPolicy == NULL) {
140        return NO_INIT;
141    }
142    if (!settingsAllowed()) {
143        return PERMISSION_DENIED;
144    }
145    if (!audio_is_output_device(device) && !audio_is_input_device(device)) {
146        return BAD_VALUE;
147    }
148    if (state != AUDIO_POLICY_DEVICE_STATE_AVAILABLE &&
149            state != AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
150        return BAD_VALUE;
151    }
152
153    ALOGV("setDeviceConnectionState() tid %d", gettid());
154    Mutex::Autolock _l(mLock);
155    return mpAudioPolicy->set_device_connection_state(mpAudioPolicy, device,
156                                                      state, device_address);
157}
158
159audio_policy_dev_state_t AudioPolicyService::getDeviceConnectionState(
160                                                              audio_devices_t device,
161                                                              const char *device_address)
162{
163    if (mpAudioPolicy == NULL) {
164        return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
165    }
166    return mpAudioPolicy->get_device_connection_state(mpAudioPolicy, device,
167                                                      device_address);
168}
169
170status_t AudioPolicyService::setPhoneState(audio_mode_t state)
171{
172    if (mpAudioPolicy == NULL) {
173        return NO_INIT;
174    }
175    if (!settingsAllowed()) {
176        return PERMISSION_DENIED;
177    }
178    if (uint32_t(state) >= AUDIO_MODE_CNT) {
179        return BAD_VALUE;
180    }
181
182    ALOGV("setPhoneState() tid %d", gettid());
183
184    // TODO: check if it is more appropriate to do it in platform specific policy manager
185    AudioSystem::setMode(state);
186
187    Mutex::Autolock _l(mLock);
188    mpAudioPolicy->set_phone_state(mpAudioPolicy, state);
189    return NO_ERROR;
190}
191
192status_t AudioPolicyService::setForceUse(audio_policy_force_use_t usage,
193                                         audio_policy_forced_cfg_t config)
194{
195    if (mpAudioPolicy == NULL) {
196        return NO_INIT;
197    }
198    if (!settingsAllowed()) {
199        return PERMISSION_DENIED;
200    }
201    if (usage < 0 || usage >= AUDIO_POLICY_FORCE_USE_CNT) {
202        return BAD_VALUE;
203    }
204    if (config < 0 || config >= AUDIO_POLICY_FORCE_CFG_CNT) {
205        return BAD_VALUE;
206    }
207    ALOGV("setForceUse() tid %d", gettid());
208    Mutex::Autolock _l(mLock);
209    mpAudioPolicy->set_force_use(mpAudioPolicy, usage, config);
210    return NO_ERROR;
211}
212
213audio_policy_forced_cfg_t AudioPolicyService::getForceUse(audio_policy_force_use_t usage)
214{
215    if (mpAudioPolicy == NULL) {
216        return AUDIO_POLICY_FORCE_NONE;
217    }
218    if (usage < 0 || usage >= AUDIO_POLICY_FORCE_USE_CNT) {
219        return AUDIO_POLICY_FORCE_NONE;
220    }
221    return mpAudioPolicy->get_force_use(mpAudioPolicy, usage);
222}
223
224audio_io_handle_t AudioPolicyService::getOutput(audio_stream_type_t stream,
225                                    uint32_t samplingRate,
226                                    audio_format_t format,
227                                    uint32_t channels,
228                                    audio_policy_output_flags_t flags)
229{
230    if (mpAudioPolicy == NULL) {
231        return 0;
232    }
233    ALOGV("getOutput() tid %d", gettid());
234    Mutex::Autolock _l(mLock);
235    return mpAudioPolicy->get_output(mpAudioPolicy, stream, samplingRate, format, channels, flags);
236}
237
238status_t AudioPolicyService::startOutput(audio_io_handle_t output,
239                                         audio_stream_type_t stream,
240                                         int session)
241{
242    if (mpAudioPolicy == NULL) {
243        return NO_INIT;
244    }
245    ALOGV("startOutput() tid %d", gettid());
246    Mutex::Autolock _l(mLock);
247    return mpAudioPolicy->start_output(mpAudioPolicy, output, stream, session);
248}
249
250status_t AudioPolicyService::stopOutput(audio_io_handle_t output,
251                                        audio_stream_type_t stream,
252                                        int session)
253{
254    if (mpAudioPolicy == NULL) {
255        return NO_INIT;
256    }
257    ALOGV("stopOutput() tid %d", gettid());
258    Mutex::Autolock _l(mLock);
259    return mpAudioPolicy->stop_output(mpAudioPolicy, output, stream, session);
260}
261
262void AudioPolicyService::releaseOutput(audio_io_handle_t output)
263{
264    if (mpAudioPolicy == NULL) {
265        return;
266    }
267    ALOGV("releaseOutput() tid %d", gettid());
268    Mutex::Autolock _l(mLock);
269    mpAudioPolicy->release_output(mpAudioPolicy, output);
270}
271
272audio_io_handle_t AudioPolicyService::getInput(audio_source_t inputSource,
273                                    uint32_t samplingRate,
274                                    audio_format_t format,
275                                    uint32_t channels,
276                                    audio_in_acoustics_t acoustics,
277                                    int audioSession)
278{
279    if (mpAudioPolicy == NULL) {
280        return 0;
281    }
282    // already checked by client, but double-check in case the client wrapper is bypassed
283    if (uint32_t(inputSource) >= AUDIO_SOURCE_CNT) {
284        return 0;
285    }
286    Mutex::Autolock _l(mLock);
287    audio_io_handle_t input = mpAudioPolicy->get_input(mpAudioPolicy, inputSource, samplingRate,
288                                                       format, channels, acoustics);
289
290    if (input == 0) {
291        return input;
292    }
293    // create audio pre processors according to input source
294    ssize_t index = mInputSources.indexOfKey(inputSource);
295    if (index < 0) {
296        return input;
297    }
298    ssize_t idx = mInputs.indexOfKey(input);
299    InputDesc *inputDesc;
300    if (idx < 0) {
301        inputDesc = new InputDesc();
302        inputDesc->mSessionId = audioSession;
303        mInputs.add(input, inputDesc);
304    } else {
305        inputDesc = mInputs.valueAt(idx);
306    }
307
308    Vector <EffectDesc *> effects = mInputSources.valueAt(index)->mEffects;
309    for (size_t i = 0; i < effects.size(); i++) {
310        EffectDesc *effect = effects[i];
311        sp<AudioEffect> fx = new AudioEffect(NULL, &effect->mUuid, -1, 0, 0, audioSession, input);
312        status_t status = fx->initCheck();
313        if (status != NO_ERROR && status != ALREADY_EXISTS) {
314            ALOGW("Failed to create Fx %s on input %d", effect->mName, input);
315            // fx goes out of scope and strong ref on AudioEffect is released
316            continue;
317        }
318        for (size_t j = 0; j < effect->mParams.size(); j++) {
319            fx->setParameter(effect->mParams[j]);
320        }
321        inputDesc->mEffects.add(fx);
322    }
323    setPreProcessorEnabled(inputDesc, true);
324    return input;
325}
326
327status_t AudioPolicyService::startInput(audio_io_handle_t input)
328{
329    if (mpAudioPolicy == NULL) {
330        return NO_INIT;
331    }
332    Mutex::Autolock _l(mLock);
333
334    return mpAudioPolicy->start_input(mpAudioPolicy, input);
335}
336
337status_t AudioPolicyService::stopInput(audio_io_handle_t input)
338{
339    if (mpAudioPolicy == NULL) {
340        return NO_INIT;
341    }
342    Mutex::Autolock _l(mLock);
343
344    return mpAudioPolicy->stop_input(mpAudioPolicy, input);
345}
346
347void AudioPolicyService::releaseInput(audio_io_handle_t input)
348{
349    if (mpAudioPolicy == NULL) {
350        return;
351    }
352    Mutex::Autolock _l(mLock);
353    mpAudioPolicy->release_input(mpAudioPolicy, input);
354
355    ssize_t index = mInputs.indexOfKey(input);
356    if (index < 0) {
357        return;
358    }
359    InputDesc *inputDesc = mInputs.valueAt(index);
360    setPreProcessorEnabled(inputDesc, false);
361    inputDesc->mEffects.clear();
362    delete inputDesc;
363    mInputs.removeItemsAt(index);
364}
365
366status_t AudioPolicyService::initStreamVolume(audio_stream_type_t stream,
367                                            int indexMin,
368                                            int indexMax)
369{
370    if (mpAudioPolicy == NULL) {
371        return NO_INIT;
372    }
373    if (!settingsAllowed()) {
374        return PERMISSION_DENIED;
375    }
376    if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
377        return BAD_VALUE;
378    }
379    mpAudioPolicy->init_stream_volume(mpAudioPolicy, stream, indexMin, indexMax);
380    return NO_ERROR;
381}
382
383status_t AudioPolicyService::setStreamVolumeIndex(audio_stream_type_t stream,
384                                                  int index,
385                                                  audio_devices_t device)
386{
387    if (mpAudioPolicy == NULL) {
388        return NO_INIT;
389    }
390    if (!settingsAllowed()) {
391        return PERMISSION_DENIED;
392    }
393    if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
394        return BAD_VALUE;
395    }
396
397    if (mpAudioPolicy->set_stream_volume_index_for_device) {
398        return mpAudioPolicy->set_stream_volume_index_for_device(mpAudioPolicy,
399                                                                stream,
400                                                                index,
401                                                                device);
402    } else {
403        return mpAudioPolicy->set_stream_volume_index(mpAudioPolicy, stream, index);
404    }
405}
406
407status_t AudioPolicyService::getStreamVolumeIndex(audio_stream_type_t stream,
408                                                  int *index,
409                                                  audio_devices_t device)
410{
411    if (mpAudioPolicy == NULL) {
412        return NO_INIT;
413    }
414    if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
415        return BAD_VALUE;
416    }
417    if (mpAudioPolicy->get_stream_volume_index_for_device) {
418        return mpAudioPolicy->get_stream_volume_index_for_device(mpAudioPolicy,
419                                                                stream,
420                                                                index,
421                                                                device);
422    } else {
423        return mpAudioPolicy->get_stream_volume_index(mpAudioPolicy, stream, index);
424    }
425}
426
427uint32_t AudioPolicyService::getStrategyForStream(audio_stream_type_t stream)
428{
429    if (mpAudioPolicy == NULL) {
430        return 0;
431    }
432    return mpAudioPolicy->get_strategy_for_stream(mpAudioPolicy, stream);
433}
434
435uint32_t AudioPolicyService::getDevicesForStream(audio_stream_type_t stream)
436{
437    if (mpAudioPolicy == NULL) {
438        return 0;
439    }
440    return mpAudioPolicy->get_devices_for_stream(mpAudioPolicy, stream);
441}
442
443audio_io_handle_t AudioPolicyService::getOutputForEffect(effect_descriptor_t *desc)
444{
445    if (mpAudioPolicy == NULL) {
446        return NO_INIT;
447    }
448    Mutex::Autolock _l(mLock);
449    return mpAudioPolicy->get_output_for_effect(mpAudioPolicy, desc);
450}
451
452status_t AudioPolicyService::registerEffect(effect_descriptor_t *desc,
453                                audio_io_handle_t io,
454                                uint32_t strategy,
455                                int session,
456                                int id)
457{
458    if (mpAudioPolicy == NULL) {
459        return NO_INIT;
460    }
461    return mpAudioPolicy->register_effect(mpAudioPolicy, desc, io, strategy, session, id);
462}
463
464status_t AudioPolicyService::unregisterEffect(int id)
465{
466    if (mpAudioPolicy == NULL) {
467        return NO_INIT;
468    }
469    return mpAudioPolicy->unregister_effect(mpAudioPolicy, id);
470}
471
472status_t AudioPolicyService::setEffectEnabled(int id, bool enabled)
473{
474    if (mpAudioPolicy == NULL) {
475        return NO_INIT;
476    }
477    return mpAudioPolicy->set_effect_enabled(mpAudioPolicy, id, enabled);
478}
479
480bool AudioPolicyService::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
481{
482    if (mpAudioPolicy == NULL) {
483        return 0;
484    }
485    Mutex::Autolock _l(mLock);
486    return mpAudioPolicy->is_stream_active(mpAudioPolicy, stream, inPastMs);
487}
488
489status_t AudioPolicyService::queryDefaultPreProcessing(int audioSession,
490                                                       effect_descriptor_t *descriptors,
491                                                       uint32_t *count)
492{
493
494    if (mpAudioPolicy == NULL) {
495        *count = 0;
496        return NO_INIT;
497    }
498    Mutex::Autolock _l(mLock);
499    status_t status = NO_ERROR;
500
501    size_t index;
502    for (index = 0; index < mInputs.size(); index++) {
503        if (mInputs.valueAt(index)->mSessionId == audioSession) {
504            break;
505        }
506    }
507    if (index == mInputs.size()) {
508        *count = 0;
509        return BAD_VALUE;
510    }
511    Vector< sp<AudioEffect> > effects = mInputs.valueAt(index)->mEffects;
512
513    for (size_t i = 0; i < effects.size(); i++) {
514        effect_descriptor_t desc = effects[i]->descriptor();
515        if (i < *count) {
516            memcpy(descriptors + i, &desc, sizeof(effect_descriptor_t));
517        }
518    }
519    if (effects.size() > *count) {
520        status = NO_MEMORY;
521    }
522    *count = effects.size();
523    return status;
524}
525
526void AudioPolicyService::binderDied(const wp<IBinder>& who) {
527    ALOGW("binderDied() %p, tid %d, calling pid %d", who.unsafe_get(), gettid(),
528            IPCThreadState::self()->getCallingPid());
529}
530
531static bool tryLock(Mutex& mutex)
532{
533    bool locked = false;
534    for (int i = 0; i < kDumpLockRetries; ++i) {
535        if (mutex.tryLock() == NO_ERROR) {
536            locked = true;
537            break;
538        }
539        usleep(kDumpLockSleepUs);
540    }
541    return locked;
542}
543
544status_t AudioPolicyService::dumpInternals(int fd)
545{
546    const size_t SIZE = 256;
547    char buffer[SIZE];
548    String8 result;
549
550    snprintf(buffer, SIZE, "PolicyManager Interface: %p\n", mpAudioPolicy);
551    result.append(buffer);
552    snprintf(buffer, SIZE, "Command Thread: %p\n", mAudioCommandThread.get());
553    result.append(buffer);
554    snprintf(buffer, SIZE, "Tones Thread: %p\n", mTonePlaybackThread.get());
555    result.append(buffer);
556
557    write(fd, result.string(), result.size());
558    return NO_ERROR;
559}
560
561status_t AudioPolicyService::dump(int fd, const Vector<String16>& args)
562{
563    if (!dumpAllowed()) {
564        dumpPermissionDenial(fd);
565    } else {
566        bool locked = tryLock(mLock);
567        if (!locked) {
568            String8 result(kDeadlockedString);
569            write(fd, result.string(), result.size());
570        }
571
572        dumpInternals(fd);
573        if (mAudioCommandThread != 0) {
574            mAudioCommandThread->dump(fd);
575        }
576        if (mTonePlaybackThread != 0) {
577            mTonePlaybackThread->dump(fd);
578        }
579
580        if (mpAudioPolicy) {
581            mpAudioPolicy->dump(mpAudioPolicy, fd);
582        }
583
584        if (locked) mLock.unlock();
585    }
586    return NO_ERROR;
587}
588
589status_t AudioPolicyService::dumpPermissionDenial(int fd)
590{
591    const size_t SIZE = 256;
592    char buffer[SIZE];
593    String8 result;
594    snprintf(buffer, SIZE, "Permission Denial: "
595            "can't dump AudioPolicyService from pid=%d, uid=%d\n",
596            IPCThreadState::self()->getCallingPid(),
597            IPCThreadState::self()->getCallingUid());
598    result.append(buffer);
599    write(fd, result.string(), result.size());
600    return NO_ERROR;
601}
602
603void AudioPolicyService::setPreProcessorEnabled(InputDesc *inputDesc, bool enabled)
604{
605    Vector<sp<AudioEffect> > fxVector = inputDesc->mEffects;
606    for (size_t i = 0; i < fxVector.size(); i++) {
607        sp<AudioEffect> fx = fxVector.itemAt(i);
608        fx->setEnabled(enabled);
609    }
610}
611
612status_t AudioPolicyService::onTransact(
613        uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
614{
615    return BnAudioPolicyService::onTransact(code, data, reply, flags);
616}
617
618
619// -----------  AudioPolicyService::AudioCommandThread implementation ----------
620
621AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name)
622    : Thread(false), mName(name)
623{
624    mpToneGenerator = NULL;
625}
626
627
628AudioPolicyService::AudioCommandThread::~AudioCommandThread()
629{
630    if (mName != "" && !mAudioCommands.isEmpty()) {
631        release_wake_lock(mName.string());
632    }
633    mAudioCommands.clear();
634    delete mpToneGenerator;
635}
636
637void AudioPolicyService::AudioCommandThread::onFirstRef()
638{
639    if (mName != "") {
640        run(mName.string(), ANDROID_PRIORITY_AUDIO);
641    } else {
642        run("AudioCommandThread", ANDROID_PRIORITY_AUDIO);
643    }
644}
645
646bool AudioPolicyService::AudioCommandThread::threadLoop()
647{
648    nsecs_t waitTime = INT64_MAX;
649
650    mLock.lock();
651    while (!exitPending())
652    {
653        while(!mAudioCommands.isEmpty()) {
654            nsecs_t curTime = systemTime();
655            // commands are sorted by increasing time stamp: execute them from index 0 and up
656            if (mAudioCommands[0]->mTime <= curTime) {
657                AudioCommand *command = mAudioCommands[0];
658                mAudioCommands.removeAt(0);
659                mLastCommand = *command;
660
661                switch (command->mCommand) {
662                case START_TONE: {
663                    mLock.unlock();
664                    ToneData *data = (ToneData *)command->mParam;
665                    ALOGV("AudioCommandThread() processing start tone %d on stream %d",
666                            data->mType, data->mStream);
667                    delete mpToneGenerator;
668                    mpToneGenerator = new ToneGenerator(data->mStream, 1.0);
669                    mpToneGenerator->startTone(data->mType);
670                    delete data;
671                    mLock.lock();
672                    }break;
673                case STOP_TONE: {
674                    mLock.unlock();
675                    ALOGV("AudioCommandThread() processing stop tone");
676                    if (mpToneGenerator != NULL) {
677                        mpToneGenerator->stopTone();
678                        delete mpToneGenerator;
679                        mpToneGenerator = NULL;
680                    }
681                    mLock.lock();
682                    }break;
683                case SET_VOLUME: {
684                    VolumeData *data = (VolumeData *)command->mParam;
685                    ALOGV("AudioCommandThread() processing set volume stream %d, \
686                            volume %f, output %d", data->mStream, data->mVolume, data->mIO);
687                    command->mStatus = AudioSystem::setStreamVolume(data->mStream,
688                                                                    data->mVolume,
689                                                                    data->mIO);
690                    if (command->mWaitStatus) {
691                        command->mCond.signal();
692                        mWaitWorkCV.wait(mLock);
693                    }
694                    delete data;
695                    }break;
696                case SET_PARAMETERS: {
697                     ParametersData *data = (ParametersData *)command->mParam;
698                     ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
699                             data->mKeyValuePairs.string(), data->mIO);
700                     command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
701                     if (command->mWaitStatus) {
702                         command->mCond.signal();
703                         mWaitWorkCV.wait(mLock);
704                     }
705                     delete data;
706                     }break;
707                case SET_VOICE_VOLUME: {
708                    VoiceVolumeData *data = (VoiceVolumeData *)command->mParam;
709                    ALOGV("AudioCommandThread() processing set voice volume volume %f",
710                            data->mVolume);
711                    command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
712                    if (command->mWaitStatus) {
713                        command->mCond.signal();
714                        mWaitWorkCV.wait(mLock);
715                    }
716                    delete data;
717                    }break;
718                default:
719                    ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
720                }
721                delete command;
722                waitTime = INT64_MAX;
723            } else {
724                waitTime = mAudioCommands[0]->mTime - curTime;
725                break;
726            }
727        }
728        // release delayed commands wake lock
729        if (mName != "" && mAudioCommands.isEmpty()) {
730            release_wake_lock(mName.string());
731        }
732        ALOGV("AudioCommandThread() going to sleep");
733        mWaitWorkCV.waitRelative(mLock, waitTime);
734        ALOGV("AudioCommandThread() waking up");
735    }
736    mLock.unlock();
737    return false;
738}
739
740status_t AudioPolicyService::AudioCommandThread::dump(int fd)
741{
742    const size_t SIZE = 256;
743    char buffer[SIZE];
744    String8 result;
745
746    snprintf(buffer, SIZE, "AudioCommandThread %p Dump\n", this);
747    result.append(buffer);
748    write(fd, result.string(), result.size());
749
750    bool locked = tryLock(mLock);
751    if (!locked) {
752        String8 result2(kCmdDeadlockedString);
753        write(fd, result2.string(), result2.size());
754    }
755
756    snprintf(buffer, SIZE, "- Commands:\n");
757    result = String8(buffer);
758    result.append("   Command Time        Wait pParam\n");
759    for (size_t i = 0; i < mAudioCommands.size(); i++) {
760        mAudioCommands[i]->dump(buffer, SIZE);
761        result.append(buffer);
762    }
763    result.append("  Last Command\n");
764    mLastCommand.dump(buffer, SIZE);
765    result.append(buffer);
766
767    write(fd, result.string(), result.size());
768
769    if (locked) mLock.unlock();
770
771    return NO_ERROR;
772}
773
774void AudioPolicyService::AudioCommandThread::startToneCommand(ToneGenerator::tone_type type,
775        audio_stream_type_t stream)
776{
777    AudioCommand *command = new AudioCommand();
778    command->mCommand = START_TONE;
779    ToneData *data = new ToneData();
780    data->mType = type;
781    data->mStream = stream;
782    command->mParam = (void *)data;
783    command->mWaitStatus = false;
784    Mutex::Autolock _l(mLock);
785    insertCommand_l(command);
786    ALOGV("AudioCommandThread() adding tone start type %d, stream %d", type, stream);
787    mWaitWorkCV.signal();
788}
789
790void AudioPolicyService::AudioCommandThread::stopToneCommand()
791{
792    AudioCommand *command = new AudioCommand();
793    command->mCommand = STOP_TONE;
794    command->mParam = NULL;
795    command->mWaitStatus = false;
796    Mutex::Autolock _l(mLock);
797    insertCommand_l(command);
798    ALOGV("AudioCommandThread() adding tone stop");
799    mWaitWorkCV.signal();
800}
801
802status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
803                                                               float volume,
804                                                               audio_io_handle_t output,
805                                                               int delayMs)
806{
807    status_t status = NO_ERROR;
808
809    AudioCommand *command = new AudioCommand();
810    command->mCommand = SET_VOLUME;
811    VolumeData *data = new VolumeData();
812    data->mStream = stream;
813    data->mVolume = volume;
814    data->mIO = output;
815    command->mParam = data;
816    if (delayMs == 0) {
817        command->mWaitStatus = true;
818    } else {
819        command->mWaitStatus = false;
820    }
821    Mutex::Autolock _l(mLock);
822    insertCommand_l(command, delayMs);
823    ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
824            stream, volume, output);
825    mWaitWorkCV.signal();
826    if (command->mWaitStatus) {
827        command->mCond.wait(mLock);
828        status =  command->mStatus;
829        mWaitWorkCV.signal();
830    }
831    return status;
832}
833
834status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
835                                                                   const char *keyValuePairs,
836                                                                   int delayMs)
837{
838    status_t status = NO_ERROR;
839
840    AudioCommand *command = new AudioCommand();
841    command->mCommand = SET_PARAMETERS;
842    ParametersData *data = new ParametersData();
843    data->mIO = ioHandle;
844    data->mKeyValuePairs = String8(keyValuePairs);
845    command->mParam = data;
846    if (delayMs == 0) {
847        command->mWaitStatus = true;
848    } else {
849        command->mWaitStatus = false;
850    }
851    Mutex::Autolock _l(mLock);
852    insertCommand_l(command, delayMs);
853    ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
854            keyValuePairs, ioHandle, delayMs);
855    mWaitWorkCV.signal();
856    if (command->mWaitStatus) {
857        command->mCond.wait(mLock);
858        status =  command->mStatus;
859        mWaitWorkCV.signal();
860    }
861    return status;
862}
863
864status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
865{
866    status_t status = NO_ERROR;
867
868    AudioCommand *command = new AudioCommand();
869    command->mCommand = SET_VOICE_VOLUME;
870    VoiceVolumeData *data = new VoiceVolumeData();
871    data->mVolume = volume;
872    command->mParam = data;
873    if (delayMs == 0) {
874        command->mWaitStatus = true;
875    } else {
876        command->mWaitStatus = false;
877    }
878    Mutex::Autolock _l(mLock);
879    insertCommand_l(command, delayMs);
880    ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
881    mWaitWorkCV.signal();
882    if (command->mWaitStatus) {
883        command->mCond.wait(mLock);
884        status =  command->mStatus;
885        mWaitWorkCV.signal();
886    }
887    return status;
888}
889
890// insertCommand_l() must be called with mLock held
891void AudioPolicyService::AudioCommandThread::insertCommand_l(AudioCommand *command, int delayMs)
892{
893    ssize_t i;  // not size_t because i will count down to -1
894    Vector <AudioCommand *> removedCommands;
895
896    command->mTime = systemTime() + milliseconds(delayMs);
897
898    // acquire wake lock to make sure delayed commands are processed
899    if (mName != "" && mAudioCommands.isEmpty()) {
900        acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.string());
901    }
902
903    // check same pending commands with later time stamps and eliminate them
904    for (i = mAudioCommands.size()-1; i >= 0; i--) {
905        AudioCommand *command2 = mAudioCommands[i];
906        // commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
907        if (command2->mTime <= command->mTime) break;
908        if (command2->mCommand != command->mCommand) continue;
909
910        switch (command->mCommand) {
911        case SET_PARAMETERS: {
912            ParametersData *data = (ParametersData *)command->mParam;
913            ParametersData *data2 = (ParametersData *)command2->mParam;
914            if (data->mIO != data2->mIO) break;
915            ALOGV("Comparing parameter command %s to new command %s",
916                    data2->mKeyValuePairs.string(), data->mKeyValuePairs.string());
917            AudioParameter param = AudioParameter(data->mKeyValuePairs);
918            AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
919            for (size_t j = 0; j < param.size(); j++) {
920               String8 key;
921               String8 value;
922               param.getAt(j, key, value);
923               for (size_t k = 0; k < param2.size(); k++) {
924                  String8 key2;
925                  String8 value2;
926                  param2.getAt(k, key2, value2);
927                  if (key2 == key) {
928                      param2.remove(key2);
929                      ALOGV("Filtering out parameter %s", key2.string());
930                      break;
931                  }
932               }
933            }
934            // if all keys have been filtered out, remove the command.
935            // otherwise, update the key value pairs
936            if (param2.size() == 0) {
937                removedCommands.add(command2);
938            } else {
939                data2->mKeyValuePairs = param2.toString();
940            }
941        } break;
942
943        case SET_VOLUME: {
944            VolumeData *data = (VolumeData *)command->mParam;
945            VolumeData *data2 = (VolumeData *)command2->mParam;
946            if (data->mIO != data2->mIO) break;
947            if (data->mStream != data2->mStream) break;
948            ALOGV("Filtering out volume command on output %d for stream %d",
949                    data->mIO, data->mStream);
950            removedCommands.add(command2);
951        } break;
952        case START_TONE:
953        case STOP_TONE:
954        default:
955            break;
956        }
957    }
958
959    // remove filtered commands
960    for (size_t j = 0; j < removedCommands.size(); j++) {
961        // removed commands always have time stamps greater than current command
962        for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
963            if (mAudioCommands[k] == removedCommands[j]) {
964                ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
965                mAudioCommands.removeAt(k);
966                break;
967            }
968        }
969    }
970    removedCommands.clear();
971
972    // insert command at the right place according to its time stamp
973    ALOGV("inserting command: %d at index %d, num commands %d",
974            command->mCommand, (int)i+1, mAudioCommands.size());
975    mAudioCommands.insertAt(command, i + 1);
976}
977
978void AudioPolicyService::AudioCommandThread::exit()
979{
980    ALOGV("AudioCommandThread::exit");
981    {
982        AutoMutex _l(mLock);
983        requestExit();
984        mWaitWorkCV.signal();
985    }
986    requestExitAndWait();
987}
988
989void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
990{
991    snprintf(buffer, size, "   %02d      %06d.%03d  %01u    %p\n",
992            mCommand,
993            (int)ns2s(mTime),
994            (int)ns2ms(mTime)%1000,
995            mWaitStatus,
996            mParam);
997}
998
999/******* helpers for the service_ops callbacks defined below *********/
1000void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
1001                                       const char *keyValuePairs,
1002                                       int delayMs)
1003{
1004    mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
1005                                           delayMs);
1006}
1007
1008int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
1009                                        float volume,
1010                                        audio_io_handle_t output,
1011                                        int delayMs)
1012{
1013    return (int)mAudioCommandThread->volumeCommand(stream, volume,
1014                                                   output, delayMs);
1015}
1016
1017int AudioPolicyService::startTone(audio_policy_tone_t tone,
1018                                  audio_stream_type_t stream)
1019{
1020    if (tone != AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION)
1021        ALOGE("startTone: illegal tone requested (%d)", tone);
1022    if (stream != AUDIO_STREAM_VOICE_CALL)
1023        ALOGE("startTone: illegal stream (%d) requested for tone %d", stream,
1024             tone);
1025    mTonePlaybackThread->startToneCommand(ToneGenerator::TONE_SUP_CALL_WAITING,
1026                                          AUDIO_STREAM_VOICE_CALL);
1027    return 0;
1028}
1029
1030int AudioPolicyService::stopTone()
1031{
1032    mTonePlaybackThread->stopToneCommand();
1033    return 0;
1034}
1035
1036int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
1037{
1038    return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
1039}
1040
1041// ----------------------------------------------------------------------------
1042// Audio pre-processing configuration
1043// ----------------------------------------------------------------------------
1044
1045/*static*/ const char * const AudioPolicyService::kInputSourceNames[AUDIO_SOURCE_CNT -1] = {
1046    MIC_SRC_TAG,
1047    VOICE_UL_SRC_TAG,
1048    VOICE_DL_SRC_TAG,
1049    VOICE_CALL_SRC_TAG,
1050    CAMCORDER_SRC_TAG,
1051    VOICE_REC_SRC_TAG,
1052    VOICE_COMM_SRC_TAG
1053};
1054
1055// returns the audio_source_t enum corresponding to the input source name or
1056// AUDIO_SOURCE_CNT is no match found
1057audio_source_t AudioPolicyService::inputSourceNameToEnum(const char *name)
1058{
1059    int i;
1060    for (i = AUDIO_SOURCE_MIC; i < AUDIO_SOURCE_CNT; i++) {
1061        if (strcmp(name, kInputSourceNames[i - AUDIO_SOURCE_MIC]) == 0) {
1062            ALOGV("inputSourceNameToEnum found source %s %d", name, i);
1063            break;
1064        }
1065    }
1066    return (audio_source_t)i;
1067}
1068
1069size_t AudioPolicyService::growParamSize(char *param,
1070                                         size_t size,
1071                                         size_t *curSize,
1072                                         size_t *totSize)
1073{
1074    // *curSize is at least sizeof(effect_param_t) + 2 * sizeof(int)
1075    size_t pos = ((*curSize - 1 ) / size + 1) * size;
1076
1077    if (pos + size > *totSize) {
1078        while (pos + size > *totSize) {
1079            *totSize += ((*totSize + 7) / 8) * 4;
1080        }
1081        param = (char *)realloc(param, *totSize);
1082    }
1083    *curSize = pos + size;
1084    return pos;
1085}
1086
1087size_t AudioPolicyService::readParamValue(cnode *node,
1088                                          char *param,
1089                                          size_t *curSize,
1090                                          size_t *totSize)
1091{
1092    if (strncmp(node->name, SHORT_TAG, sizeof(SHORT_TAG) + 1) == 0) {
1093        size_t pos = growParamSize(param, sizeof(short), curSize, totSize);
1094        *(short *)((char *)param + pos) = (short)atoi(node->value);
1095        ALOGV("readParamValue() reading short %d", *(short *)((char *)param + pos));
1096        return sizeof(short);
1097    } else if (strncmp(node->name, INT_TAG, sizeof(INT_TAG) + 1) == 0) {
1098        size_t pos = growParamSize(param, sizeof(int), curSize, totSize);
1099        *(int *)((char *)param + pos) = atoi(node->value);
1100        ALOGV("readParamValue() reading int %d", *(int *)((char *)param + pos));
1101        return sizeof(int);
1102    } else if (strncmp(node->name, FLOAT_TAG, sizeof(FLOAT_TAG) + 1) == 0) {
1103        size_t pos = growParamSize(param, sizeof(float), curSize, totSize);
1104        *(float *)((char *)param + pos) = (float)atof(node->value);
1105        ALOGV("readParamValue() reading float %f",*(float *)((char *)param + pos));
1106        return sizeof(float);
1107    } else if (strncmp(node->name, BOOL_TAG, sizeof(BOOL_TAG) + 1) == 0) {
1108        size_t pos = growParamSize(param, sizeof(bool), curSize, totSize);
1109        if (strncmp(node->value, "false", strlen("false") + 1) == 0) {
1110            *(bool *)((char *)param + pos) = false;
1111        } else {
1112            *(bool *)((char *)param + pos) = true;
1113        }
1114        ALOGV("readParamValue() reading bool %s",*(bool *)((char *)param + pos) ? "true" : "false");
1115        return sizeof(bool);
1116    } else if (strncmp(node->name, STRING_TAG, sizeof(STRING_TAG) + 1) == 0) {
1117        size_t len = strnlen(node->value, EFFECT_STRING_LEN_MAX);
1118        if (*curSize + len + 1 > *totSize) {
1119            *totSize = *curSize + len + 1;
1120            param = (char *)realloc(param, *totSize);
1121        }
1122        strncpy(param + *curSize, node->value, len);
1123        *curSize += len;
1124        param[*curSize] = '\0';
1125        ALOGV("readParamValue() reading string %s", param + *curSize - len);
1126        return len;
1127    }
1128    ALOGW("readParamValue() unknown param type %s", node->name);
1129    return 0;
1130}
1131
1132effect_param_t *AudioPolicyService::loadEffectParameter(cnode *root)
1133{
1134    cnode *param;
1135    cnode *value;
1136    size_t curSize = sizeof(effect_param_t);
1137    size_t totSize = sizeof(effect_param_t) + 2 * sizeof(int);
1138    effect_param_t *fx_param = (effect_param_t *)malloc(totSize);
1139
1140    param = config_find(root, PARAM_TAG);
1141    value = config_find(root, VALUE_TAG);
1142    if (param == NULL && value == NULL) {
1143        // try to parse simple parameter form {int int}
1144        param = root->first_child;
1145        if (param != NULL) {
1146            // Note: that a pair of random strings is read as 0 0
1147            int *ptr = (int *)fx_param->data;
1148            int *ptr2 = (int *)((char *)param + sizeof(effect_param_t));
1149            ALOGW("loadEffectParameter() ptr %p ptr2 %p", ptr, ptr2);
1150            *ptr++ = atoi(param->name);
1151            *ptr = atoi(param->value);
1152            fx_param->psize = sizeof(int);
1153            fx_param->vsize = sizeof(int);
1154            return fx_param;
1155        }
1156    }
1157    if (param == NULL || value == NULL) {
1158        ALOGW("loadEffectParameter() invalid parameter description %s", root->name);
1159        goto error;
1160    }
1161
1162    fx_param->psize = 0;
1163    param = param->first_child;
1164    while (param) {
1165        ALOGV("loadEffectParameter() reading param of type %s", param->name);
1166        size_t size = readParamValue(param, (char *)fx_param, &curSize, &totSize);
1167        if (size == 0) {
1168            goto error;
1169        }
1170        fx_param->psize += size;
1171        param = param->next;
1172    }
1173
1174    // align start of value field on 32 bit boundary
1175    curSize = ((curSize - 1 ) / sizeof(int) + 1) * sizeof(int);
1176
1177    fx_param->vsize = 0;
1178    value = value->first_child;
1179    while (value) {
1180        ALOGV("loadEffectParameter() reading value of type %s", value->name);
1181        size_t size = readParamValue(value, (char *)fx_param, &curSize, &totSize);
1182        if (size == 0) {
1183            goto error;
1184        }
1185        fx_param->vsize += size;
1186        value = value->next;
1187    }
1188
1189    return fx_param;
1190
1191error:
1192    delete fx_param;
1193    return NULL;
1194}
1195
1196void AudioPolicyService::loadEffectParameters(cnode *root, Vector <effect_param_t *>& params)
1197{
1198    cnode *node = root->first_child;
1199    while (node) {
1200        ALOGV("loadEffectParameters() loading param %s", node->name);
1201        effect_param_t *param = loadEffectParameter(node);
1202        if (param == NULL) {
1203            node = node->next;
1204            continue;
1205        }
1206        params.add(param);
1207        node = node->next;
1208    }
1209}
1210
1211AudioPolicyService::InputSourceDesc *AudioPolicyService::loadInputSource(
1212                                                            cnode *root,
1213                                                            const Vector <EffectDesc *>& effects)
1214{
1215    cnode *node = root->first_child;
1216    if (node == NULL) {
1217        ALOGW("loadInputSource() empty element %s", root->name);
1218        return NULL;
1219    }
1220    InputSourceDesc *source = new InputSourceDesc();
1221    while (node) {
1222        size_t i;
1223        for (i = 0; i < effects.size(); i++) {
1224            if (strncmp(effects[i]->mName, node->name, EFFECT_STRING_LEN_MAX) == 0) {
1225                ALOGV("loadInputSource() found effect %s in list", node->name);
1226                break;
1227            }
1228        }
1229        if (i == effects.size()) {
1230            ALOGV("loadInputSource() effect %s not in list", node->name);
1231            node = node->next;
1232            continue;
1233        }
1234        EffectDesc *effect = new EffectDesc(*effects[i]);   // deep copy
1235        loadEffectParameters(node, effect->mParams);
1236        ALOGV("loadInputSource() adding effect %s uuid %08x", effect->mName, effect->mUuid.timeLow);
1237        source->mEffects.add(effect);
1238        node = node->next;
1239    }
1240    if (source->mEffects.size() == 0) {
1241        ALOGW("loadInputSource() no valid effects found in source %s", root->name);
1242        delete source;
1243        return NULL;
1244    }
1245    return source;
1246}
1247
1248status_t AudioPolicyService::loadInputSources(cnode *root, const Vector <EffectDesc *>& effects)
1249{
1250    cnode *node = config_find(root, PREPROCESSING_TAG);
1251    if (node == NULL) {
1252        return -ENOENT;
1253    }
1254    node = node->first_child;
1255    while (node) {
1256        audio_source_t source = inputSourceNameToEnum(node->name);
1257        if (source == AUDIO_SOURCE_CNT) {
1258            ALOGW("loadInputSources() invalid input source %s", node->name);
1259            node = node->next;
1260            continue;
1261        }
1262        ALOGV("loadInputSources() loading input source %s", node->name);
1263        InputSourceDesc *desc = loadInputSource(node, effects);
1264        if (desc == NULL) {
1265            node = node->next;
1266            continue;
1267        }
1268        mInputSources.add(source, desc);
1269        node = node->next;
1270    }
1271    return NO_ERROR;
1272}
1273
1274AudioPolicyService::EffectDesc *AudioPolicyService::loadEffect(cnode *root)
1275{
1276    cnode *node = config_find(root, UUID_TAG);
1277    if (node == NULL) {
1278        return NULL;
1279    }
1280    effect_uuid_t uuid;
1281    if (AudioEffect::stringToGuid(node->value, &uuid) != NO_ERROR) {
1282        ALOGW("loadEffect() invalid uuid %s", node->value);
1283        return NULL;
1284    }
1285    return new EffectDesc(root->name, uuid);
1286}
1287
1288status_t AudioPolicyService::loadEffects(cnode *root, Vector <EffectDesc *>& effects)
1289{
1290    cnode *node = config_find(root, EFFECTS_TAG);
1291    if (node == NULL) {
1292        return -ENOENT;
1293    }
1294    node = node->first_child;
1295    while (node) {
1296        ALOGV("loadEffects() loading effect %s", node->name);
1297        EffectDesc *effect = loadEffect(node);
1298        if (effect == NULL) {
1299            node = node->next;
1300            continue;
1301        }
1302        effects.add(effect);
1303        node = node->next;
1304    }
1305    return NO_ERROR;
1306}
1307
1308status_t AudioPolicyService::loadPreProcessorConfig(const char *path)
1309{
1310    cnode *root;
1311    char *data;
1312
1313    data = (char *)load_file(path, NULL);
1314    if (data == NULL) {
1315        return -ENODEV;
1316    }
1317    root = config_node("", "");
1318    config_load(root, data);
1319
1320    Vector <EffectDesc *> effects;
1321    loadEffects(root, effects);
1322    loadInputSources(root, effects);
1323
1324    config_free(root);
1325    free(root);
1326    free(data);
1327
1328    return NO_ERROR;
1329}
1330
1331/* implementation of the interface to the policy manager */
1332extern "C" {
1333
1334static audio_io_handle_t aps_open_output(void *service,
1335                                             uint32_t *pDevices,
1336                                             uint32_t *pSamplingRate,
1337                                             audio_format_t *pFormat,
1338                                             uint32_t *pChannels,
1339                                             uint32_t *pLatencyMs,
1340                                             audio_policy_output_flags_t flags)
1341{
1342    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1343    if (af == 0) {
1344        ALOGW("%s: could not get AudioFlinger", __func__);
1345        return 0;
1346    }
1347
1348    return af->openOutput(pDevices, pSamplingRate, pFormat, pChannels,
1349                          pLatencyMs, flags);
1350}
1351
1352static audio_io_handle_t aps_open_dup_output(void *service,
1353                                                 audio_io_handle_t output1,
1354                                                 audio_io_handle_t output2)
1355{
1356    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1357    if (af == 0) {
1358        ALOGW("%s: could not get AudioFlinger", __func__);
1359        return 0;
1360    }
1361    return af->openDuplicateOutput(output1, output2);
1362}
1363
1364static int aps_close_output(void *service, audio_io_handle_t output)
1365{
1366    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1367    if (af == 0)
1368        return PERMISSION_DENIED;
1369
1370    return af->closeOutput(output);
1371}
1372
1373static int aps_suspend_output(void *service, audio_io_handle_t output)
1374{
1375    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1376    if (af == 0) {
1377        ALOGW("%s: could not get AudioFlinger", __func__);
1378        return PERMISSION_DENIED;
1379    }
1380
1381    return af->suspendOutput(output);
1382}
1383
1384static int aps_restore_output(void *service, audio_io_handle_t output)
1385{
1386    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1387    if (af == 0) {
1388        ALOGW("%s: could not get AudioFlinger", __func__);
1389        return PERMISSION_DENIED;
1390    }
1391
1392    return af->restoreOutput(output);
1393}
1394
1395static audio_io_handle_t aps_open_input(void *service,
1396                                            uint32_t *pDevices,
1397                                            uint32_t *pSamplingRate,
1398                                            audio_format_t *pFormat,
1399                                            uint32_t *pChannels,
1400                                            audio_in_acoustics_t acoustics)
1401{
1402    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1403    if (af == 0) {
1404        ALOGW("%s: could not get AudioFlinger", __func__);
1405        return 0;
1406    }
1407
1408    return af->openInput(pDevices, pSamplingRate, pFormat, pChannels,
1409                         acoustics);
1410}
1411
1412static int aps_close_input(void *service, audio_io_handle_t input)
1413{
1414    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1415    if (af == 0)
1416        return PERMISSION_DENIED;
1417
1418    return af->closeInput(input);
1419}
1420
1421static int aps_set_stream_output(void *service, audio_stream_type_t stream,
1422                                     audio_io_handle_t output)
1423{
1424    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1425    if (af == 0)
1426        return PERMISSION_DENIED;
1427
1428    return af->setStreamOutput(stream, output);
1429}
1430
1431static int aps_move_effects(void *service, int session,
1432                                audio_io_handle_t src_output,
1433                                audio_io_handle_t dst_output)
1434{
1435    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
1436    if (af == 0)
1437        return PERMISSION_DENIED;
1438
1439    return af->moveEffects(session, src_output, dst_output);
1440}
1441
1442static char * aps_get_parameters(void *service, audio_io_handle_t io_handle,
1443                                     const char *keys)
1444{
1445    String8 result = AudioSystem::getParameters(io_handle, String8(keys));
1446    return strdup(result.string());
1447}
1448
1449static void aps_set_parameters(void *service, audio_io_handle_t io_handle,
1450                                   const char *kv_pairs, int delay_ms)
1451{
1452    AudioPolicyService *audioPolicyService = (AudioPolicyService *)service;
1453
1454    audioPolicyService->setParameters(io_handle, kv_pairs, delay_ms);
1455}
1456
1457static int aps_set_stream_volume(void *service, audio_stream_type_t stream,
1458                                     float volume, audio_io_handle_t output,
1459                                     int delay_ms)
1460{
1461    AudioPolicyService *audioPolicyService = (AudioPolicyService *)service;
1462
1463    return audioPolicyService->setStreamVolume(stream, volume, output,
1464                                               delay_ms);
1465}
1466
1467static int aps_start_tone(void *service, audio_policy_tone_t tone,
1468                              audio_stream_type_t stream)
1469{
1470    AudioPolicyService *audioPolicyService = (AudioPolicyService *)service;
1471
1472    return audioPolicyService->startTone(tone, stream);
1473}
1474
1475static int aps_stop_tone(void *service)
1476{
1477    AudioPolicyService *audioPolicyService = (AudioPolicyService *)service;
1478
1479    return audioPolicyService->stopTone();
1480}
1481
1482static int aps_set_voice_volume(void *service, float volume, int delay_ms)
1483{
1484    AudioPolicyService *audioPolicyService = (AudioPolicyService *)service;
1485
1486    return audioPolicyService->setVoiceVolume(volume, delay_ms);
1487}
1488
1489}; // extern "C"
1490
1491namespace {
1492    struct audio_policy_service_ops aps_ops = {
1493        open_output           : aps_open_output,
1494        open_duplicate_output : aps_open_dup_output,
1495        close_output          : aps_close_output,
1496        suspend_output        : aps_suspend_output,
1497        restore_output        : aps_restore_output,
1498        open_input            : aps_open_input,
1499        close_input           : aps_close_input,
1500        set_stream_volume     : aps_set_stream_volume,
1501        set_stream_output     : aps_set_stream_output,
1502        set_parameters        : aps_set_parameters,
1503        get_parameters        : aps_get_parameters,
1504        start_tone            : aps_start_tone,
1505        stop_tone             : aps_stop_tone,
1506        set_voice_volume      : aps_set_voice_volume,
1507        move_effects          : aps_move_effects,
1508    };
1509}; // namespace <unnamed>
1510
1511}; // namespace android
1512