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