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 "AudioPolicyManagerBase"
     18 //#define LOG_NDEBUG 0
     19 #include <utils/Log.h>
     20 #include <hardware_legacy/AudioPolicyManagerBase.h>
     21 #include <media/mediarecorder.h>
     22 
     23 namespace android {
     24 
     25 
     26 // ----------------------------------------------------------------------------
     27 // AudioPolicyInterface implementation
     28 // ----------------------------------------------------------------------------
     29 
     30 
     31 status_t AudioPolicyManagerBase::setDeviceConnectionState(AudioSystem::audio_devices device,
     32                                                   AudioSystem::device_connection_state state,
     33                                                   const char *device_address)
     34 {
     35 
     36     LOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
     37 
     38     // connect/disconnect only 1 device at a time
     39     if (AudioSystem::popCount(device) != 1) return BAD_VALUE;
     40 
     41     if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
     42         LOGE("setDeviceConnectionState() invalid address: %s", device_address);
     43         return BAD_VALUE;
     44     }
     45 
     46     // handle output devices
     47     if (AudioSystem::isOutputDevice(device)) {
     48 
     49 #ifndef WITH_A2DP
     50         if (AudioSystem::isA2dpDevice(device)) {
     51             LOGE("setDeviceConnectionState() invalid device: %x", device);
     52             return BAD_VALUE;
     53         }
     54 #endif
     55 
     56         switch (state)
     57         {
     58         // handle output device connection
     59         case AudioSystem::DEVICE_STATE_AVAILABLE:
     60             if (mAvailableOutputDevices & device) {
     61                 LOGW("setDeviceConnectionState() device already connected: %x", device);
     62                 return INVALID_OPERATION;
     63             }
     64             LOGV("setDeviceConnectionState() connecting device %x", device);
     65 
     66             // register new device as available
     67             mAvailableOutputDevices |= device;
     68 
     69 #ifdef WITH_A2DP
     70             // handle A2DP device connection
     71             if (AudioSystem::isA2dpDevice(device)) {
     72                 status_t status = handleA2dpConnection(device, device_address);
     73                 if (status != NO_ERROR) {
     74                     mAvailableOutputDevices &= ~device;
     75                     return status;
     76                 }
     77             } else
     78 #endif
     79             {
     80                 if (AudioSystem::isBluetoothScoDevice(device)) {
     81                     LOGV("setDeviceConnectionState() BT SCO  device, address %s", device_address);
     82                     // keep track of SCO device address
     83                     mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
     84 #ifdef WITH_A2DP
     85                     if (mA2dpOutput != 0 &&
     86                         mPhoneState != AudioSystem::MODE_NORMAL) {
     87                         mpClientInterface->suspendOutput(mA2dpOutput);
     88                     }
     89 #endif
     90                 }
     91             }
     92             break;
     93         // handle output device disconnection
     94         case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
     95             if (!(mAvailableOutputDevices & device)) {
     96                 LOGW("setDeviceConnectionState() device not connected: %x", device);
     97                 return INVALID_OPERATION;
     98             }
     99 
    100 
    101             LOGV("setDeviceConnectionState() disconnecting device %x", device);
    102             // remove device from available output devices
    103             mAvailableOutputDevices &= ~device;
    104 
    105 #ifdef WITH_A2DP
    106             // handle A2DP device disconnection
    107             if (AudioSystem::isA2dpDevice(device)) {
    108                 status_t status = handleA2dpDisconnection(device, device_address);
    109                 if (status != NO_ERROR) {
    110                     mAvailableOutputDevices |= device;
    111                     return status;
    112                 }
    113             } else
    114 #endif
    115             {
    116                 if (AudioSystem::isBluetoothScoDevice(device)) {
    117                     mScoDeviceAddress = "";
    118 #ifdef WITH_A2DP
    119                     if (mA2dpOutput != 0 &&
    120                         mPhoneState != AudioSystem::MODE_NORMAL) {
    121                         mpClientInterface->restoreOutput(mA2dpOutput);
    122                     }
    123 #endif
    124                 }
    125             }
    126             } break;
    127 
    128         default:
    129             LOGE("setDeviceConnectionState() invalid state: %x", state);
    130             return BAD_VALUE;
    131         }
    132 
    133         // request routing change if necessary
    134         uint32_t newDevice = getNewDevice(mHardwareOutput, false);
    135 #ifdef WITH_A2DP
    136         checkOutputForAllStrategies();
    137         // A2DP outputs must be closed after checkOutputForAllStrategies() is executed
    138         if (state == AudioSystem::DEVICE_STATE_UNAVAILABLE && AudioSystem::isA2dpDevice(device)) {
    139             closeA2dpOutputs();
    140         }
    141 #endif
    142         updateDeviceForStrategy();
    143         setOutputDevice(mHardwareOutput, newDevice);
    144 
    145         if (device == AudioSystem::DEVICE_OUT_WIRED_HEADSET) {
    146             device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
    147         } else if (device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO ||
    148                    device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
    149                    device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
    150             device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
    151         } else {
    152             return NO_ERROR;
    153         }
    154     }
    155     // handle input devices
    156     if (AudioSystem::isInputDevice(device)) {
    157 
    158         switch (state)
    159         {
    160         // handle input device connection
    161         case AudioSystem::DEVICE_STATE_AVAILABLE: {
    162             if (mAvailableInputDevices & device) {
    163                 LOGW("setDeviceConnectionState() device already connected: %d", device);
    164                 return INVALID_OPERATION;
    165             }
    166             mAvailableInputDevices |= device;
    167             }
    168             break;
    169 
    170         // handle input device disconnection
    171         case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
    172             if (!(mAvailableInputDevices & device)) {
    173                 LOGW("setDeviceConnectionState() device not connected: %d", device);
    174                 return INVALID_OPERATION;
    175             }
    176             mAvailableInputDevices &= ~device;
    177             } break;
    178 
    179         default:
    180             LOGE("setDeviceConnectionState() invalid state: %x", state);
    181             return BAD_VALUE;
    182         }
    183 
    184         audio_io_handle_t activeInput = getActiveInput();
    185         if (activeInput != 0) {
    186             AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
    187             uint32_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
    188             if (newDevice != inputDesc->mDevice) {
    189                 LOGV("setDeviceConnectionState() changing device from %x to %x for input %d",
    190                         inputDesc->mDevice, newDevice, activeInput);
    191                 inputDesc->mDevice = newDevice;
    192                 AudioParameter param = AudioParameter();
    193                 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
    194                 mpClientInterface->setParameters(activeInput, param.toString());
    195             }
    196         }
    197 
    198         return NO_ERROR;
    199     }
    200 
    201     LOGW("setDeviceConnectionState() invalid device: %x", device);
    202     return BAD_VALUE;
    203 }
    204 
    205 AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(AudioSystem::audio_devices device,
    206                                                   const char *device_address)
    207 {
    208     AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE;
    209     String8 address = String8(device_address);
    210     if (AudioSystem::isOutputDevice(device)) {
    211         if (device & mAvailableOutputDevices) {
    212 #ifdef WITH_A2DP
    213             if (AudioSystem::isA2dpDevice(device) &&
    214                 address != "" && mA2dpDeviceAddress != address) {
    215                 return state;
    216             }
    217 #endif
    218             if (AudioSystem::isBluetoothScoDevice(device) &&
    219                 address != "" && mScoDeviceAddress != address) {
    220                 return state;
    221             }
    222             state = AudioSystem::DEVICE_STATE_AVAILABLE;
    223         }
    224     } else if (AudioSystem::isInputDevice(device)) {
    225         if (device & mAvailableInputDevices) {
    226             state = AudioSystem::DEVICE_STATE_AVAILABLE;
    227         }
    228     }
    229 
    230     return state;
    231 }
    232 
    233 void AudioPolicyManagerBase::setPhoneState(int state)
    234 {
    235     LOGV("setPhoneState() state %d", state);
    236     uint32_t newDevice = 0;
    237     if (state < 0 || state >= AudioSystem::NUM_MODES) {
    238         LOGW("setPhoneState() invalid state %d", state);
    239         return;
    240     }
    241 
    242     if (state == mPhoneState ) {
    243         LOGW("setPhoneState() setting same state %d", state);
    244         return;
    245     }
    246 
    247     // if leaving call state, handle special case of active streams
    248     // pertaining to sonification strategy see handleIncallSonification()
    249     if (mPhoneState == AudioSystem::MODE_IN_CALL) {
    250         LOGV("setPhoneState() in call state management: new state is %d", state);
    251         for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
    252             handleIncallSonification(stream, false, true);
    253         }
    254     }
    255 
    256     // store previous phone state for management of sonification strategy below
    257     int oldState = mPhoneState;
    258     mPhoneState = state;
    259     bool force = false;
    260 
    261     // are we entering or starting a call
    262     if ((oldState != AudioSystem::MODE_IN_CALL) && (state == AudioSystem::MODE_IN_CALL)) {
    263         LOGV("  Entering call in setPhoneState()");
    264         // force routing command to audio hardware when starting a call
    265         // even if no device change is needed
    266         force = true;
    267     } else if ((oldState == AudioSystem::MODE_IN_CALL) && (state != AudioSystem::MODE_IN_CALL)) {
    268         LOGV("  Exiting call in setPhoneState()");
    269         // force routing command to audio hardware when exiting a call
    270         // even if no device change is needed
    271         force = true;
    272     }
    273 
    274     // check for device and output changes triggered by new phone state
    275     newDevice = getNewDevice(mHardwareOutput, false);
    276 #ifdef WITH_A2DP
    277     checkOutputForAllStrategies();
    278     // suspend A2DP output if a SCO device is present.
    279     if (mA2dpOutput != 0 && mScoDeviceAddress != "") {
    280         if (oldState == AudioSystem::MODE_NORMAL) {
    281             mpClientInterface->suspendOutput(mA2dpOutput);
    282         } else if (state == AudioSystem::MODE_NORMAL) {
    283             mpClientInterface->restoreOutput(mA2dpOutput);
    284         }
    285     }
    286 #endif
    287     updateDeviceForStrategy();
    288 
    289     AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
    290 
    291     // force routing command to audio hardware when ending call
    292     // even if no device change is needed
    293     if (oldState == AudioSystem::MODE_IN_CALL && newDevice == 0) {
    294         newDevice = hwOutputDesc->device();
    295     }
    296 
    297     // when changing from ring tone to in call mode, mute the ringing tone
    298     // immediately and delay the route change to avoid sending the ring tone
    299     // tail into the earpiece or headset.
    300     int delayMs = 0;
    301     if (state == AudioSystem::MODE_IN_CALL && oldState == AudioSystem::MODE_RINGTONE) {
    302         // delay the device change command by twice the output latency to have some margin
    303         // and be sure that audio buffers not yet affected by the mute are out when
    304         // we actually apply the route change
    305         delayMs = hwOutputDesc->mLatency*2;
    306         setStreamMute(AudioSystem::RING, true, mHardwareOutput);
    307     }
    308 
    309     // change routing is necessary
    310     setOutputDevice(mHardwareOutput, newDevice, force, delayMs);
    311 
    312     // if entering in call state, handle special case of active streams
    313     // pertaining to sonification strategy see handleIncallSonification()
    314     if (state == AudioSystem::MODE_IN_CALL) {
    315         LOGV("setPhoneState() in call state management: new state is %d", state);
    316         // unmute the ringing tone after a sufficient delay if it was muted before
    317         // setting output device above
    318         if (oldState == AudioSystem::MODE_RINGTONE) {
    319             setStreamMute(AudioSystem::RING, false, mHardwareOutput, MUTE_TIME_MS);
    320         }
    321         for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
    322             handleIncallSonification(stream, true, true);
    323         }
    324     }
    325 
    326     // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
    327     if (state == AudioSystem::MODE_RINGTONE &&
    328         (hwOutputDesc->mRefCount[AudioSystem::MUSIC] ||
    329         (systemTime() - mMusicStopTime) < seconds(SONIFICATION_HEADSET_MUSIC_DELAY))) {
    330         mLimitRingtoneVolume = true;
    331     } else {
    332         mLimitRingtoneVolume = false;
    333     }
    334 }
    335 
    336 void AudioPolicyManagerBase::setRingerMode(uint32_t mode, uint32_t mask)
    337 {
    338     LOGV("setRingerMode() mode %x, mask %x", mode, mask);
    339 
    340     mRingerMode = mode;
    341 }
    342 
    343 void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
    344 {
    345     LOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
    346 
    347     bool forceVolumeReeval = false;
    348     switch(usage) {
    349     case AudioSystem::FOR_COMMUNICATION:
    350         if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
    351             config != AudioSystem::FORCE_NONE) {
    352             LOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
    353             return;
    354         }
    355         mForceUse[usage] = config;
    356         break;
    357     case AudioSystem::FOR_MEDIA:
    358         if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP &&
    359             config != AudioSystem::FORCE_WIRED_ACCESSORY && config != AudioSystem::FORCE_NONE) {
    360             LOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
    361             return;
    362         }
    363         mForceUse[usage] = config;
    364         break;
    365     case AudioSystem::FOR_RECORD:
    366         if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY &&
    367             config != AudioSystem::FORCE_NONE) {
    368             LOGW("setForceUse() invalid config %d for FOR_RECORD", config);
    369             return;
    370         }
    371         mForceUse[usage] = config;
    372         break;
    373     case AudioSystem::FOR_DOCK:
    374         if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK &&
    375             config != AudioSystem::FORCE_BT_DESK_DOCK && config != AudioSystem::FORCE_WIRED_ACCESSORY) {
    376             LOGW("setForceUse() invalid config %d for FOR_DOCK", config);
    377         }
    378         forceVolumeReeval = true;
    379         mForceUse[usage] = config;
    380         break;
    381     default:
    382         LOGW("setForceUse() invalid usage %d", usage);
    383         break;
    384     }
    385 
    386     // check for device and output changes triggered by new phone state
    387     uint32_t newDevice = getNewDevice(mHardwareOutput, false);
    388 #ifdef WITH_A2DP
    389     checkOutputForAllStrategies();
    390 #endif
    391     updateDeviceForStrategy();
    392     setOutputDevice(mHardwareOutput, newDevice);
    393     if (forceVolumeReeval) {
    394         applyStreamVolumes(mHardwareOutput, newDevice);
    395     }
    396 
    397     audio_io_handle_t activeInput = getActiveInput();
    398     if (activeInput != 0) {
    399         AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
    400         newDevice = getDeviceForInputSource(inputDesc->mInputSource);
    401         if (newDevice != inputDesc->mDevice) {
    402             LOGV("setForceUse() changing device from %x to %x for input %d",
    403                     inputDesc->mDevice, newDevice, activeInput);
    404             inputDesc->mDevice = newDevice;
    405             AudioParameter param = AudioParameter();
    406             param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
    407             mpClientInterface->setParameters(activeInput, param.toString());
    408         }
    409     }
    410 
    411 }
    412 
    413 AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage)
    414 {
    415     return mForceUse[usage];
    416 }
    417 
    418 void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value)
    419 {
    420     LOGV("setSystemProperty() property %s, value %s", property, value);
    421     if (strcmp(property, "ro.camera.sound.forced") == 0) {
    422         if (atoi(value)) {
    423             LOGV("ENFORCED_AUDIBLE cannot be muted");
    424             mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = false;
    425         } else {
    426             LOGV("ENFORCED_AUDIBLE can be muted");
    427             mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = true;
    428         }
    429     }
    430 }
    431 
    432 audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream,
    433                                     uint32_t samplingRate,
    434                                     uint32_t format,
    435                                     uint32_t channels,
    436                                     AudioSystem::output_flags flags)
    437 {
    438     audio_io_handle_t output = 0;
    439     uint32_t latency = 0;
    440     routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
    441     uint32_t device = getDeviceForStrategy(strategy);
    442     LOGV("getOutput() stream %d, samplingRate %d, format %d, channels %x, flags %x", stream, samplingRate, format, channels, flags);
    443 
    444 #ifdef AUDIO_POLICY_TEST
    445     if (mCurOutput != 0) {
    446         LOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channels %x, mDirectOutput %d",
    447                 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
    448 
    449         if (mTestOutputs[mCurOutput] == 0) {
    450             LOGV("getOutput() opening test output");
    451             AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
    452             outputDesc->mDevice = mTestDevice;
    453             outputDesc->mSamplingRate = mTestSamplingRate;
    454             outputDesc->mFormat = mTestFormat;
    455             outputDesc->mChannels = mTestChannels;
    456             outputDesc->mLatency = mTestLatencyMs;
    457             outputDesc->mFlags = (AudioSystem::output_flags)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0);
    458             outputDesc->mRefCount[stream] = 0;
    459             mTestOutputs[mCurOutput] = mpClientInterface->openOutput(&outputDesc->mDevice,
    460                                             &outputDesc->mSamplingRate,
    461                                             &outputDesc->mFormat,
    462                                             &outputDesc->mChannels,
    463                                             &outputDesc->mLatency,
    464                                             outputDesc->mFlags);
    465             if (mTestOutputs[mCurOutput]) {
    466                 AudioParameter outputCmd = AudioParameter();
    467                 outputCmd.addInt(String8("set_id"),mCurOutput);
    468                 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
    469                 addOutput(mTestOutputs[mCurOutput], outputDesc);
    470             }
    471         }
    472         return mTestOutputs[mCurOutput];
    473     }
    474 #endif //AUDIO_POLICY_TEST
    475 
    476     // open a direct output if required by specified parameters
    477     if (needsDirectOuput(stream, samplingRate, format, channels, flags, device)) {
    478 
    479         LOGV("getOutput() opening direct output device %x", device);
    480         AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
    481         outputDesc->mDevice = device;
    482         outputDesc->mSamplingRate = samplingRate;
    483         outputDesc->mFormat = format;
    484         outputDesc->mChannels = channels;
    485         outputDesc->mLatency = 0;
    486         outputDesc->mFlags = (AudioSystem::output_flags)(flags | AudioSystem::OUTPUT_FLAG_DIRECT);
    487         outputDesc->mRefCount[stream] = 0;
    488         output = mpClientInterface->openOutput(&outputDesc->mDevice,
    489                                         &outputDesc->mSamplingRate,
    490                                         &outputDesc->mFormat,
    491                                         &outputDesc->mChannels,
    492                                         &outputDesc->mLatency,
    493                                         outputDesc->mFlags);
    494 
    495         // only accept an output with the requeted parameters
    496         if (output == 0 ||
    497             (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
    498             (format != 0 && format != outputDesc->mFormat) ||
    499             (channels != 0 && channels != outputDesc->mChannels)) {
    500             LOGV("getOutput() failed opening direct output: samplingRate %d, format %d, channels %d",
    501                     samplingRate, format, channels);
    502             if (output != 0) {
    503                 mpClientInterface->closeOutput(output);
    504             }
    505             delete outputDesc;
    506             return 0;
    507         }
    508         addOutput(output, outputDesc);
    509         return output;
    510     }
    511 
    512     if (channels != 0 && channels != AudioSystem::CHANNEL_OUT_MONO &&
    513         channels != AudioSystem::CHANNEL_OUT_STEREO) {
    514         return 0;
    515     }
    516     // open a non direct output
    517 
    518     // get which output is suitable for the specified stream. The actual routing change will happen
    519     // when startOutput() will be called
    520     uint32_t a2dpDevice = device & AudioSystem::DEVICE_OUT_ALL_A2DP;
    521     if (AudioSystem::popCount((AudioSystem::audio_devices)device) == 2) {
    522 #ifdef WITH_A2DP
    523         if (a2dpUsedForSonification() && a2dpDevice != 0) {
    524             // if playing on 2 devices among which one is A2DP, use duplicated output
    525             LOGV("getOutput() using duplicated output");
    526             LOGW_IF((mA2dpOutput == 0), "getOutput() A2DP device in multiple %x selected but A2DP output not opened", device);
    527             output = mDuplicatedOutput;
    528         } else
    529 #endif
    530         {
    531             // if playing on 2 devices among which none is A2DP, use hardware output
    532             output = mHardwareOutput;
    533         }
    534         LOGV("getOutput() using output %d for 2 devices %x", output, device);
    535     } else {
    536 #ifdef WITH_A2DP
    537         if (a2dpDevice != 0) {
    538             // if playing on A2DP device, use a2dp output
    539             LOGW_IF((mA2dpOutput == 0), "getOutput() A2DP device %x selected but A2DP output not opened", device);
    540             output = mA2dpOutput;
    541         } else
    542 #endif
    543         {
    544             // if playing on not A2DP device, use hardware output
    545             output = mHardwareOutput;
    546         }
    547     }
    548 
    549 
    550     LOGW_IF((output ==0), "getOutput() could not find output for stream %d, samplingRate %d, format %d, channels %x, flags %x",
    551                 stream, samplingRate, format, channels, flags);
    552 
    553     return output;
    554 }
    555 
    556 status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output,
    557                                              AudioSystem::stream_type stream,
    558                                              int session)
    559 {
    560     LOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
    561     ssize_t index = mOutputs.indexOfKey(output);
    562     if (index < 0) {
    563         LOGW("startOutput() unknow output %d", output);
    564         return BAD_VALUE;
    565     }
    566 
    567     AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
    568     routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
    569 
    570 #ifdef WITH_A2DP
    571     if (mA2dpOutput != 0  && !a2dpUsedForSonification() && strategy == STRATEGY_SONIFICATION) {
    572         setStrategyMute(STRATEGY_MEDIA, true, mA2dpOutput);
    573     }
    574 #endif
    575 
    576     // incremenent usage count for this stream on the requested output:
    577     // NOTE that the usage count is the same for duplicated output and hardware output which is
    578     // necassary for a correct control of hardware output routing by startOutput() and stopOutput()
    579     outputDesc->changeRefCount(stream, 1);
    580 
    581     setOutputDevice(output, getNewDevice(output));
    582 
    583     // handle special case for sonification while in call
    584     if (mPhoneState == AudioSystem::MODE_IN_CALL) {
    585         handleIncallSonification(stream, true, false);
    586     }
    587 
    588     // apply volume rules for current stream and device if necessary
    589     checkAndSetVolume(stream, mStreams[stream].mIndexCur, output, outputDesc->device());
    590 
    591     return NO_ERROR;
    592 }
    593 
    594 status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
    595                                             AudioSystem::stream_type stream,
    596                                             int session)
    597 {
    598     LOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
    599     ssize_t index = mOutputs.indexOfKey(output);
    600     if (index < 0) {
    601         LOGW("stopOutput() unknow output %d", output);
    602         return BAD_VALUE;
    603     }
    604 
    605     AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
    606     routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
    607 
    608     // handle special case for sonification while in call
    609     if (mPhoneState == AudioSystem::MODE_IN_CALL) {
    610         handleIncallSonification(stream, false, false);
    611     }
    612 
    613     if (outputDesc->mRefCount[stream] > 0) {
    614         // decrement usage count of this stream on the output
    615         outputDesc->changeRefCount(stream, -1);
    616         // store time at which the last music track was stopped - see computeVolume()
    617         if (stream == AudioSystem::MUSIC) {
    618             mMusicStopTime = systemTime();
    619         }
    620 
    621         setOutputDevice(output, getNewDevice(output));
    622 
    623 #ifdef WITH_A2DP
    624         if (mA2dpOutput != 0 && !a2dpUsedForSonification() &&
    625                 strategy == STRATEGY_SONIFICATION) {
    626             setStrategyMute(STRATEGY_MEDIA,
    627                             false,
    628                             mA2dpOutput,
    629                             mOutputs.valueFor(mHardwareOutput)->mLatency*2);
    630         }
    631 #endif
    632         if (output != mHardwareOutput) {
    633             setOutputDevice(mHardwareOutput, getNewDevice(mHardwareOutput), true);
    634         }
    635         return NO_ERROR;
    636     } else {
    637         LOGW("stopOutput() refcount is already 0 for output %d", output);
    638         return INVALID_OPERATION;
    639     }
    640 }
    641 
    642 void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
    643 {
    644     LOGV("releaseOutput() %d", output);
    645     ssize_t index = mOutputs.indexOfKey(output);
    646     if (index < 0) {
    647         LOGW("releaseOutput() releasing unknown output %d", output);
    648         return;
    649     }
    650 
    651 #ifdef AUDIO_POLICY_TEST
    652     int testIndex = testOutputIndex(output);
    653     if (testIndex != 0) {
    654         AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
    655         if (outputDesc->refCount() == 0) {
    656             mpClientInterface->closeOutput(output);
    657             delete mOutputs.valueAt(index);
    658             mOutputs.removeItem(output);
    659             mTestOutputs[testIndex] = 0;
    660         }
    661         return;
    662     }
    663 #endif //AUDIO_POLICY_TEST
    664 
    665     if (mOutputs.valueAt(index)->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
    666         mpClientInterface->closeOutput(output);
    667         delete mOutputs.valueAt(index);
    668         mOutputs.removeItem(output);
    669     }
    670 }
    671 
    672 audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
    673                                     uint32_t samplingRate,
    674                                     uint32_t format,
    675                                     uint32_t channels,
    676                                     AudioSystem::audio_in_acoustics acoustics)
    677 {
    678     audio_io_handle_t input = 0;
    679     uint32_t device = getDeviceForInputSource(inputSource);
    680 
    681     LOGV("getInput() inputSource %d, samplingRate %d, format %d, channels %x, acoustics %x", inputSource, samplingRate, format, channels, acoustics);
    682 
    683     if (device == 0) {
    684         return 0;
    685     }
    686 
    687     // adapt channel selection to input source
    688     switch(inputSource) {
    689     case AUDIO_SOURCE_VOICE_UPLINK:
    690         channels = AudioSystem::CHANNEL_IN_VOICE_UPLINK;
    691         break;
    692     case AUDIO_SOURCE_VOICE_DOWNLINK:
    693         channels = AudioSystem::CHANNEL_IN_VOICE_DNLINK;
    694         break;
    695     case AUDIO_SOURCE_VOICE_CALL:
    696         channels = (AudioSystem::CHANNEL_IN_VOICE_UPLINK | AudioSystem::CHANNEL_IN_VOICE_DNLINK);
    697         break;
    698     default:
    699         break;
    700     }
    701 
    702     AudioInputDescriptor *inputDesc = new AudioInputDescriptor();
    703 
    704     inputDesc->mInputSource = inputSource;
    705     inputDesc->mDevice = device;
    706     inputDesc->mSamplingRate = samplingRate;
    707     inputDesc->mFormat = format;
    708     inputDesc->mChannels = channels;
    709     inputDesc->mAcoustics = acoustics;
    710     inputDesc->mRefCount = 0;
    711     input = mpClientInterface->openInput(&inputDesc->mDevice,
    712                                     &inputDesc->mSamplingRate,
    713                                     &inputDesc->mFormat,
    714                                     &inputDesc->mChannels,
    715                                     inputDesc->mAcoustics);
    716 
    717     // only accept input with the exact requested set of parameters
    718     if (input == 0 ||
    719         (samplingRate != inputDesc->mSamplingRate) ||
    720         (format != inputDesc->mFormat) ||
    721         (channels != inputDesc->mChannels)) {
    722         LOGV("getInput() failed opening input: samplingRate %d, format %d, channels %d",
    723                 samplingRate, format, channels);
    724         if (input != 0) {
    725             mpClientInterface->closeInput(input);
    726         }
    727         delete inputDesc;
    728         return 0;
    729     }
    730     mInputs.add(input, inputDesc);
    731     return input;
    732 }
    733 
    734 status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
    735 {
    736     LOGV("startInput() input %d", input);
    737     ssize_t index = mInputs.indexOfKey(input);
    738     if (index < 0) {
    739         LOGW("startInput() unknow input %d", input);
    740         return BAD_VALUE;
    741     }
    742     AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
    743 
    744 #ifdef AUDIO_POLICY_TEST
    745     if (mTestInput == 0)
    746 #endif //AUDIO_POLICY_TEST
    747     {
    748         // refuse 2 active AudioRecord clients at the same time
    749         if (getActiveInput() != 0) {
    750             LOGW("startInput() input %d failed: other input already started", input);
    751             return INVALID_OPERATION;
    752         }
    753     }
    754 
    755     AudioParameter param = AudioParameter();
    756     param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
    757 
    758     // use Voice Recognition mode or not for this input based on input source
    759     int vr_enabled = inputDesc->mInputSource == AUDIO_SOURCE_VOICE_RECOGNITION ? 1 : 0;
    760     param.addInt(String8("vr_mode"), vr_enabled);
    761     LOGV("AudioPolicyManager::startInput(%d), setting vr_mode to %d", inputDesc->mInputSource, vr_enabled);
    762 
    763     mpClientInterface->setParameters(input, param.toString());
    764 
    765     inputDesc->mRefCount = 1;
    766     return NO_ERROR;
    767 }
    768 
    769 status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
    770 {
    771     LOGV("stopInput() input %d", input);
    772     ssize_t index = mInputs.indexOfKey(input);
    773     if (index < 0) {
    774         LOGW("stopInput() unknow input %d", input);
    775         return BAD_VALUE;
    776     }
    777     AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
    778 
    779     if (inputDesc->mRefCount == 0) {
    780         LOGW("stopInput() input %d already stopped", input);
    781         return INVALID_OPERATION;
    782     } else {
    783         AudioParameter param = AudioParameter();
    784         param.addInt(String8(AudioParameter::keyRouting), 0);
    785         mpClientInterface->setParameters(input, param.toString());
    786         inputDesc->mRefCount = 0;
    787         return NO_ERROR;
    788     }
    789 }
    790 
    791 void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
    792 {
    793     LOGV("releaseInput() %d", input);
    794     ssize_t index = mInputs.indexOfKey(input);
    795     if (index < 0) {
    796         LOGW("releaseInput() releasing unknown input %d", input);
    797         return;
    798     }
    799     mpClientInterface->closeInput(input);
    800     delete mInputs.valueAt(index);
    801     mInputs.removeItem(input);
    802     LOGV("releaseInput() exit");
    803 }
    804 
    805 void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
    806                                             int indexMin,
    807                                             int indexMax)
    808 {
    809     LOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
    810     if (indexMin < 0 || indexMin >= indexMax) {
    811         LOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
    812         return;
    813     }
    814     mStreams[stream].mIndexMin = indexMin;
    815     mStreams[stream].mIndexMax = indexMax;
    816 }
    817 
    818 status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream, int index)
    819 {
    820 
    821     if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
    822         return BAD_VALUE;
    823     }
    824 
    825     // Force max volume if stream cannot be muted
    826     if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
    827 
    828     LOGV("setStreamVolumeIndex() stream %d, index %d", stream, index);
    829     mStreams[stream].mIndexCur = index;
    830 
    831     // compute and apply stream volume on all outputs according to connected device
    832     status_t status = NO_ERROR;
    833     for (size_t i = 0; i < mOutputs.size(); i++) {
    834         status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), mOutputs.valueAt(i)->device());
    835         if (volStatus != NO_ERROR) {
    836             status = volStatus;
    837         }
    838     }
    839     return status;
    840 }
    841 
    842 status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream, int *index)
    843 {
    844     if (index == 0) {
    845         return BAD_VALUE;
    846     }
    847     LOGV("getStreamVolumeIndex() stream %d", stream);
    848     *index =  mStreams[stream].mIndexCur;
    849     return NO_ERROR;
    850 }
    851 
    852 audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(effect_descriptor_t *desc)
    853 {
    854     LOGV("getOutputForEffect()");
    855     // apply simple rule where global effects are attached to the same output as MUSIC streams
    856     return getOutput(AudioSystem::MUSIC);
    857 }
    858 
    859 status_t AudioPolicyManagerBase::registerEffect(effect_descriptor_t *desc,
    860                                 audio_io_handle_t output,
    861                                 uint32_t strategy,
    862                                 int session,
    863                                 int id)
    864 {
    865     ssize_t index = mOutputs.indexOfKey(output);
    866     if (index < 0) {
    867         LOGW("registerEffect() unknown output %d", output);
    868         return INVALID_OPERATION;
    869     }
    870 
    871     if (mTotalEffectsCpuLoad + desc->cpuLoad > getMaxEffectsCpuLoad()) {
    872         LOGW("registerEffect() CPU Load limit exceeded for Fx %s, CPU %f MIPS",
    873                 desc->name, (float)desc->cpuLoad/10);
    874         return INVALID_OPERATION;
    875     }
    876     if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
    877         LOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
    878                 desc->name, desc->memoryUsage);
    879         return INVALID_OPERATION;
    880     }
    881     mTotalEffectsCpuLoad += desc->cpuLoad;
    882     mTotalEffectsMemory += desc->memoryUsage;
    883     LOGV("registerEffect() effect %s, output %d, strategy %d session %d id %d",
    884             desc->name, output, strategy, session, id);
    885 
    886     LOGV("registerEffect() CPU %d, memory %d", desc->cpuLoad, desc->memoryUsage);
    887     LOGV("  total CPU %d, total memory %d", mTotalEffectsCpuLoad, mTotalEffectsMemory);
    888 
    889     EffectDescriptor *pDesc = new EffectDescriptor();
    890     memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
    891     pDesc->mOutput = output;
    892     pDesc->mStrategy = (routing_strategy)strategy;
    893     pDesc->mSession = session;
    894     mEffects.add(id, pDesc);
    895 
    896     return NO_ERROR;
    897 }
    898 
    899 status_t AudioPolicyManagerBase::unregisterEffect(int id)
    900 {
    901     ssize_t index = mEffects.indexOfKey(id);
    902     if (index < 0) {
    903         LOGW("unregisterEffect() unknown effect ID %d", id);
    904         return INVALID_OPERATION;
    905     }
    906 
    907     EffectDescriptor *pDesc = mEffects.valueAt(index);
    908 
    909     if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
    910         LOGW("unregisterEffect() CPU load %d too high for total %d",
    911                 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
    912         pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
    913     }
    914     mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
    915     if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
    916         LOGW("unregisterEffect() memory %d too big for total %d",
    917                 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
    918         pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
    919     }
    920     mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
    921     LOGV("unregisterEffect() effect %s, ID %d, CPU %d, memory %d",
    922             pDesc->mDesc.name, id, pDesc->mDesc.cpuLoad, pDesc->mDesc.memoryUsage);
    923     LOGV("  total CPU %d, total memory %d", mTotalEffectsCpuLoad, mTotalEffectsMemory);
    924 
    925     mEffects.removeItem(id);
    926     delete pDesc;
    927 
    928     return NO_ERROR;
    929 }
    930 
    931 status_t AudioPolicyManagerBase::dump(int fd)
    932 {
    933     const size_t SIZE = 256;
    934     char buffer[SIZE];
    935     String8 result;
    936 
    937     snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
    938     result.append(buffer);
    939     snprintf(buffer, SIZE, " Hardware Output: %d\n", mHardwareOutput);
    940     result.append(buffer);
    941 #ifdef WITH_A2DP
    942     snprintf(buffer, SIZE, " A2DP Output: %d\n", mA2dpOutput);
    943     result.append(buffer);
    944     snprintf(buffer, SIZE, " Duplicated Output: %d\n", mDuplicatedOutput);
    945     result.append(buffer);
    946     snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
    947     result.append(buffer);
    948 #endif
    949     snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
    950     result.append(buffer);
    951     snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
    952     result.append(buffer);
    953     snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
    954     result.append(buffer);
    955     snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
    956     result.append(buffer);
    957     snprintf(buffer, SIZE, " Ringer mode: %d\n", mRingerMode);
    958     result.append(buffer);
    959     snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
    960     result.append(buffer);
    961     snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
    962     result.append(buffer);
    963     snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
    964     result.append(buffer);
    965     snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
    966     result.append(buffer);
    967     write(fd, result.string(), result.size());
    968 
    969     snprintf(buffer, SIZE, "\nOutputs dump:\n");
    970     write(fd, buffer, strlen(buffer));
    971     for (size_t i = 0; i < mOutputs.size(); i++) {
    972         snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
    973         write(fd, buffer, strlen(buffer));
    974         mOutputs.valueAt(i)->dump(fd);
    975     }
    976 
    977     snprintf(buffer, SIZE, "\nInputs dump:\n");
    978     write(fd, buffer, strlen(buffer));
    979     for (size_t i = 0; i < mInputs.size(); i++) {
    980         snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
    981         write(fd, buffer, strlen(buffer));
    982         mInputs.valueAt(i)->dump(fd);
    983     }
    984 
    985     snprintf(buffer, SIZE, "\nStreams dump:\n");
    986     write(fd, buffer, strlen(buffer));
    987     snprintf(buffer, SIZE, " Stream  Index Min  Index Max  Index Cur  Can be muted\n");
    988     write(fd, buffer, strlen(buffer));
    989     for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
    990         snprintf(buffer, SIZE, " %02d", i);
    991         mStreams[i].dump(buffer + 3, SIZE);
    992         write(fd, buffer, strlen(buffer));
    993     }
    994 
    995     snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
    996             (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
    997     write(fd, buffer, strlen(buffer));
    998 
    999     snprintf(buffer, SIZE, "Registered effects:\n");
   1000     write(fd, buffer, strlen(buffer));
   1001     for (size_t i = 0; i < mEffects.size(); i++) {
   1002         snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
   1003         write(fd, buffer, strlen(buffer));
   1004         mEffects.valueAt(i)->dump(fd);
   1005     }
   1006 
   1007 
   1008     return NO_ERROR;
   1009 }
   1010 
   1011 // ----------------------------------------------------------------------------
   1012 // AudioPolicyManagerBase
   1013 // ----------------------------------------------------------------------------
   1014 
   1015 AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
   1016     :
   1017 #ifdef AUDIO_POLICY_TEST
   1018     Thread(false),
   1019 #endif //AUDIO_POLICY_TEST
   1020     mPhoneState(AudioSystem::MODE_NORMAL), mRingerMode(0), mMusicStopTime(0),
   1021     mLimitRingtoneVolume(false), mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0)
   1022 {
   1023     mpClientInterface = clientInterface;
   1024 
   1025     for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
   1026         mForceUse[i] = AudioSystem::FORCE_NONE;
   1027     }
   1028 
   1029     // devices available by default are speaker, ear piece and microphone
   1030     mAvailableOutputDevices = AudioSystem::DEVICE_OUT_EARPIECE |
   1031                         AudioSystem::DEVICE_OUT_SPEAKER;
   1032     mAvailableInputDevices = AudioSystem::DEVICE_IN_BUILTIN_MIC;
   1033 
   1034 #ifdef WITH_A2DP
   1035     mA2dpOutput = 0;
   1036     mDuplicatedOutput = 0;
   1037     mA2dpDeviceAddress = String8("");
   1038 #endif
   1039     mScoDeviceAddress = String8("");
   1040 
   1041     // open hardware output
   1042     AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
   1043     outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER;
   1044     mHardwareOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
   1045                                     &outputDesc->mSamplingRate,
   1046                                     &outputDesc->mFormat,
   1047                                     &outputDesc->mChannels,
   1048                                     &outputDesc->mLatency,
   1049                                     outputDesc->mFlags);
   1050 
   1051     if (mHardwareOutput == 0) {
   1052         LOGE("Failed to initialize hardware output stream, samplingRate: %d, format %d, channels %d",
   1053                 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannels);
   1054     } else {
   1055         addOutput(mHardwareOutput, outputDesc);
   1056         setOutputDevice(mHardwareOutput, (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER, true);
   1057         //TODO: configure audio effect output stage here
   1058     }
   1059 
   1060     updateDeviceForStrategy();
   1061 #ifdef AUDIO_POLICY_TEST
   1062     AudioParameter outputCmd = AudioParameter();
   1063     outputCmd.addInt(String8("set_id"), 0);
   1064     mpClientInterface->setParameters(mHardwareOutput, outputCmd.toString());
   1065 
   1066     mTestDevice = AudioSystem::DEVICE_OUT_SPEAKER;
   1067     mTestSamplingRate = 44100;
   1068     mTestFormat = AudioSystem::PCM_16_BIT;
   1069     mTestChannels =  AudioSystem::CHANNEL_OUT_STEREO;
   1070     mTestLatencyMs = 0;
   1071     mCurOutput = 0;
   1072     mDirectOutput = false;
   1073     for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
   1074         mTestOutputs[i] = 0;
   1075     }
   1076 
   1077     const size_t SIZE = 256;
   1078     char buffer[SIZE];
   1079     snprintf(buffer, SIZE, "AudioPolicyManagerTest");
   1080     run(buffer, ANDROID_PRIORITY_AUDIO);
   1081 #endif //AUDIO_POLICY_TEST
   1082 }
   1083 
   1084 AudioPolicyManagerBase::~AudioPolicyManagerBase()
   1085 {
   1086 #ifdef AUDIO_POLICY_TEST
   1087     exit();
   1088 #endif //AUDIO_POLICY_TEST
   1089    for (size_t i = 0; i < mOutputs.size(); i++) {
   1090         mpClientInterface->closeOutput(mOutputs.keyAt(i));
   1091         delete mOutputs.valueAt(i);
   1092    }
   1093    mOutputs.clear();
   1094    for (size_t i = 0; i < mInputs.size(); i++) {
   1095         mpClientInterface->closeInput(mInputs.keyAt(i));
   1096         delete mInputs.valueAt(i);
   1097    }
   1098    mInputs.clear();
   1099 }
   1100 
   1101 #ifdef AUDIO_POLICY_TEST
   1102 bool AudioPolicyManagerBase::threadLoop()
   1103 {
   1104     LOGV("entering threadLoop()");
   1105     while (!exitPending())
   1106     {
   1107         String8 command;
   1108         int valueInt;
   1109         String8 value;
   1110 
   1111         Mutex::Autolock _l(mLock);
   1112         mWaitWorkCV.waitRelative(mLock, milliseconds(50));
   1113 
   1114         command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
   1115         AudioParameter param = AudioParameter(command);
   1116 
   1117         if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
   1118             valueInt != 0) {
   1119             LOGV("Test command %s received", command.string());
   1120             String8 target;
   1121             if (param.get(String8("target"), target) != NO_ERROR) {
   1122                 target = "Manager";
   1123             }
   1124             if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
   1125                 param.remove(String8("test_cmd_policy_output"));
   1126                 mCurOutput = valueInt;
   1127             }
   1128             if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
   1129                 param.remove(String8("test_cmd_policy_direct"));
   1130                 if (value == "false") {
   1131                     mDirectOutput = false;
   1132                 } else if (value == "true") {
   1133                     mDirectOutput = true;
   1134                 }
   1135             }
   1136             if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
   1137                 param.remove(String8("test_cmd_policy_input"));
   1138                 mTestInput = valueInt;
   1139             }
   1140 
   1141             if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
   1142                 param.remove(String8("test_cmd_policy_format"));
   1143                 int format = AudioSystem::INVALID_FORMAT;
   1144                 if (value == "PCM 16 bits") {
   1145                     format = AudioSystem::PCM_16_BIT;
   1146                 } else if (value == "PCM 8 bits") {
   1147                     format = AudioSystem::PCM_8_BIT;
   1148                 } else if (value == "Compressed MP3") {
   1149                     format = AudioSystem::MP3;
   1150                 }
   1151                 if (format != AudioSystem::INVALID_FORMAT) {
   1152                     if (target == "Manager") {
   1153                         mTestFormat = format;
   1154                     } else if (mTestOutputs[mCurOutput] != 0) {
   1155                         AudioParameter outputParam = AudioParameter();
   1156                         outputParam.addInt(String8("format"), format);
   1157                         mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
   1158                     }
   1159                 }
   1160             }
   1161             if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
   1162                 param.remove(String8("test_cmd_policy_channels"));
   1163                 int channels = 0;
   1164 
   1165                 if (value == "Channels Stereo") {
   1166                     channels =  AudioSystem::CHANNEL_OUT_STEREO;
   1167                 } else if (value == "Channels Mono") {
   1168                     channels =  AudioSystem::CHANNEL_OUT_MONO;
   1169                 }
   1170                 if (channels != 0) {
   1171                     if (target == "Manager") {
   1172                         mTestChannels = channels;
   1173                     } else if (mTestOutputs[mCurOutput] != 0) {
   1174                         AudioParameter outputParam = AudioParameter();
   1175                         outputParam.addInt(String8("channels"), channels);
   1176                         mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
   1177                     }
   1178                 }
   1179             }
   1180             if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
   1181                 param.remove(String8("test_cmd_policy_sampleRate"));
   1182                 if (valueInt >= 0 && valueInt <= 96000) {
   1183                     int samplingRate = valueInt;
   1184                     if (target == "Manager") {
   1185                         mTestSamplingRate = samplingRate;
   1186                     } else if (mTestOutputs[mCurOutput] != 0) {
   1187                         AudioParameter outputParam = AudioParameter();
   1188                         outputParam.addInt(String8("sampling_rate"), samplingRate);
   1189                         mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
   1190                     }
   1191                 }
   1192             }
   1193 
   1194             if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
   1195                 param.remove(String8("test_cmd_policy_reopen"));
   1196 
   1197                 mpClientInterface->closeOutput(mHardwareOutput);
   1198                 delete mOutputs.valueFor(mHardwareOutput);
   1199                 mOutputs.removeItem(mHardwareOutput);
   1200 
   1201                 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
   1202                 outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER;
   1203                 mHardwareOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
   1204                                                 &outputDesc->mSamplingRate,
   1205                                                 &outputDesc->mFormat,
   1206                                                 &outputDesc->mChannels,
   1207                                                 &outputDesc->mLatency,
   1208                                                 outputDesc->mFlags);
   1209                 if (mHardwareOutput == 0) {
   1210                     LOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
   1211                             outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannels);
   1212                 } else {
   1213                     AudioParameter outputCmd = AudioParameter();
   1214                     outputCmd.addInt(String8("set_id"), 0);
   1215                     mpClientInterface->setParameters(mHardwareOutput, outputCmd.toString());
   1216                     addOutput(mHardwareOutput, outputDesc);
   1217                 }
   1218             }
   1219 
   1220 
   1221             mpClientInterface->setParameters(0, String8("test_cmd_policy="));
   1222         }
   1223     }
   1224     return false;
   1225 }
   1226 
   1227 void AudioPolicyManagerBase::exit()
   1228 {
   1229     {
   1230         AutoMutex _l(mLock);
   1231         requestExit();
   1232         mWaitWorkCV.signal();
   1233     }
   1234     requestExitAndWait();
   1235 }
   1236 
   1237 int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
   1238 {
   1239     for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
   1240         if (output == mTestOutputs[i]) return i;
   1241     }
   1242     return 0;
   1243 }
   1244 #endif //AUDIO_POLICY_TEST
   1245 
   1246 // ---
   1247 
   1248 void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
   1249 {
   1250     outputDesc->mId = id;
   1251     mOutputs.add(id, outputDesc);
   1252 }
   1253 
   1254 
   1255 #ifdef WITH_A2DP
   1256 status_t AudioPolicyManagerBase::handleA2dpConnection(AudioSystem::audio_devices device,
   1257                                                  const char *device_address)
   1258 {
   1259     // when an A2DP device is connected, open an A2DP and a duplicated output
   1260     LOGV("opening A2DP output for device %s", device_address);
   1261     AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
   1262     outputDesc->mDevice = device;
   1263     mA2dpOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
   1264                                             &outputDesc->mSamplingRate,
   1265                                             &outputDesc->mFormat,
   1266                                             &outputDesc->mChannels,
   1267                                             &outputDesc->mLatency,
   1268                                             outputDesc->mFlags);
   1269     if (mA2dpOutput) {
   1270         // add A2DP output descriptor
   1271         addOutput(mA2dpOutput, outputDesc);
   1272 
   1273         //TODO: configure audio effect output stage here
   1274 
   1275         // set initial stream volume for A2DP device
   1276         applyStreamVolumes(mA2dpOutput, device);
   1277         if (a2dpUsedForSonification()) {
   1278             mDuplicatedOutput = mpClientInterface->openDuplicateOutput(mA2dpOutput, mHardwareOutput);
   1279         }
   1280         if (mDuplicatedOutput != 0 ||
   1281             !a2dpUsedForSonification()) {
   1282             // If both A2DP and duplicated outputs are open, send device address to A2DP hardware
   1283             // interface
   1284             AudioParameter param;
   1285             param.add(String8("a2dp_sink_address"), String8(device_address));
   1286             mpClientInterface->setParameters(mA2dpOutput, param.toString());
   1287             mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
   1288 
   1289             if (a2dpUsedForSonification()) {
   1290                 // add duplicated output descriptor
   1291                 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor();
   1292                 dupOutputDesc->mOutput1 = mOutputs.valueFor(mHardwareOutput);
   1293                 dupOutputDesc->mOutput2 = mOutputs.valueFor(mA2dpOutput);
   1294                 dupOutputDesc->mSamplingRate = outputDesc->mSamplingRate;
   1295                 dupOutputDesc->mFormat = outputDesc->mFormat;
   1296                 dupOutputDesc->mChannels = outputDesc->mChannels;
   1297                 dupOutputDesc->mLatency = outputDesc->mLatency;
   1298                 addOutput(mDuplicatedOutput, dupOutputDesc);
   1299                 applyStreamVolumes(mDuplicatedOutput, device);
   1300             }
   1301         } else {
   1302             LOGW("getOutput() could not open duplicated output for %d and %d",
   1303                     mHardwareOutput, mA2dpOutput);
   1304             mpClientInterface->closeOutput(mA2dpOutput);
   1305             mOutputs.removeItem(mA2dpOutput);
   1306             mA2dpOutput = 0;
   1307             delete outputDesc;
   1308             return NO_INIT;
   1309         }
   1310     } else {
   1311         LOGW("setDeviceConnectionState() could not open A2DP output for device %x", device);
   1312         delete outputDesc;
   1313         return NO_INIT;
   1314     }
   1315     AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
   1316 
   1317     if (mScoDeviceAddress != "") {
   1318         // It is normal to suspend twice if we are both in call,
   1319         // and have the hardware audio output routed to BT SCO
   1320         if (mPhoneState != AudioSystem::MODE_NORMAL) {
   1321             mpClientInterface->suspendOutput(mA2dpOutput);
   1322         }
   1323         if (AudioSystem::isBluetoothScoDevice((AudioSystem::audio_devices)hwOutputDesc->device())) {
   1324             mpClientInterface->suspendOutput(mA2dpOutput);
   1325         }
   1326     }
   1327 
   1328     if (!a2dpUsedForSonification()) {
   1329         // mute music on A2DP output if a notification or ringtone is playing
   1330         uint32_t refCount = hwOutputDesc->strategyRefCount(STRATEGY_SONIFICATION);
   1331         for (uint32_t i = 0; i < refCount; i++) {
   1332             setStrategyMute(STRATEGY_MEDIA, true, mA2dpOutput);
   1333         }
   1334     }
   1335     return NO_ERROR;
   1336 }
   1337 
   1338 status_t AudioPolicyManagerBase::handleA2dpDisconnection(AudioSystem::audio_devices device,
   1339                                                     const char *device_address)
   1340 {
   1341     if (mA2dpOutput == 0) {
   1342         LOGW("setDeviceConnectionState() disconnecting A2DP and no A2DP output!");
   1343         return INVALID_OPERATION;
   1344     }
   1345 
   1346     if (mA2dpDeviceAddress != device_address) {
   1347         LOGW("setDeviceConnectionState() disconnecting unknow A2DP sink address %s", device_address);
   1348         return INVALID_OPERATION;
   1349     }
   1350 
   1351     // mute media strategy to avoid outputting sound on hardware output while music stream
   1352     // is switched from A2DP output and before music is paused by music application
   1353     setStrategyMute(STRATEGY_MEDIA, true, mHardwareOutput);
   1354     setStrategyMute(STRATEGY_MEDIA, false, mHardwareOutput, MUTE_TIME_MS);
   1355 
   1356     if (!a2dpUsedForSonification()) {
   1357         // unmute music on A2DP output if a notification or ringtone is playing
   1358         uint32_t refCount = mOutputs.valueFor(mHardwareOutput)->strategyRefCount(STRATEGY_SONIFICATION);
   1359         for (uint32_t i = 0; i < refCount; i++) {
   1360             setStrategyMute(STRATEGY_MEDIA, false, mA2dpOutput);
   1361         }
   1362     }
   1363     mA2dpDeviceAddress = "";
   1364     return NO_ERROR;
   1365 }
   1366 
   1367 void AudioPolicyManagerBase::closeA2dpOutputs()
   1368 {
   1369     LOGV("setDeviceConnectionState() closing A2DP and duplicated output!");
   1370 
   1371     if (mDuplicatedOutput != 0) {
   1372         AudioOutputDescriptor *dupOutputDesc = mOutputs.valueFor(mDuplicatedOutput);
   1373         AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
   1374         // As all active tracks on duplicated output will be deleted,
   1375         // and as they were also referenced on hardware output, the reference
   1376         // count for their stream type must be adjusted accordingly on
   1377         // hardware output.
   1378         for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
   1379             int refCount = dupOutputDesc->mRefCount[i];
   1380             hwOutputDesc->changeRefCount((AudioSystem::stream_type)i,-refCount);
   1381         }
   1382 
   1383         mpClientInterface->closeOutput(mDuplicatedOutput);
   1384         delete mOutputs.valueFor(mDuplicatedOutput);
   1385         mOutputs.removeItem(mDuplicatedOutput);
   1386         mDuplicatedOutput = 0;
   1387     }
   1388     if (mA2dpOutput != 0) {
   1389         AudioParameter param;
   1390         param.add(String8("closing"), String8("true"));
   1391         mpClientInterface->setParameters(mA2dpOutput, param.toString());
   1392 
   1393         mpClientInterface->closeOutput(mA2dpOutput);
   1394         delete mOutputs.valueFor(mA2dpOutput);
   1395         mOutputs.removeItem(mA2dpOutput);
   1396         mA2dpOutput = 0;
   1397     }
   1398 }
   1399 
   1400 void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy)
   1401 {
   1402     uint32_t prevDevice = getDeviceForStrategy(strategy);
   1403     uint32_t curDevice = getDeviceForStrategy(strategy, false);
   1404     bool a2dpWasUsed = AudioSystem::isA2dpDevice((AudioSystem::audio_devices)(prevDevice & ~AudioSystem::DEVICE_OUT_SPEAKER));
   1405     bool a2dpIsUsed = AudioSystem::isA2dpDevice((AudioSystem::audio_devices)(curDevice & ~AudioSystem::DEVICE_OUT_SPEAKER));
   1406     audio_io_handle_t srcOutput = 0;
   1407     audio_io_handle_t dstOutput = 0;
   1408 
   1409     if (a2dpWasUsed && !a2dpIsUsed) {
   1410         bool dupUsed = a2dpUsedForSonification() && a2dpWasUsed && (AudioSystem::popCount(prevDevice) == 2);
   1411         dstOutput = mHardwareOutput;
   1412         if (dupUsed) {
   1413             LOGV("checkOutputForStrategy() moving strategy %d from duplicated", strategy);
   1414             srcOutput = mDuplicatedOutput;
   1415         } else {
   1416             LOGV("checkOutputForStrategy() moving strategy %d from a2dp", strategy);
   1417             srcOutput = mA2dpOutput;
   1418         }
   1419     }
   1420     if (a2dpIsUsed && !a2dpWasUsed) {
   1421         bool dupUsed = a2dpUsedForSonification() && a2dpIsUsed && (AudioSystem::popCount(curDevice) == 2);
   1422         srcOutput = mHardwareOutput;
   1423         if (dupUsed) {
   1424             LOGV("checkOutputForStrategy() moving strategy %d to duplicated", strategy);
   1425             dstOutput = mDuplicatedOutput;
   1426         } else {
   1427             LOGV("checkOutputForStrategy() moving strategy %d to a2dp", strategy);
   1428             dstOutput = mA2dpOutput;
   1429         }
   1430     }
   1431 
   1432     if (srcOutput != 0 && dstOutput != 0) {
   1433         // Move effects associated to this strategy from previous output to new output
   1434         for (size_t i = 0; i < mEffects.size(); i++) {
   1435             EffectDescriptor *desc = mEffects.valueAt(i);
   1436             if (desc->mSession != AudioSystem::SESSION_OUTPUT_STAGE &&
   1437                     desc->mStrategy == strategy &&
   1438                     desc->mOutput == srcOutput) {
   1439                 LOGV("checkOutputForStrategy() moving effect %d to output %d", mEffects.keyAt(i), dstOutput);
   1440                 mpClientInterface->moveEffects(desc->mSession, srcOutput, dstOutput);
   1441                 desc->mOutput = dstOutput;
   1442             }
   1443         }
   1444         // Move tracks associated to this strategy from previous output to new output
   1445         for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
   1446             if (getStrategy((AudioSystem::stream_type)i) == strategy) {
   1447                 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i, dstOutput);
   1448             }
   1449         }
   1450     }
   1451 }
   1452 
   1453 void AudioPolicyManagerBase::checkOutputForAllStrategies()
   1454 {
   1455     checkOutputForStrategy(STRATEGY_PHONE);
   1456     checkOutputForStrategy(STRATEGY_SONIFICATION);
   1457     checkOutputForStrategy(STRATEGY_MEDIA);
   1458     checkOutputForStrategy(STRATEGY_DTMF);
   1459 }
   1460 
   1461 #endif
   1462 
   1463 uint32_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
   1464 {
   1465     uint32_t device = 0;
   1466 
   1467     AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
   1468     // check the following by order of priority to request a routing change if necessary:
   1469     // 1: we are in call or the strategy phone is active on the hardware output:
   1470     //      use device for strategy phone
   1471     // 2: the strategy sonification is active on the hardware output:
   1472     //      use device for strategy sonification
   1473     // 3: the strategy media is active on the hardware output:
   1474     //      use device for strategy media
   1475     // 4: the strategy DTMF is active on the hardware output:
   1476     //      use device for strategy DTMF
   1477     if (mPhoneState == AudioSystem::MODE_IN_CALL ||
   1478         outputDesc->isUsedByStrategy(STRATEGY_PHONE)) {
   1479         device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
   1480     } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION)) {
   1481         device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
   1482     } else if (outputDesc->isUsedByStrategy(STRATEGY_MEDIA)) {
   1483         device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
   1484     } else if (outputDesc->isUsedByStrategy(STRATEGY_DTMF)) {
   1485         device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
   1486     }
   1487 
   1488     LOGV("getNewDevice() selected device %x", device);
   1489     return device;
   1490 }
   1491 
   1492 uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
   1493     return (uint32_t)getStrategy(stream);
   1494 }
   1495 
   1496 AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
   1497         AudioSystem::stream_type stream) {
   1498     // stream to strategy mapping
   1499     switch (stream) {
   1500     case AudioSystem::VOICE_CALL:
   1501     case AudioSystem::BLUETOOTH_SCO:
   1502         return STRATEGY_PHONE;
   1503     case AudioSystem::RING:
   1504     case AudioSystem::NOTIFICATION:
   1505     case AudioSystem::ALARM:
   1506     case AudioSystem::ENFORCED_AUDIBLE:
   1507         return STRATEGY_SONIFICATION;
   1508     case AudioSystem::DTMF:
   1509         return STRATEGY_DTMF;
   1510     default:
   1511         LOGE("unknown stream type");
   1512     case AudioSystem::SYSTEM:
   1513         // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
   1514         // while key clicks are played produces a poor result
   1515     case AudioSystem::TTS:
   1516     case AudioSystem::MUSIC:
   1517         return STRATEGY_MEDIA;
   1518     }
   1519 }
   1520 
   1521 uint32_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy, bool fromCache)
   1522 {
   1523     uint32_t device = 0;
   1524 
   1525     if (fromCache) {
   1526         LOGV("getDeviceForStrategy() from cache strategy %d, device %x", strategy, mDeviceForStrategy[strategy]);
   1527         return mDeviceForStrategy[strategy];
   1528     }
   1529 
   1530     switch (strategy) {
   1531     case STRATEGY_DTMF:
   1532         if (mPhoneState != AudioSystem::MODE_IN_CALL) {
   1533             // when off call, DTMF strategy follows the same rules as MEDIA strategy
   1534             device = getDeviceForStrategy(STRATEGY_MEDIA, false);
   1535             break;
   1536         }
   1537         // when in call, DTMF and PHONE strategies follow the same rules
   1538         // FALL THROUGH
   1539 
   1540     case STRATEGY_PHONE:
   1541         // for phone strategy, we first consider the forced use and then the available devices by order
   1542         // of priority
   1543         switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
   1544         case AudioSystem::FORCE_BT_SCO:
   1545             if (mPhoneState != AudioSystem::MODE_IN_CALL || strategy != STRATEGY_DTMF) {
   1546                 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
   1547                 if (device) break;
   1548             }
   1549             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
   1550             if (device) break;
   1551             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO;
   1552             if (device) break;
   1553             // if SCO device is requested but no SCO device is available, fall back to default case
   1554             // FALL THROUGH
   1555 
   1556         default:    // FORCE_NONE
   1557             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
   1558             if (device) break;
   1559             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
   1560             if (device) break;
   1561 #ifdef WITH_A2DP
   1562             // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
   1563             if (mPhoneState != AudioSystem::MODE_IN_CALL) {
   1564                 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
   1565                 if (device) break;
   1566                 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
   1567                 if (device) break;
   1568             }
   1569 #endif
   1570             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_EARPIECE;
   1571             if (device == 0) {
   1572                 LOGE("getDeviceForStrategy() earpiece device not found");
   1573             }
   1574             break;
   1575 
   1576         case AudioSystem::FORCE_SPEAKER:
   1577             if (mPhoneState != AudioSystem::MODE_IN_CALL || strategy != STRATEGY_DTMF) {
   1578                 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
   1579                 if (device) break;
   1580             }
   1581 #ifdef WITH_A2DP
   1582             // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
   1583             // A2DP speaker when forcing to speaker output
   1584             if (mPhoneState != AudioSystem::MODE_IN_CALL) {
   1585                 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
   1586                 if (device) break;
   1587             }
   1588 #endif
   1589             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
   1590             if (device == 0) {
   1591                 LOGE("getDeviceForStrategy() speaker device not found");
   1592             }
   1593             break;
   1594         }
   1595     break;
   1596 
   1597     case STRATEGY_SONIFICATION:
   1598 
   1599         // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
   1600         // handleIncallSonification().
   1601         if (mPhoneState == AudioSystem::MODE_IN_CALL) {
   1602             device = getDeviceForStrategy(STRATEGY_PHONE, false);
   1603             break;
   1604         }
   1605         device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
   1606         if (device == 0) {
   1607             LOGE("getDeviceForStrategy() speaker device not found");
   1608         }
   1609         // The second device used for sonification is the same as the device used by media strategy
   1610         // FALL THROUGH
   1611 
   1612     case STRATEGY_MEDIA: {
   1613         uint32_t device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
   1614         if (device2 == 0) {
   1615             device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
   1616         }
   1617         if (device2 == 0) {
   1618             device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
   1619         }
   1620 #ifdef WITH_A2DP
   1621         if (mA2dpOutput != 0) {
   1622             if (strategy == STRATEGY_SONIFICATION && !a2dpUsedForSonification()) {
   1623                 break;
   1624             }
   1625             if (device2 == 0) {
   1626                 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
   1627             }
   1628             if (device2 == 0) {
   1629                 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
   1630             }
   1631             if (device2 == 0) {
   1632                 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
   1633             }
   1634         }
   1635 #endif
   1636         if (device2 == 0) {
   1637             device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
   1638         }
   1639 
   1640         // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION, 0 otherwise
   1641         device |= device2;
   1642         if (device == 0) {
   1643             LOGE("getDeviceForStrategy() speaker device not found");
   1644         }
   1645         } break;
   1646 
   1647     default:
   1648         LOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
   1649         break;
   1650     }
   1651 
   1652     LOGV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
   1653     return device;
   1654 }
   1655 
   1656 void AudioPolicyManagerBase::updateDeviceForStrategy()
   1657 {
   1658     for (int i = 0; i < NUM_STRATEGIES; i++) {
   1659         mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false);
   1660     }
   1661 }
   1662 
   1663 void AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output, uint32_t device, bool force, int delayMs)
   1664 {
   1665     LOGV("setOutputDevice() output %d device %x delayMs %d", output, device, delayMs);
   1666     AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
   1667 
   1668 
   1669     if (outputDesc->isDuplicated()) {
   1670         setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
   1671         setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
   1672         return;
   1673     }
   1674 #ifdef WITH_A2DP
   1675     // filter devices according to output selected
   1676     if (output == mA2dpOutput) {
   1677         device &= AudioSystem::DEVICE_OUT_ALL_A2DP;
   1678     } else {
   1679         device &= ~AudioSystem::DEVICE_OUT_ALL_A2DP;
   1680     }
   1681 #endif
   1682 
   1683     uint32_t prevDevice = (uint32_t)outputDesc->device();
   1684     // Do not change the routing if:
   1685     //  - the requestede device is 0
   1686     //  - the requested device is the same as current device and force is not specified.
   1687     // Doing this check here allows the caller to call setOutputDevice() without conditions
   1688     if ((device == 0 || device == prevDevice) && !force) {
   1689         LOGV("setOutputDevice() setting same device %x or null device for output %d", device, output);
   1690         return;
   1691     }
   1692 
   1693     outputDesc->mDevice = device;
   1694     // mute media streams if both speaker and headset are selected
   1695     if (output == mHardwareOutput && AudioSystem::popCount(device) == 2) {
   1696         setStrategyMute(STRATEGY_MEDIA, true, output);
   1697         // wait for the PCM output buffers to empty before proceeding with the rest of the command
   1698         usleep(outputDesc->mLatency*2*1000);
   1699     }
   1700 #ifdef WITH_A2DP
   1701     // suspend A2DP output if SCO device is selected
   1702     if (AudioSystem::isBluetoothScoDevice((AudioSystem::audio_devices)device)) {
   1703          if (mA2dpOutput != 0) {
   1704              mpClientInterface->suspendOutput(mA2dpOutput);
   1705          }
   1706     }
   1707 #endif
   1708     // do the routing
   1709     AudioParameter param = AudioParameter();
   1710     param.addInt(String8(AudioParameter::keyRouting), (int)device);
   1711     mpClientInterface->setParameters(mHardwareOutput, param.toString(), delayMs);
   1712     // update stream volumes according to new device
   1713     applyStreamVolumes(output, device, delayMs);
   1714 
   1715 #ifdef WITH_A2DP
   1716     // if disconnecting SCO device, restore A2DP output
   1717     if (AudioSystem::isBluetoothScoDevice((AudioSystem::audio_devices)prevDevice)) {
   1718          if (mA2dpOutput != 0) {
   1719              LOGV("restore A2DP output");
   1720              mpClientInterface->restoreOutput(mA2dpOutput);
   1721          }
   1722     }
   1723 #endif
   1724     // if changing from a combined headset + speaker route, unmute media streams
   1725     if (output == mHardwareOutput && AudioSystem::popCount(prevDevice) == 2) {
   1726         setStrategyMute(STRATEGY_MEDIA, false, output, delayMs);
   1727     }
   1728 }
   1729 
   1730 uint32_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
   1731 {
   1732     uint32_t device;
   1733 
   1734     switch(inputSource) {
   1735     case AUDIO_SOURCE_DEFAULT:
   1736     case AUDIO_SOURCE_MIC:
   1737     case AUDIO_SOURCE_VOICE_RECOGNITION:
   1738         if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
   1739             mAvailableInputDevices & AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
   1740             device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
   1741         } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_WIRED_HEADSET) {
   1742             device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
   1743         } else {
   1744             device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
   1745         }
   1746         break;
   1747     case AUDIO_SOURCE_CAMCORDER:
   1748         if (hasBackMicrophone()) {
   1749             device = AudioSystem::DEVICE_IN_BACK_MIC;
   1750         } else {
   1751             device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
   1752         }
   1753         break;
   1754     case AUDIO_SOURCE_VOICE_UPLINK:
   1755     case AUDIO_SOURCE_VOICE_DOWNLINK:
   1756     case AUDIO_SOURCE_VOICE_CALL:
   1757         device = AudioSystem::DEVICE_IN_VOICE_CALL;
   1758         break;
   1759     default:
   1760         LOGW("getInput() invalid input source %d", inputSource);
   1761         device = 0;
   1762         break;
   1763     }
   1764     LOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
   1765     return device;
   1766 }
   1767 
   1768 audio_io_handle_t AudioPolicyManagerBase::getActiveInput()
   1769 {
   1770     for (size_t i = 0; i < mInputs.size(); i++) {
   1771         if (mInputs.valueAt(i)->mRefCount > 0) {
   1772             return mInputs.keyAt(i);
   1773         }
   1774     }
   1775     return 0;
   1776 }
   1777 
   1778 float AudioPolicyManagerBase::computeVolume(int stream, int index, audio_io_handle_t output, uint32_t device)
   1779 {
   1780     float volume = 1.0;
   1781     AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
   1782     StreamDescriptor &streamDesc = mStreams[stream];
   1783 
   1784     if (device == 0) {
   1785         device = outputDesc->device();
   1786     }
   1787 
   1788     int volInt = (100 * (index - streamDesc.mIndexMin)) / (streamDesc.mIndexMax - streamDesc.mIndexMin);
   1789     volume = AudioSystem::linearToLog(volInt);
   1790 
   1791     // if a headset is connected, apply the following rules to ring tones and notifications
   1792     // to avoid sound level bursts in user's ears:
   1793     // - always attenuate ring tones and notifications volume by 6dB
   1794     // - if music is playing, always limit the volume to current music volume,
   1795     // with a minimum threshold at -36dB so that notification is always perceived.
   1796     if ((device &
   1797         (AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP |
   1798         AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
   1799         AudioSystem::DEVICE_OUT_WIRED_HEADSET |
   1800         AudioSystem::DEVICE_OUT_WIRED_HEADPHONE)) &&
   1801         (getStrategy((AudioSystem::stream_type)stream) == STRATEGY_SONIFICATION) &&
   1802         streamDesc.mCanBeMuted) {
   1803         volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
   1804         // when the phone is ringing we must consider that music could have been paused just before
   1805         // by the music application and behave as if music was active if the last music track was
   1806         // just stopped
   1807         if (outputDesc->mRefCount[AudioSystem::MUSIC] || mLimitRingtoneVolume) {
   1808             float musicVol = computeVolume(AudioSystem::MUSIC, mStreams[AudioSystem::MUSIC].mIndexCur, output, device);
   1809             float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ? musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
   1810             if (volume > minVol) {
   1811                 volume = minVol;
   1812                 LOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
   1813             }
   1814         }
   1815     }
   1816 
   1817     return volume;
   1818 }
   1819 
   1820 status_t AudioPolicyManagerBase::checkAndSetVolume(int stream, int index, audio_io_handle_t output, uint32_t device, int delayMs, bool force)
   1821 {
   1822 
   1823     // do not change actual stream volume if the stream is muted
   1824     if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
   1825         LOGV("checkAndSetVolume() stream %d muted count %d", stream, mOutputs.valueFor(output)->mMuteCount[stream]);
   1826         return NO_ERROR;
   1827     }
   1828 
   1829     // do not change in call volume if bluetooth is connected and vice versa
   1830     if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
   1831         (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
   1832         LOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
   1833              stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
   1834         return INVALID_OPERATION;
   1835     }
   1836 
   1837     float volume = computeVolume(stream, index, output, device);
   1838     // do not set volume if the float value did not change
   1839     if (volume != mOutputs.valueFor(output)->mCurVolume[stream] || force) {
   1840         mOutputs.valueFor(output)->mCurVolume[stream] = volume;
   1841         LOGV("setStreamVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
   1842         if (stream == AudioSystem::VOICE_CALL ||
   1843             stream == AudioSystem::DTMF ||
   1844             stream == AudioSystem::BLUETOOTH_SCO) {
   1845             float voiceVolume = -1.0;
   1846             // offset value to reflect actual hardware volume that never reaches 0
   1847             // 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java)
   1848             volume = 0.01 + 0.99 * volume;
   1849             if (stream == AudioSystem::VOICE_CALL) {
   1850                 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
   1851             } else if (stream == AudioSystem::BLUETOOTH_SCO) {
   1852                 voiceVolume = 1.0;
   1853             }
   1854             if (voiceVolume >= 0 && output == mHardwareOutput) {
   1855                 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
   1856             }
   1857         }
   1858         mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
   1859     }
   1860 
   1861     return NO_ERROR;
   1862 }
   1863 
   1864 void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output, uint32_t device, int delayMs)
   1865 {
   1866     LOGV("applyStreamVolumes() for output %d and device %x", output, device);
   1867 
   1868     for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
   1869         checkAndSetVolume(stream, mStreams[stream].mIndexCur, output, device, delayMs);
   1870     }
   1871 }
   1872 
   1873 void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy, bool on, audio_io_handle_t output, int delayMs)
   1874 {
   1875     LOGV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
   1876     for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
   1877         if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
   1878             setStreamMute(stream, on, output, delayMs);
   1879         }
   1880     }
   1881 }
   1882 
   1883 void AudioPolicyManagerBase::setStreamMute(int stream, bool on, audio_io_handle_t output, int delayMs)
   1884 {
   1885     StreamDescriptor &streamDesc = mStreams[stream];
   1886     AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
   1887 
   1888     LOGV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d", stream, on, output, outputDesc->mMuteCount[stream]);
   1889 
   1890     if (on) {
   1891         if (outputDesc->mMuteCount[stream] == 0) {
   1892             if (streamDesc.mCanBeMuted) {
   1893                 checkAndSetVolume(stream, 0, output, outputDesc->device(), delayMs);
   1894             }
   1895         }
   1896         // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
   1897         outputDesc->mMuteCount[stream]++;
   1898     } else {
   1899         if (outputDesc->mMuteCount[stream] == 0) {
   1900             LOGW("setStreamMute() unmuting non muted stream!");
   1901             return;
   1902         }
   1903         if (--outputDesc->mMuteCount[stream] == 0) {
   1904             checkAndSetVolume(stream, streamDesc.mIndexCur, output, outputDesc->device(), delayMs);
   1905         }
   1906     }
   1907 }
   1908 
   1909 void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
   1910 {
   1911     // if the stream pertains to sonification strategy and we are in call we must
   1912     // mute the stream if it is low visibility. If it is high visibility, we must play a tone
   1913     // in the device used for phone strategy and play the tone if the selected device does not
   1914     // interfere with the device used for phone strategy
   1915     // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
   1916     // many times as there are active tracks on the output
   1917 
   1918     if (getStrategy((AudioSystem::stream_type)stream) == STRATEGY_SONIFICATION) {
   1919         AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mHardwareOutput);
   1920         LOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
   1921                 stream, starting, outputDesc->mDevice, stateChange);
   1922         if (outputDesc->mRefCount[stream]) {
   1923             int muteCount = 1;
   1924             if (stateChange) {
   1925                 muteCount = outputDesc->mRefCount[stream];
   1926             }
   1927             if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
   1928                 LOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
   1929                 for (int i = 0; i < muteCount; i++) {
   1930                     setStreamMute(stream, starting, mHardwareOutput);
   1931                 }
   1932             } else {
   1933                 LOGV("handleIncallSonification() high visibility");
   1934                 if (outputDesc->device() & getDeviceForStrategy(STRATEGY_PHONE)) {
   1935                     LOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
   1936                     for (int i = 0; i < muteCount; i++) {
   1937                         setStreamMute(stream, starting, mHardwareOutput);
   1938                     }
   1939                 }
   1940                 if (starting) {
   1941                     mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
   1942                 } else {
   1943                     mpClientInterface->stopTone();
   1944                 }
   1945             }
   1946         }
   1947     }
   1948 }
   1949 
   1950 bool AudioPolicyManagerBase::needsDirectOuput(AudioSystem::stream_type stream,
   1951                                     uint32_t samplingRate,
   1952                                     uint32_t format,
   1953                                     uint32_t channels,
   1954                                     AudioSystem::output_flags flags,
   1955                                     uint32_t device)
   1956 {
   1957    return ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
   1958           (format !=0 && !AudioSystem::isLinearPCM(format)));
   1959 }
   1960 
   1961 uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
   1962 {
   1963     return MAX_EFFECTS_CPU_LOAD;
   1964 }
   1965 
   1966 uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
   1967 {
   1968     return MAX_EFFECTS_MEMORY;
   1969 }
   1970 
   1971 // --- AudioOutputDescriptor class implementation
   1972 
   1973 AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor()
   1974     : mId(0), mSamplingRate(0), mFormat(0), mChannels(0), mLatency(0),
   1975     mFlags((AudioSystem::output_flags)0), mDevice(0), mOutput1(0), mOutput2(0)
   1976 {
   1977     // clear usage count for all stream types
   1978     for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
   1979         mRefCount[i] = 0;
   1980         mCurVolume[i] = -1.0;
   1981         mMuteCount[i] = 0;
   1982     }
   1983 }
   1984 
   1985 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::device()
   1986 {
   1987     uint32_t device = 0;
   1988     if (isDuplicated()) {
   1989         device = mOutput1->mDevice | mOutput2->mDevice;
   1990     } else {
   1991         device = mDevice;
   1992     }
   1993     return device;
   1994 }
   1995 
   1996 void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
   1997 {
   1998     // forward usage count change to attached outputs
   1999     if (isDuplicated()) {
   2000         mOutput1->changeRefCount(stream, delta);
   2001         mOutput2->changeRefCount(stream, delta);
   2002     }
   2003     if ((delta + (int)mRefCount[stream]) < 0) {
   2004         LOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
   2005         mRefCount[stream] = 0;
   2006         return;
   2007     }
   2008     mRefCount[stream] += delta;
   2009     LOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
   2010 }
   2011 
   2012 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::refCount()
   2013 {
   2014     uint32_t refcount = 0;
   2015     for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
   2016         refcount += mRefCount[i];
   2017     }
   2018     return refcount;
   2019 }
   2020 
   2021 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::strategyRefCount(routing_strategy strategy)
   2022 {
   2023     uint32_t refCount = 0;
   2024     for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
   2025         if (getStrategy((AudioSystem::stream_type)i) == strategy) {
   2026             refCount += mRefCount[i];
   2027         }
   2028     }
   2029     return refCount;
   2030 }
   2031 
   2032 
   2033 status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
   2034 {
   2035     const size_t SIZE = 256;
   2036     char buffer[SIZE];
   2037     String8 result;
   2038 
   2039     snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
   2040     result.append(buffer);
   2041     snprintf(buffer, SIZE, " Format: %d\n", mFormat);
   2042     result.append(buffer);
   2043     snprintf(buffer, SIZE, " Channels: %08x\n", mChannels);
   2044     result.append(buffer);
   2045     snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
   2046     result.append(buffer);
   2047     snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
   2048     result.append(buffer);
   2049     snprintf(buffer, SIZE, " Devices %08x\n", device());
   2050     result.append(buffer);
   2051     snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
   2052     result.append(buffer);
   2053     for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
   2054         snprintf(buffer, SIZE, " %02d     %.03f     %02d       %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
   2055         result.append(buffer);
   2056     }
   2057     write(fd, result.string(), result.size());
   2058 
   2059     return NO_ERROR;
   2060 }
   2061 
   2062 // --- AudioInputDescriptor class implementation
   2063 
   2064 AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor()
   2065     : mSamplingRate(0), mFormat(0), mChannels(0),
   2066      mAcoustics((AudioSystem::audio_in_acoustics)0), mDevice(0), mRefCount(0)
   2067 {
   2068 }
   2069 
   2070 status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
   2071 {
   2072     const size_t SIZE = 256;
   2073     char buffer[SIZE];
   2074     String8 result;
   2075 
   2076     snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
   2077     result.append(buffer);
   2078     snprintf(buffer, SIZE, " Format: %d\n", mFormat);
   2079     result.append(buffer);
   2080     snprintf(buffer, SIZE, " Channels: %08x\n", mChannels);
   2081     result.append(buffer);
   2082     snprintf(buffer, SIZE, " Acoustics %08x\n", mAcoustics);
   2083     result.append(buffer);
   2084     snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
   2085     result.append(buffer);
   2086     snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
   2087     result.append(buffer);
   2088     write(fd, result.string(), result.size());
   2089 
   2090     return NO_ERROR;
   2091 }
   2092 
   2093 // --- StreamDescriptor class implementation
   2094 
   2095 void AudioPolicyManagerBase::StreamDescriptor::dump(char* buffer, size_t size)
   2096 {
   2097     snprintf(buffer, size, "      %02d         %02d         %02d         %d\n",
   2098             mIndexMin,
   2099             mIndexMax,
   2100             mIndexCur,
   2101             mCanBeMuted);
   2102 }
   2103 
   2104 // --- EffectDescriptor class implementation
   2105 
   2106 status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
   2107 {
   2108     const size_t SIZE = 256;
   2109     char buffer[SIZE];
   2110     String8 result;
   2111 
   2112     snprintf(buffer, SIZE, " Output: %d\n", mOutput);
   2113     result.append(buffer);
   2114     snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
   2115     result.append(buffer);
   2116     snprintf(buffer, SIZE, " Session: %d\n", mSession);
   2117     result.append(buffer);
   2118     snprintf(buffer, SIZE, " Name: %s\n",  mDesc.name);
   2119     result.append(buffer);
   2120     write(fd, result.string(), result.size());
   2121 
   2122     return NO_ERROR;
   2123 }
   2124 
   2125 
   2126 
   2127 }; // namespace android
   2128