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