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