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