Home | History | Annotate | Download | only in libmedia
      1 /*
      2  * Copyright (C) 2006-2007 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 "AudioSystem"
     18 //#define LOG_NDEBUG 0
     19 
     20 #include <utils/Log.h>
     21 #include <binder/IServiceManager.h>
     22 #include <media/AudioSystem.h>
     23 #include <media/IAudioPolicyService.h>
     24 #include <math.h>
     25 
     26 // ----------------------------------------------------------------------------
     27 // the sim build doesn't have gettid
     28 
     29 #ifndef HAVE_GETTID
     30 # define gettid getpid
     31 #endif
     32 
     33 // ----------------------------------------------------------------------------
     34 
     35 namespace android {
     36 
     37 // client singleton for AudioFlinger binder interface
     38 Mutex AudioSystem::gLock;
     39 sp<IAudioFlinger> AudioSystem::gAudioFlinger;
     40 sp<AudioSystem::AudioFlingerClient> AudioSystem::gAudioFlingerClient;
     41 audio_error_callback AudioSystem::gAudioErrorCallback = NULL;
     42 // Cached values
     43 DefaultKeyedVector<int, audio_io_handle_t> AudioSystem::gStreamOutputMap(0);
     44 DefaultKeyedVector<audio_io_handle_t, AudioSystem::OutputDescriptor *> AudioSystem::gOutputs(0);
     45 
     46 // Cached values for recording queries
     47 uint32_t AudioSystem::gPrevInSamplingRate = 16000;
     48 int AudioSystem::gPrevInFormat = AudioSystem::PCM_16_BIT;
     49 int AudioSystem::gPrevInChannelCount = 1;
     50 size_t AudioSystem::gInBuffSize = 0;
     51 
     52 
     53 // establish binder interface to AudioFlinger service
     54 const sp<IAudioFlinger>& AudioSystem::get_audio_flinger()
     55 {
     56     Mutex::Autolock _l(gLock);
     57     if (gAudioFlinger.get() == 0) {
     58         sp<IServiceManager> sm = defaultServiceManager();
     59         sp<IBinder> binder;
     60         do {
     61             binder = sm->getService(String16("media.audio_flinger"));
     62             if (binder != 0)
     63                 break;
     64             LOGW("AudioFlinger not published, waiting...");
     65             usleep(500000); // 0.5 s
     66         } while(true);
     67         if (gAudioFlingerClient == NULL) {
     68             gAudioFlingerClient = new AudioFlingerClient();
     69         } else {
     70             if (gAudioErrorCallback) {
     71                 gAudioErrorCallback(NO_ERROR);
     72             }
     73          }
     74         binder->linkToDeath(gAudioFlingerClient);
     75         gAudioFlinger = interface_cast<IAudioFlinger>(binder);
     76         gAudioFlinger->registerClient(gAudioFlingerClient);
     77     }
     78     LOGE_IF(gAudioFlinger==0, "no AudioFlinger!?");
     79 
     80     return gAudioFlinger;
     81 }
     82 
     83 status_t AudioSystem::muteMicrophone(bool state) {
     84     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
     85     if (af == 0) return PERMISSION_DENIED;
     86     return af->setMicMute(state);
     87 }
     88 
     89 status_t AudioSystem::isMicrophoneMuted(bool* state) {
     90     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
     91     if (af == 0) return PERMISSION_DENIED;
     92     *state = af->getMicMute();
     93     return NO_ERROR;
     94 }
     95 
     96 status_t AudioSystem::setMasterVolume(float value)
     97 {
     98     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
     99     if (af == 0) return PERMISSION_DENIED;
    100     af->setMasterVolume(value);
    101     return NO_ERROR;
    102 }
    103 
    104 status_t AudioSystem::setMasterMute(bool mute)
    105 {
    106     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
    107     if (af == 0) return PERMISSION_DENIED;
    108     af->setMasterMute(mute);
    109     return NO_ERROR;
    110 }
    111 
    112 status_t AudioSystem::getMasterVolume(float* volume)
    113 {
    114     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
    115     if (af == 0) return PERMISSION_DENIED;
    116     *volume = af->masterVolume();
    117     return NO_ERROR;
    118 }
    119 
    120 status_t AudioSystem::getMasterMute(bool* mute)
    121 {
    122     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
    123     if (af == 0) return PERMISSION_DENIED;
    124     *mute = af->masterMute();
    125     return NO_ERROR;
    126 }
    127 
    128 status_t AudioSystem::setStreamVolume(int stream, float value, int output)
    129 {
    130     if (uint32_t(stream) >= NUM_STREAM_TYPES) return BAD_VALUE;
    131     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
    132     if (af == 0) return PERMISSION_DENIED;
    133     af->setStreamVolume(stream, value, output);
    134     return NO_ERROR;
    135 }
    136 
    137 status_t AudioSystem::setStreamMute(int stream, bool mute)
    138 {
    139     if (uint32_t(stream) >= NUM_STREAM_TYPES) return BAD_VALUE;
    140     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
    141     if (af == 0) return PERMISSION_DENIED;
    142     af->setStreamMute(stream, mute);
    143     return NO_ERROR;
    144 }
    145 
    146 status_t AudioSystem::getStreamVolume(int stream, float* volume, int output)
    147 {
    148     if (uint32_t(stream) >= NUM_STREAM_TYPES) return BAD_VALUE;
    149     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
    150     if (af == 0) return PERMISSION_DENIED;
    151     *volume = af->streamVolume(stream, output);
    152     return NO_ERROR;
    153 }
    154 
    155 status_t AudioSystem::getStreamMute(int stream, bool* mute)
    156 {
    157     if (uint32_t(stream) >= NUM_STREAM_TYPES) return BAD_VALUE;
    158     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
    159     if (af == 0) return PERMISSION_DENIED;
    160     *mute = af->streamMute(stream);
    161     return NO_ERROR;
    162 }
    163 
    164 status_t AudioSystem::setMode(int mode)
    165 {
    166     if (mode >= NUM_MODES) return BAD_VALUE;
    167     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
    168     if (af == 0) return PERMISSION_DENIED;
    169     return af->setMode(mode);
    170 }
    171 
    172 
    173 status_t AudioSystem::isStreamActive(int stream, bool* state) {
    174     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
    175     if (af == 0) return PERMISSION_DENIED;
    176     *state = af->isStreamActive(stream);
    177     return NO_ERROR;
    178 }
    179 
    180 
    181 status_t AudioSystem::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs) {
    182     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
    183     if (af == 0) return PERMISSION_DENIED;
    184     return af->setParameters(ioHandle, keyValuePairs);
    185 }
    186 
    187 String8 AudioSystem::getParameters(audio_io_handle_t ioHandle, const String8& keys) {
    188     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
    189     String8 result = String8("");
    190     if (af == 0) return result;
    191 
    192     result = af->getParameters(ioHandle, keys);
    193     return result;
    194 }
    195 
    196 // convert volume steps to natural log scale
    197 
    198 // change this value to change volume scaling
    199 static const float dBPerStep = 0.5f;
    200 // shouldn't need to touch these
    201 static const float dBConvert = -dBPerStep * 2.302585093f / 20.0f;
    202 static const float dBConvertInverse = 1.0f / dBConvert;
    203 
    204 float AudioSystem::linearToLog(int volume)
    205 {
    206     // float v = volume ? exp(float(100 - volume) * dBConvert) : 0;
    207     // LOGD("linearToLog(%d)=%f", volume, v);
    208     // return v;
    209     return volume ? exp(float(100 - volume) * dBConvert) : 0;
    210 }
    211 
    212 int AudioSystem::logToLinear(float volume)
    213 {
    214     // int v = volume ? 100 - int(dBConvertInverse * log(volume) + 0.5) : 0;
    215     // LOGD("logTolinear(%d)=%f", v, volume);
    216     // return v;
    217     return volume ? 100 - int(dBConvertInverse * log(volume) + 0.5) : 0;
    218 }
    219 
    220 status_t AudioSystem::getOutputSamplingRate(int* samplingRate, int streamType)
    221 {
    222     OutputDescriptor *outputDesc;
    223     audio_io_handle_t output;
    224 
    225     if (streamType == DEFAULT) {
    226         streamType = MUSIC;
    227     }
    228 
    229     output = getOutput((stream_type)streamType);
    230     if (output == 0) {
    231         return PERMISSION_DENIED;
    232     }
    233 
    234     gLock.lock();
    235     outputDesc = AudioSystem::gOutputs.valueFor(output);
    236     if (outputDesc == 0) {
    237         LOGV("getOutputSamplingRate() no output descriptor for output %d in gOutputs", output);
    238         gLock.unlock();
    239         const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
    240         if (af == 0) return PERMISSION_DENIED;
    241         *samplingRate = af->sampleRate(output);
    242     } else {
    243         LOGV("getOutputSamplingRate() reading from output desc");
    244         *samplingRate = outputDesc->samplingRate;
    245         gLock.unlock();
    246     }
    247 
    248     LOGV("getOutputSamplingRate() streamType %d, output %d, sampling rate %d", streamType, output, *samplingRate);
    249 
    250     return NO_ERROR;
    251 }
    252 
    253 status_t AudioSystem::getOutputFrameCount(int* frameCount, int streamType)
    254 {
    255     OutputDescriptor *outputDesc;
    256     audio_io_handle_t output;
    257 
    258     if (streamType == DEFAULT) {
    259         streamType = MUSIC;
    260     }
    261 
    262     output = getOutput((stream_type)streamType);
    263     if (output == 0) {
    264         return PERMISSION_DENIED;
    265     }
    266 
    267     gLock.lock();
    268     outputDesc = AudioSystem::gOutputs.valueFor(output);
    269     if (outputDesc == 0) {
    270         gLock.unlock();
    271         const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
    272         if (af == 0) return PERMISSION_DENIED;
    273         *frameCount = af->frameCount(output);
    274     } else {
    275         *frameCount = outputDesc->frameCount;
    276         gLock.unlock();
    277     }
    278 
    279     LOGV("getOutputFrameCount() streamType %d, output %d, frameCount %d", streamType, output, *frameCount);
    280 
    281     return NO_ERROR;
    282 }
    283 
    284 status_t AudioSystem::getOutputLatency(uint32_t* latency, int streamType)
    285 {
    286     OutputDescriptor *outputDesc;
    287     audio_io_handle_t output;
    288 
    289     if (streamType == DEFAULT) {
    290         streamType = MUSIC;
    291     }
    292 
    293     output = getOutput((stream_type)streamType);
    294     if (output == 0) {
    295         return PERMISSION_DENIED;
    296     }
    297 
    298     gLock.lock();
    299     outputDesc = AudioSystem::gOutputs.valueFor(output);
    300     if (outputDesc == 0) {
    301         gLock.unlock();
    302         const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
    303         if (af == 0) return PERMISSION_DENIED;
    304         *latency = af->latency(output);
    305     } else {
    306         *latency = outputDesc->latency;
    307         gLock.unlock();
    308     }
    309 
    310     LOGV("getOutputLatency() streamType %d, output %d, latency %d", streamType, output, *latency);
    311 
    312     return NO_ERROR;
    313 }
    314 
    315 status_t AudioSystem::getInputBufferSize(uint32_t sampleRate, int format, int channelCount,
    316     size_t* buffSize)
    317 {
    318     // Do we have a stale gInBufferSize or are we requesting the input buffer size for new values
    319     if ((gInBuffSize == 0) || (sampleRate != gPrevInSamplingRate) || (format != gPrevInFormat)
    320         || (channelCount != gPrevInChannelCount)) {
    321         // save the request params
    322         gPrevInSamplingRate = sampleRate;
    323         gPrevInFormat = format;
    324         gPrevInChannelCount = channelCount;
    325 
    326         gInBuffSize = 0;
    327         const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
    328         if (af == 0) {
    329             return PERMISSION_DENIED;
    330         }
    331         gInBuffSize = af->getInputBufferSize(sampleRate, format, channelCount);
    332     }
    333     *buffSize = gInBuffSize;
    334 
    335     return NO_ERROR;
    336 }
    337 
    338 status_t AudioSystem::setVoiceVolume(float value)
    339 {
    340     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
    341     if (af == 0) return PERMISSION_DENIED;
    342     return af->setVoiceVolume(value);
    343 }
    344 
    345 status_t AudioSystem::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int stream)
    346 {
    347     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
    348     if (af == 0) return PERMISSION_DENIED;
    349 
    350     if (stream == DEFAULT) {
    351         stream = MUSIC;
    352     }
    353 
    354     return af->getRenderPosition(halFrames, dspFrames, getOutput((stream_type)stream));
    355 }
    356 
    357 unsigned int AudioSystem::getInputFramesLost(audio_io_handle_t ioHandle) {
    358     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
    359     unsigned int result = 0;
    360     if (af == 0) return result;
    361     if (ioHandle == 0) return result;
    362 
    363     result = af->getInputFramesLost(ioHandle);
    364     return result;
    365 }
    366 
    367 int AudioSystem::newAudioSessionId() {
    368     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
    369     if (af == 0) return 0;
    370     return af->newAudioSessionId();
    371 }
    372 
    373 // ---------------------------------------------------------------------------
    374 
    375 void AudioSystem::AudioFlingerClient::binderDied(const wp<IBinder>& who) {
    376     Mutex::Autolock _l(AudioSystem::gLock);
    377 
    378     AudioSystem::gAudioFlinger.clear();
    379     // clear output handles and stream to output map caches
    380     AudioSystem::gStreamOutputMap.clear();
    381     AudioSystem::gOutputs.clear();
    382 
    383     if (gAudioErrorCallback) {
    384         gAudioErrorCallback(DEAD_OBJECT);
    385     }
    386     LOGW("AudioFlinger server died!");
    387 }
    388 
    389 void AudioSystem::AudioFlingerClient::ioConfigChanged(int event, int ioHandle, void *param2) {
    390     LOGV("ioConfigChanged() event %d", event);
    391     OutputDescriptor *desc;
    392     uint32_t stream;
    393 
    394     if (ioHandle == 0) return;
    395 
    396     Mutex::Autolock _l(AudioSystem::gLock);
    397 
    398     switch (event) {
    399     case STREAM_CONFIG_CHANGED:
    400         if (param2 == 0) break;
    401         stream = *(uint32_t *)param2;
    402         LOGV("ioConfigChanged() STREAM_CONFIG_CHANGED stream %d, output %d", stream, ioHandle);
    403         if (gStreamOutputMap.indexOfKey(stream) >= 0) {
    404             gStreamOutputMap.replaceValueFor(stream, ioHandle);
    405         }
    406         break;
    407     case OUTPUT_OPENED: {
    408         if (gOutputs.indexOfKey(ioHandle) >= 0) {
    409             LOGV("ioConfigChanged() opening already existing output! %d", ioHandle);
    410             break;
    411         }
    412         if (param2 == 0) break;
    413         desc = (OutputDescriptor *)param2;
    414 
    415         OutputDescriptor *outputDesc =  new OutputDescriptor(*desc);
    416         gOutputs.add(ioHandle, outputDesc);
    417         LOGV("ioConfigChanged() new output samplingRate %d, format %d channels %d frameCount %d latency %d",
    418                 outputDesc->samplingRate, outputDesc->format, outputDesc->channels, outputDesc->frameCount, outputDesc->latency);
    419         } break;
    420     case OUTPUT_CLOSED: {
    421         if (gOutputs.indexOfKey(ioHandle) < 0) {
    422             LOGW("ioConfigChanged() closing unknow output! %d", ioHandle);
    423             break;
    424         }
    425         LOGV("ioConfigChanged() output %d closed", ioHandle);
    426 
    427         gOutputs.removeItem(ioHandle);
    428         for (int i = gStreamOutputMap.size() - 1; i >= 0 ; i--) {
    429             if (gStreamOutputMap.valueAt(i) == ioHandle) {
    430                 gStreamOutputMap.removeItemsAt(i);
    431             }
    432         }
    433         } break;
    434 
    435     case OUTPUT_CONFIG_CHANGED: {
    436         int index = gOutputs.indexOfKey(ioHandle);
    437         if (index < 0) {
    438             LOGW("ioConfigChanged() modifying unknow output! %d", ioHandle);
    439             break;
    440         }
    441         if (param2 == 0) break;
    442         desc = (OutputDescriptor *)param2;
    443 
    444         LOGV("ioConfigChanged() new config for output %d samplingRate %d, format %d channels %d frameCount %d latency %d",
    445                 ioHandle, desc->samplingRate, desc->format,
    446                 desc->channels, desc->frameCount, desc->latency);
    447         OutputDescriptor *outputDesc = gOutputs.valueAt(index);
    448         delete outputDesc;
    449         outputDesc =  new OutputDescriptor(*desc);
    450         gOutputs.replaceValueFor(ioHandle, outputDesc);
    451     } break;
    452     case INPUT_OPENED:
    453     case INPUT_CLOSED:
    454     case INPUT_CONFIG_CHANGED:
    455         break;
    456 
    457     }
    458 }
    459 
    460 void AudioSystem::setErrorCallback(audio_error_callback cb) {
    461     Mutex::Autolock _l(gLock);
    462     gAudioErrorCallback = cb;
    463 }
    464 
    465 bool AudioSystem::routedToA2dpOutput(int streamType) {
    466     switch(streamType) {
    467     case MUSIC:
    468     case VOICE_CALL:
    469     case BLUETOOTH_SCO:
    470     case SYSTEM:
    471         return true;
    472     default:
    473         return false;
    474     }
    475 }
    476 
    477 
    478 // client singleton for AudioPolicyService binder interface
    479 sp<IAudioPolicyService> AudioSystem::gAudioPolicyService;
    480 sp<AudioSystem::AudioPolicyServiceClient> AudioSystem::gAudioPolicyServiceClient;
    481 
    482 
    483 // establish binder interface to AudioFlinger service
    484 const sp<IAudioPolicyService>& AudioSystem::get_audio_policy_service()
    485 {
    486     gLock.lock();
    487     if (gAudioPolicyService.get() == 0) {
    488         sp<IServiceManager> sm = defaultServiceManager();
    489         sp<IBinder> binder;
    490         do {
    491             binder = sm->getService(String16("media.audio_policy"));
    492             if (binder != 0)
    493                 break;
    494             LOGW("AudioPolicyService not published, waiting...");
    495             usleep(500000); // 0.5 s
    496         } while(true);
    497         if (gAudioPolicyServiceClient == NULL) {
    498             gAudioPolicyServiceClient = new AudioPolicyServiceClient();
    499         }
    500         binder->linkToDeath(gAudioPolicyServiceClient);
    501         gAudioPolicyService = interface_cast<IAudioPolicyService>(binder);
    502         gLock.unlock();
    503     } else {
    504         gLock.unlock();
    505     }
    506     return gAudioPolicyService;
    507 }
    508 
    509 status_t AudioSystem::setDeviceConnectionState(audio_devices device,
    510                                                   device_connection_state state,
    511                                                   const char *device_address)
    512 {
    513     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
    514     if (aps == 0) return PERMISSION_DENIED;
    515 
    516     return aps->setDeviceConnectionState(device, state, device_address);
    517 }
    518 
    519 AudioSystem::device_connection_state AudioSystem::getDeviceConnectionState(audio_devices device,
    520                                                   const char *device_address)
    521 {
    522     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
    523     if (aps == 0) return DEVICE_STATE_UNAVAILABLE;
    524 
    525     return aps->getDeviceConnectionState(device, device_address);
    526 }
    527 
    528 status_t AudioSystem::setPhoneState(int state)
    529 {
    530     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
    531     if (aps == 0) return PERMISSION_DENIED;
    532 
    533     return aps->setPhoneState(state);
    534 }
    535 
    536 status_t AudioSystem::setRingerMode(uint32_t mode, uint32_t mask)
    537 {
    538     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
    539     if (aps == 0) return PERMISSION_DENIED;
    540     return aps->setRingerMode(mode, mask);
    541 }
    542 
    543 status_t AudioSystem::setForceUse(force_use usage, forced_config config)
    544 {
    545     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
    546     if (aps == 0) return PERMISSION_DENIED;
    547     return aps->setForceUse(usage, config);
    548 }
    549 
    550 AudioSystem::forced_config AudioSystem::getForceUse(force_use usage)
    551 {
    552     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
    553     if (aps == 0) return FORCE_NONE;
    554     return aps->getForceUse(usage);
    555 }
    556 
    557 
    558 audio_io_handle_t AudioSystem::getOutput(stream_type stream,
    559                                     uint32_t samplingRate,
    560                                     uint32_t format,
    561                                     uint32_t channels,
    562                                     output_flags flags)
    563 {
    564     audio_io_handle_t output = 0;
    565     // Do not use stream to output map cache if the direct output
    566     // flag is set or if we are likely to use a direct output
    567     // (e.g voice call stream @ 8kHz could use BT SCO device and be routed to
    568     // a direct output on some platforms).
    569     // TODO: the output cache and stream to output mapping implementation needs to
    570     // be reworked for proper operation with direct outputs. This code is too specific
    571     // to the first use case we want to cover (Voice Recognition and Voice Dialer over
    572     // Bluetooth SCO
    573     if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) == 0 &&
    574         ((stream != AudioSystem::VOICE_CALL && stream != AudioSystem::BLUETOOTH_SCO) ||
    575          channels != AudioSystem::CHANNEL_OUT_MONO ||
    576          (samplingRate != 8000 && samplingRate != 16000))) {
    577         Mutex::Autolock _l(gLock);
    578         output = AudioSystem::gStreamOutputMap.valueFor(stream);
    579         LOGV_IF((output != 0), "getOutput() read %d from cache for stream %d", output, stream);
    580     }
    581     if (output == 0) {
    582         const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
    583         if (aps == 0) return 0;
    584         output = aps->getOutput(stream, samplingRate, format, channels, flags);
    585         if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) == 0) {
    586             Mutex::Autolock _l(gLock);
    587             AudioSystem::gStreamOutputMap.add(stream, output);
    588         }
    589     }
    590     return output;
    591 }
    592 
    593 status_t AudioSystem::startOutput(audio_io_handle_t output,
    594                                   AudioSystem::stream_type stream,
    595                                   int session)
    596 {
    597     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
    598     if (aps == 0) return PERMISSION_DENIED;
    599     return aps->startOutput(output, stream, session);
    600 }
    601 
    602 status_t AudioSystem::stopOutput(audio_io_handle_t output,
    603                                  AudioSystem::stream_type stream,
    604                                  int session)
    605 {
    606     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
    607     if (aps == 0) return PERMISSION_DENIED;
    608     return aps->stopOutput(output, stream, session);
    609 }
    610 
    611 void AudioSystem::releaseOutput(audio_io_handle_t output)
    612 {
    613     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
    614     if (aps == 0) return;
    615     aps->releaseOutput(output);
    616 }
    617 
    618 audio_io_handle_t AudioSystem::getInput(int inputSource,
    619                                     uint32_t samplingRate,
    620                                     uint32_t format,
    621                                     uint32_t channels,
    622                                     audio_in_acoustics acoustics)
    623 {
    624     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
    625     if (aps == 0) return 0;
    626     return aps->getInput(inputSource, samplingRate, format, channels, acoustics);
    627 }
    628 
    629 status_t AudioSystem::startInput(audio_io_handle_t input)
    630 {
    631     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
    632     if (aps == 0) return PERMISSION_DENIED;
    633     return aps->startInput(input);
    634 }
    635 
    636 status_t AudioSystem::stopInput(audio_io_handle_t input)
    637 {
    638     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
    639     if (aps == 0) return PERMISSION_DENIED;
    640     return aps->stopInput(input);
    641 }
    642 
    643 void AudioSystem::releaseInput(audio_io_handle_t input)
    644 {
    645     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
    646     if (aps == 0) return;
    647     aps->releaseInput(input);
    648 }
    649 
    650 status_t AudioSystem::initStreamVolume(stream_type stream,
    651                                     int indexMin,
    652                                     int indexMax)
    653 {
    654     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
    655     if (aps == 0) return PERMISSION_DENIED;
    656     return aps->initStreamVolume(stream, indexMin, indexMax);
    657 }
    658 
    659 status_t AudioSystem::setStreamVolumeIndex(stream_type stream, int index)
    660 {
    661     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
    662     if (aps == 0) return PERMISSION_DENIED;
    663     return aps->setStreamVolumeIndex(stream, index);
    664 }
    665 
    666 status_t AudioSystem::getStreamVolumeIndex(stream_type stream, int *index)
    667 {
    668     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
    669     if (aps == 0) return PERMISSION_DENIED;
    670     return aps->getStreamVolumeIndex(stream, index);
    671 }
    672 
    673 uint32_t AudioSystem::getStrategyForStream(AudioSystem::stream_type stream)
    674 {
    675     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
    676     if (aps == 0) return 0;
    677     return aps->getStrategyForStream(stream);
    678 }
    679 
    680 audio_io_handle_t AudioSystem::getOutputForEffect(effect_descriptor_t *desc)
    681 {
    682     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
    683     if (aps == 0) return PERMISSION_DENIED;
    684     return aps->getOutputForEffect(desc);
    685 }
    686 
    687 status_t AudioSystem::registerEffect(effect_descriptor_t *desc,
    688                                 audio_io_handle_t output,
    689                                 uint32_t strategy,
    690                                 int session,
    691                                 int id)
    692 {
    693     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
    694     if (aps == 0) return PERMISSION_DENIED;
    695     return aps->registerEffect(desc, output, strategy, session, id);
    696 }
    697 
    698 status_t AudioSystem::unregisterEffect(int id)
    699 {
    700     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
    701     if (aps == 0) return PERMISSION_DENIED;
    702     return aps->unregisterEffect(id);
    703 }
    704 
    705 // ---------------------------------------------------------------------------
    706 
    707 void AudioSystem::AudioPolicyServiceClient::binderDied(const wp<IBinder>& who) {
    708     Mutex::Autolock _l(AudioSystem::gLock);
    709     AudioSystem::gAudioPolicyService.clear();
    710 
    711     LOGW("AudioPolicyService server died!");
    712 }
    713 
    714 // ---------------------------------------------------------------------------
    715 
    716 
    717 // use emulated popcount optimization
    718 // http://www.df.lth.se/~john_e/gems/gem002d.html
    719 uint32_t AudioSystem::popCount(uint32_t u)
    720 {
    721     u = ((u&0x55555555) + ((u>>1)&0x55555555));
    722     u = ((u&0x33333333) + ((u>>2)&0x33333333));
    723     u = ((u&0x0f0f0f0f) + ((u>>4)&0x0f0f0f0f));
    724     u = ((u&0x00ff00ff) + ((u>>8)&0x00ff00ff));
    725     u = ( u&0x0000ffff) + (u>>16);
    726     return u;
    727 }
    728 
    729 bool AudioSystem::isOutputDevice(audio_devices device)
    730 {
    731     if ((popCount(device) == 1 ) &&
    732         ((device & ~AudioSystem::DEVICE_OUT_ALL) == 0)) {
    733         return true;
    734     } else {
    735         return false;
    736     }
    737 }
    738 
    739 bool AudioSystem::isInputDevice(audio_devices device)
    740 {
    741     if ((popCount(device) == 1 ) &&
    742         ((device & ~AudioSystem::DEVICE_IN_ALL) == 0)) {
    743         return true;
    744     } else {
    745         return false;
    746     }
    747 }
    748 
    749 bool AudioSystem::isA2dpDevice(audio_devices device)
    750 {
    751     if ((popCount(device) == 1 ) &&
    752         (device & (AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP |
    753                    AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
    754                    AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER))) {
    755         return true;
    756     } else {
    757         return false;
    758     }
    759 }
    760 
    761 bool AudioSystem::isBluetoothScoDevice(audio_devices device)
    762 {
    763     if ((popCount(device) == 1 ) &&
    764         (device & (AudioSystem::DEVICE_OUT_BLUETOOTH_SCO |
    765                    AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET |
    766                    AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT |
    767                    AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET))) {
    768         return true;
    769     } else {
    770         return false;
    771     }
    772 }
    773 
    774 bool AudioSystem::isLowVisibility(stream_type stream)
    775 {
    776     if (stream == AudioSystem::SYSTEM ||
    777         stream == AudioSystem::NOTIFICATION ||
    778         stream == AudioSystem::RING) {
    779         return true;
    780     } else {
    781         return false;
    782     }
    783 }
    784 
    785 bool AudioSystem::isInputChannel(uint32_t channel)
    786 {
    787     if ((channel & ~AudioSystem::CHANNEL_IN_ALL) == 0) {
    788         return true;
    789     } else {
    790         return false;
    791     }
    792 }
    793 
    794 bool AudioSystem::isOutputChannel(uint32_t channel)
    795 {
    796     if ((channel & ~AudioSystem::CHANNEL_OUT_ALL) == 0) {
    797         return true;
    798     } else {
    799         return false;
    800     }
    801 }
    802 
    803 bool AudioSystem::isValidFormat(uint32_t format)
    804 {
    805     switch (format & MAIN_FORMAT_MASK) {
    806     case         PCM:
    807     case         MP3:
    808     case         AMR_NB:
    809     case         AMR_WB:
    810     case         AAC:
    811     case         HE_AAC_V1:
    812     case         HE_AAC_V2:
    813     case         VORBIS:
    814         return true;
    815     default:
    816         return false;
    817     }
    818 }
    819 
    820 bool AudioSystem::isLinearPCM(uint32_t format)
    821 {
    822     switch (format) {
    823     case         PCM_16_BIT:
    824     case         PCM_8_BIT:
    825         return true;
    826     default:
    827         return false;
    828     }
    829 }
    830 
    831 //------------------------- AudioParameter class implementation ---------------
    832 
    833 const char *AudioParameter::keyRouting = "routing";
    834 const char *AudioParameter::keySamplingRate = "sampling_rate";
    835 const char *AudioParameter::keyFormat = "format";
    836 const char *AudioParameter::keyChannels = "channels";
    837 const char *AudioParameter::keyFrameCount = "frame_count";
    838 const char *AudioParameter::keyInputSource = "input_source";
    839 
    840 AudioParameter::AudioParameter(const String8& keyValuePairs)
    841 {
    842     char *str = new char[keyValuePairs.length()+1];
    843     mKeyValuePairs = keyValuePairs;
    844 
    845     strcpy(str, keyValuePairs.string());
    846     char *pair = strtok(str, ";");
    847     while (pair != NULL) {
    848         if (strlen(pair) != 0) {
    849             size_t eqIdx = strcspn(pair, "=");
    850             String8 key = String8(pair, eqIdx);
    851             String8 value;
    852             if (eqIdx == strlen(pair)) {
    853                 value = String8("");
    854             } else {
    855                 value = String8(pair + eqIdx + 1);
    856             }
    857             if (mParameters.indexOfKey(key) < 0) {
    858                 mParameters.add(key, value);
    859             } else {
    860                 mParameters.replaceValueFor(key, value);
    861             }
    862         } else {
    863             LOGV("AudioParameter() cstor empty key value pair");
    864         }
    865         pair = strtok(NULL, ";");
    866     }
    867 
    868     delete[] str;
    869 }
    870 
    871 AudioParameter::~AudioParameter()
    872 {
    873     mParameters.clear();
    874 }
    875 
    876 String8 AudioParameter::toString()
    877 {
    878     String8 str = String8("");
    879 
    880     size_t size = mParameters.size();
    881     for (size_t i = 0; i < size; i++) {
    882         str += mParameters.keyAt(i);
    883         str += "=";
    884         str += mParameters.valueAt(i);
    885         if (i < (size - 1)) str += ";";
    886     }
    887     return str;
    888 }
    889 
    890 status_t AudioParameter::add(const String8& key, const String8& value)
    891 {
    892     if (mParameters.indexOfKey(key) < 0) {
    893         mParameters.add(key, value);
    894         return NO_ERROR;
    895     } else {
    896         mParameters.replaceValueFor(key, value);
    897         return ALREADY_EXISTS;
    898     }
    899 }
    900 
    901 status_t AudioParameter::addInt(const String8& key, const int value)
    902 {
    903     char str[12];
    904     if (snprintf(str, 12, "%d", value) > 0) {
    905         String8 str8 = String8(str);
    906         return add(key, str8);
    907     } else {
    908         return BAD_VALUE;
    909     }
    910 }
    911 
    912 status_t AudioParameter::addFloat(const String8& key, const float value)
    913 {
    914     char str[23];
    915     if (snprintf(str, 23, "%.10f", value) > 0) {
    916         String8 str8 = String8(str);
    917         return add(key, str8);
    918     } else {
    919         return BAD_VALUE;
    920     }
    921 }
    922 
    923 status_t AudioParameter::remove(const String8& key)
    924 {
    925     if (mParameters.indexOfKey(key) >= 0) {
    926         mParameters.removeItem(key);
    927         return NO_ERROR;
    928     } else {
    929         return BAD_VALUE;
    930     }
    931 }
    932 
    933 status_t AudioParameter::get(const String8& key, String8& value)
    934 {
    935     if (mParameters.indexOfKey(key) >= 0) {
    936         value = mParameters.valueFor(key);
    937         return NO_ERROR;
    938     } else {
    939         return BAD_VALUE;
    940     }
    941 }
    942 
    943 status_t AudioParameter::getInt(const String8& key, int& value)
    944 {
    945     String8 str8;
    946     status_t result = get(key, str8);
    947     value = 0;
    948     if (result == NO_ERROR) {
    949         int val;
    950         if (sscanf(str8.string(), "%d", &val) == 1) {
    951             value = val;
    952         } else {
    953             result = INVALID_OPERATION;
    954         }
    955     }
    956     return result;
    957 }
    958 
    959 status_t AudioParameter::getFloat(const String8& key, float& value)
    960 {
    961     String8 str8;
    962     status_t result = get(key, str8);
    963     value = 0;
    964     if (result == NO_ERROR) {
    965         float val;
    966         if (sscanf(str8.string(), "%f", &val) == 1) {
    967             value = val;
    968         } else {
    969             result = INVALID_OPERATION;
    970         }
    971     }
    972     return result;
    973 }
    974 
    975 status_t AudioParameter::getAt(size_t index, String8& key, String8& value)
    976 {
    977     if (mParameters.size() > index) {
    978         key = mParameters.keyAt(index);
    979         value = mParameters.valueAt(index);
    980         return NO_ERROR;
    981     } else {
    982         return BAD_VALUE;
    983     }
    984 }
    985 }; // namespace android
    986 
    987