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