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