Home | History | Annotate | Download | only in audio
      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 
     20 //#define VERY_VERBOSE_LOGGING
     21 #ifdef VERY_VERBOSE_LOGGING
     22 #define ALOGVV ALOGV
     23 #else
     24 #define ALOGVV(a...) do { } while(0)
     25 #endif
     26 
     27 // A device mask for all audio input devices that are considered "virtual" when evaluating
     28 // active inputs in getActiveInput()
     29 #define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL  AUDIO_DEVICE_IN_REMOTE_SUBMIX
     30 
     31 #include <utils/Log.h>
     32 #include <hardware_legacy/AudioPolicyManagerBase.h>
     33 #include <hardware/audio_effect.h>
     34 #include <hardware/audio.h>
     35 #include <math.h>
     36 #include <hardware_legacy/audio_policy_conf.h>
     37 
     38 namespace android_audio_legacy {
     39 
     40 // ----------------------------------------------------------------------------
     41 // AudioPolicyInterface implementation
     42 // ----------------------------------------------------------------------------
     43 
     44 
     45 status_t AudioPolicyManagerBase::setDeviceConnectionState(audio_devices_t device,
     46                                                   AudioSystem::device_connection_state state,
     47                                                   const char *device_address)
     48 {
     49     SortedVector <audio_io_handle_t> outputs;
     50 
     51     ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
     52 
     53     // connect/disconnect only 1 device at a time
     54     if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
     55 
     56     if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
     57         ALOGE("setDeviceConnectionState() invalid address: %s", device_address);
     58         return BAD_VALUE;
     59     }
     60 
     61     // handle output devices
     62     if (audio_is_output_device(device)) {
     63 
     64         if (!mHasA2dp && audio_is_a2dp_device(device)) {
     65             ALOGE("setDeviceConnectionState() invalid A2DP device: %x", device);
     66             return BAD_VALUE;
     67         }
     68         if (!mHasUsb && audio_is_usb_device(device)) {
     69             ALOGE("setDeviceConnectionState() invalid USB audio device: %x", device);
     70             return BAD_VALUE;
     71         }
     72         if (!mHasRemoteSubmix && audio_is_remote_submix_device((audio_devices_t)device)) {
     73             ALOGE("setDeviceConnectionState() invalid remote submix audio device: %x", device);
     74             return BAD_VALUE;
     75         }
     76 
     77         // save a copy of the opened output descriptors before any output is opened or closed
     78         // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
     79         mPreviousOutputs = mOutputs;
     80         switch (state)
     81         {
     82         // handle output device connection
     83         case AudioSystem::DEVICE_STATE_AVAILABLE:
     84             if (mAvailableOutputDevices & device) {
     85                 ALOGW("setDeviceConnectionState() device already connected: %x", device);
     86                 return INVALID_OPERATION;
     87             }
     88             ALOGV("setDeviceConnectionState() connecting device %x", device);
     89 
     90             if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
     91                 return INVALID_OPERATION;
     92             }
     93             ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %d outputs",
     94                   outputs.size());
     95             // register new device as available
     96             mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices | device);
     97 
     98             if (!outputs.isEmpty()) {
     99                 String8 paramStr;
    100                 if (mHasA2dp && audio_is_a2dp_device(device)) {
    101                     // handle A2DP device connection
    102                     AudioParameter param;
    103                     param.add(String8(AUDIO_PARAMETER_A2DP_SINK_ADDRESS), String8(device_address));
    104                     paramStr = param.toString();
    105                     mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
    106                     mA2dpSuspended = false;
    107                 } else if (audio_is_bluetooth_sco_device(device)) {
    108                     // handle SCO device connection
    109                     mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
    110                 } else if (mHasUsb && audio_is_usb_device(device)) {
    111                     // handle USB device connection
    112                     mUsbCardAndDevice = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
    113                     paramStr = mUsbCardAndDevice;
    114                 }
    115                 // not currently handling multiple simultaneous submixes: ignoring remote submix
    116                 //   case and address
    117                 if (!paramStr.isEmpty()) {
    118                     for (size_t i = 0; i < outputs.size(); i++) {
    119                         mpClientInterface->setParameters(outputs[i], paramStr);
    120                     }
    121                 }
    122             }
    123             break;
    124         // handle output device disconnection
    125         case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
    126             if (!(mAvailableOutputDevices & device)) {
    127                 ALOGW("setDeviceConnectionState() device not connected: %x", device);
    128                 return INVALID_OPERATION;
    129             }
    130 
    131             ALOGV("setDeviceConnectionState() disconnecting device %x", device);
    132             // remove device from available output devices
    133             mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices & ~device);
    134 
    135             checkOutputsForDevice(device, state, outputs);
    136             if (mHasA2dp && audio_is_a2dp_device(device)) {
    137                 // handle A2DP device disconnection
    138                 mA2dpDeviceAddress = "";
    139                 mA2dpSuspended = false;
    140             } else if (audio_is_bluetooth_sco_device(device)) {
    141                 // handle SCO device disconnection
    142                 mScoDeviceAddress = "";
    143             } else if (mHasUsb && audio_is_usb_device(device)) {
    144                 // handle USB device disconnection
    145                 mUsbCardAndDevice = "";
    146             }
    147             // not currently handling multiple simultaneous submixes: ignoring remote submix
    148             //   case and address
    149             } break;
    150 
    151         default:
    152             ALOGE("setDeviceConnectionState() invalid state: %x", state);
    153             return BAD_VALUE;
    154         }
    155 
    156         checkA2dpSuspend();
    157         checkOutputForAllStrategies();
    158         // outputs must be closed after checkOutputForAllStrategies() is executed
    159         if (!outputs.isEmpty()) {
    160             for (size_t i = 0; i < outputs.size(); i++) {
    161                 // close unused outputs after device disconnection or direct outputs that have been
    162                 // opened by checkOutputsForDevice() to query dynamic parameters
    163                 if ((state == AudioSystem::DEVICE_STATE_UNAVAILABLE) ||
    164                         (mOutputs.valueFor(outputs[i])->mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
    165                     closeOutput(outputs[i]);
    166                 }
    167             }
    168         }
    169 
    170         updateDevicesAndOutputs();
    171         for (size_t i = 0; i < mOutputs.size(); i++) {
    172             setOutputDevice(mOutputs.keyAt(i),
    173                             getNewDevice(mOutputs.keyAt(i), true /*fromCache*/),
    174                             true,
    175                             0);
    176         }
    177 
    178         if (device == AUDIO_DEVICE_OUT_WIRED_HEADSET) {
    179             device = AUDIO_DEVICE_IN_WIRED_HEADSET;
    180         } else if (device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO ||
    181                    device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
    182                    device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
    183             device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
    184         } else {
    185             return NO_ERROR;
    186         }
    187     }
    188     // handle input devices
    189     if (audio_is_input_device(device)) {
    190 
    191         switch (state)
    192         {
    193         // handle input device connection
    194         case AudioSystem::DEVICE_STATE_AVAILABLE: {
    195             if (mAvailableInputDevices & device) {
    196                 ALOGW("setDeviceConnectionState() device already connected: %d", device);
    197                 return INVALID_OPERATION;
    198             }
    199             mAvailableInputDevices = mAvailableInputDevices | (device & ~AUDIO_DEVICE_BIT_IN);
    200             }
    201             break;
    202 
    203         // handle input device disconnection
    204         case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
    205             if (!(mAvailableInputDevices & device)) {
    206                 ALOGW("setDeviceConnectionState() device not connected: %d", device);
    207                 return INVALID_OPERATION;
    208             }
    209             mAvailableInputDevices = (audio_devices_t) (mAvailableInputDevices & ~device);
    210             } break;
    211 
    212         default:
    213             ALOGE("setDeviceConnectionState() invalid state: %x", state);
    214             return BAD_VALUE;
    215         }
    216 
    217         audio_io_handle_t activeInput = getActiveInput();
    218         if (activeInput != 0) {
    219             AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
    220             audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
    221             if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
    222                 ALOGV("setDeviceConnectionState() changing device from %x to %x for input %d",
    223                         inputDesc->mDevice, newDevice, activeInput);
    224                 inputDesc->mDevice = newDevice;
    225                 AudioParameter param = AudioParameter();
    226                 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
    227                 mpClientInterface->setParameters(activeInput, param.toString());
    228             }
    229         }
    230 
    231         return NO_ERROR;
    232     }
    233 
    234     ALOGW("setDeviceConnectionState() invalid device: %x", device);
    235     return BAD_VALUE;
    236 }
    237 
    238 AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(audio_devices_t device,
    239                                                   const char *device_address)
    240 {
    241     AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE;
    242     String8 address = String8(device_address);
    243     if (audio_is_output_device(device)) {
    244         if (device & mAvailableOutputDevices) {
    245             if (audio_is_a2dp_device(device) &&
    246                 (!mHasA2dp || (address != "" && mA2dpDeviceAddress != address))) {
    247                 return state;
    248             }
    249             if (audio_is_bluetooth_sco_device(device) &&
    250                 address != "" && mScoDeviceAddress != address) {
    251                 return state;
    252             }
    253             if (audio_is_usb_device(device) &&
    254                 (!mHasUsb || (address != "" && mUsbCardAndDevice != address))) {
    255                 ALOGE("getDeviceConnectionState() invalid device: %x", device);
    256                 return state;
    257             }
    258             if (audio_is_remote_submix_device((audio_devices_t)device) && !mHasRemoteSubmix) {
    259                 return state;
    260             }
    261             state = AudioSystem::DEVICE_STATE_AVAILABLE;
    262         }
    263     } else if (audio_is_input_device(device)) {
    264         if (device & mAvailableInputDevices) {
    265             state = AudioSystem::DEVICE_STATE_AVAILABLE;
    266         }
    267     }
    268 
    269     return state;
    270 }
    271 
    272 void AudioPolicyManagerBase::setPhoneState(int state)
    273 {
    274     ALOGV("setPhoneState() state %d", state);
    275     audio_devices_t newDevice = AUDIO_DEVICE_NONE;
    276     if (state < 0 || state >= AudioSystem::NUM_MODES) {
    277         ALOGW("setPhoneState() invalid state %d", state);
    278         return;
    279     }
    280 
    281     if (state == mPhoneState ) {
    282         ALOGW("setPhoneState() setting same state %d", state);
    283         return;
    284     }
    285 
    286     // if leaving call state, handle special case of active streams
    287     // pertaining to sonification strategy see handleIncallSonification()
    288     if (isInCall()) {
    289         ALOGV("setPhoneState() in call state management: new state is %d", state);
    290         for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
    291             handleIncallSonification(stream, false, true);
    292         }
    293     }
    294 
    295     // store previous phone state for management of sonification strategy below
    296     int oldState = mPhoneState;
    297     mPhoneState = state;
    298     bool force = false;
    299 
    300     // are we entering or starting a call
    301     if (!isStateInCall(oldState) && isStateInCall(state)) {
    302         ALOGV("  Entering call in setPhoneState()");
    303         // force routing command to audio hardware when starting a call
    304         // even if no device change is needed
    305         force = true;
    306     } else if (isStateInCall(oldState) && !isStateInCall(state)) {
    307         ALOGV("  Exiting call in setPhoneState()");
    308         // force routing command to audio hardware when exiting a call
    309         // even if no device change is needed
    310         force = true;
    311     } else if (isStateInCall(state) && (state != oldState)) {
    312         ALOGV("  Switching between telephony and VoIP in setPhoneState()");
    313         // force routing command to audio hardware when switching between telephony and VoIP
    314         // even if no device change is needed
    315         force = true;
    316     }
    317 
    318     // check for device and output changes triggered by new phone state
    319     newDevice = getNewDevice(mPrimaryOutput, false /*fromCache*/);
    320     checkA2dpSuspend();
    321     checkOutputForAllStrategies();
    322     updateDevicesAndOutputs();
    323 
    324     AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
    325 
    326     // force routing command to audio hardware when ending call
    327     // even if no device change is needed
    328     if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
    329         newDevice = hwOutputDesc->device();
    330     }
    331 
    332     // when changing from ring tone to in call mode, mute the ringing tone
    333     // immediately and delay the route change to avoid sending the ring tone
    334     // tail into the earpiece or headset.
    335     int delayMs = 0;
    336     if (isStateInCall(state) && oldState == AudioSystem::MODE_RINGTONE) {
    337         // delay the device change command by twice the output latency to have some margin
    338         // and be sure that audio buffers not yet affected by the mute are out when
    339         // we actually apply the route change
    340         delayMs = hwOutputDesc->mLatency*2;
    341         setStreamMute(AudioSystem::RING, true, mPrimaryOutput);
    342     }
    343 
    344     if (isStateInCall(state)) {
    345         for (size_t i = 0; i < mOutputs.size(); i++) {
    346             AudioOutputDescriptor *desc = mOutputs.valueAt(i);
    347             //take the biggest latency for all outputs
    348             if (delayMs < desc->mLatency*2) {
    349                 delayMs = desc->mLatency*2;
    350             }
    351             //mute STRATEGY_MEDIA on all outputs
    352             if (desc->strategyRefCount(STRATEGY_MEDIA) != 0) {
    353                 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
    354                 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
    355                     getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
    356             }
    357         }
    358     }
    359 
    360     // change routing is necessary
    361     setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
    362 
    363     // if entering in call state, handle special case of active streams
    364     // pertaining to sonification strategy see handleIncallSonification()
    365     if (isStateInCall(state)) {
    366         ALOGV("setPhoneState() in call state management: new state is %d", state);
    367         // unmute the ringing tone after a sufficient delay if it was muted before
    368         // setting output device above
    369         if (oldState == AudioSystem::MODE_RINGTONE) {
    370             setStreamMute(AudioSystem::RING, false, mPrimaryOutput, MUTE_TIME_MS);
    371         }
    372         for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
    373             handleIncallSonification(stream, true, true);
    374         }
    375     }
    376 
    377     // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
    378     if (state == AudioSystem::MODE_RINGTONE &&
    379         isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
    380         mLimitRingtoneVolume = true;
    381     } else {
    382         mLimitRingtoneVolume = false;
    383     }
    384 }
    385 
    386 void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
    387 {
    388     ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
    389 
    390     bool forceVolumeReeval = false;
    391     switch(usage) {
    392     case AudioSystem::FOR_COMMUNICATION:
    393         if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
    394             config != AudioSystem::FORCE_NONE) {
    395             ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
    396             return;
    397         }
    398         forceVolumeReeval = true;
    399         mForceUse[usage] = config;
    400         break;
    401     case AudioSystem::FOR_MEDIA:
    402         if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP &&
    403             config != AudioSystem::FORCE_WIRED_ACCESSORY &&
    404             config != AudioSystem::FORCE_ANALOG_DOCK &&
    405             config != AudioSystem::FORCE_DIGITAL_DOCK && config != AudioSystem::FORCE_NONE &&
    406             config != AudioSystem::FORCE_NO_BT_A2DP) {
    407             ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
    408             return;
    409         }
    410         mForceUse[usage] = config;
    411         break;
    412     case AudioSystem::FOR_RECORD:
    413         if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY &&
    414             config != AudioSystem::FORCE_NONE) {
    415             ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
    416             return;
    417         }
    418         mForceUse[usage] = config;
    419         break;
    420     case AudioSystem::FOR_DOCK:
    421         if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK &&
    422             config != AudioSystem::FORCE_BT_DESK_DOCK &&
    423             config != AudioSystem::FORCE_WIRED_ACCESSORY &&
    424             config != AudioSystem::FORCE_ANALOG_DOCK &&
    425             config != AudioSystem::FORCE_DIGITAL_DOCK) {
    426             ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
    427         }
    428         forceVolumeReeval = true;
    429         mForceUse[usage] = config;
    430         break;
    431     case AudioSystem::FOR_SYSTEM:
    432         if (config != AudioSystem::FORCE_NONE &&
    433             config != AudioSystem::FORCE_SYSTEM_ENFORCED) {
    434             ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
    435         }
    436         forceVolumeReeval = true;
    437         mForceUse[usage] = config;
    438         break;
    439     default:
    440         ALOGW("setForceUse() invalid usage %d", usage);
    441         break;
    442     }
    443 
    444     // check for device and output changes triggered by new force usage
    445     checkA2dpSuspend();
    446     checkOutputForAllStrategies();
    447     updateDevicesAndOutputs();
    448     for (size_t i = 0; i < mOutputs.size(); i++) {
    449         audio_io_handle_t output = mOutputs.keyAt(i);
    450         audio_devices_t newDevice = getNewDevice(output, true /*fromCache*/);
    451         setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
    452         if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
    453             applyStreamVolumes(output, newDevice, 0, true);
    454         }
    455     }
    456 
    457     audio_io_handle_t activeInput = getActiveInput();
    458     if (activeInput != 0) {
    459         AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
    460         audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
    461         if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
    462             ALOGV("setForceUse() changing device from %x to %x for input %d",
    463                     inputDesc->mDevice, newDevice, activeInput);
    464             inputDesc->mDevice = newDevice;
    465             AudioParameter param = AudioParameter();
    466             param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
    467             mpClientInterface->setParameters(activeInput, param.toString());
    468         }
    469     }
    470 
    471 }
    472 
    473 AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage)
    474 {
    475     return mForceUse[usage];
    476 }
    477 
    478 void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value)
    479 {
    480     ALOGV("setSystemProperty() property %s, value %s", property, value);
    481 }
    482 
    483 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getProfileForDirectOutput(
    484                                                                audio_devices_t device,
    485                                                                uint32_t samplingRate,
    486                                                                uint32_t format,
    487                                                                uint32_t channelMask,
    488                                                                audio_output_flags_t flags)
    489 {
    490     for (size_t i = 0; i < mHwModules.size(); i++) {
    491         if (mHwModules[i]->mHandle == 0) {
    492             continue;
    493         }
    494         for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
    495            IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
    496            if (profile->isCompatibleProfile(device, samplingRate, format,
    497                                            channelMask,
    498                                            AUDIO_OUTPUT_FLAG_DIRECT)) {
    499                if (mAvailableOutputDevices & profile->mSupportedDevices) {
    500                    return mHwModules[i]->mOutputProfiles[j];
    501                }
    502            }
    503         }
    504     }
    505     return 0;
    506 }
    507 
    508 audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream,
    509                                     uint32_t samplingRate,
    510                                     uint32_t format,
    511                                     uint32_t channelMask,
    512                                     AudioSystem::output_flags flags)
    513 {
    514     audio_io_handle_t output = 0;
    515     uint32_t latency = 0;
    516     routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
    517     audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
    518     ALOGV("getOutput() stream %d, samplingRate %d, format %d, channelMask %x, flags %x",
    519           stream, samplingRate, format, channelMask, flags);
    520 
    521 #ifdef AUDIO_POLICY_TEST
    522     if (mCurOutput != 0) {
    523         ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
    524                 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
    525 
    526         if (mTestOutputs[mCurOutput] == 0) {
    527             ALOGV("getOutput() opening test output");
    528             AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
    529             outputDesc->mDevice = mTestDevice;
    530             outputDesc->mSamplingRate = mTestSamplingRate;
    531             outputDesc->mFormat = mTestFormat;
    532             outputDesc->mChannelMask = mTestChannels;
    533             outputDesc->mLatency = mTestLatencyMs;
    534             outputDesc->mFlags = (audio_output_flags_t)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0);
    535             outputDesc->mRefCount[stream] = 0;
    536             mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
    537                                             &outputDesc->mSamplingRate,
    538                                             &outputDesc->mFormat,
    539                                             &outputDesc->mChannelMask,
    540                                             &outputDesc->mLatency,
    541                                             outputDesc->mFlags);
    542             if (mTestOutputs[mCurOutput]) {
    543                 AudioParameter outputCmd = AudioParameter();
    544                 outputCmd.addInt(String8("set_id"),mCurOutput);
    545                 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
    546                 addOutput(mTestOutputs[mCurOutput], outputDesc);
    547             }
    548         }
    549         return mTestOutputs[mCurOutput];
    550     }
    551 #endif //AUDIO_POLICY_TEST
    552 
    553     // open a direct output if required by specified parameters
    554     IOProfile *profile = getProfileForDirectOutput(device,
    555                                                    samplingRate,
    556                                                    format,
    557                                                    channelMask,
    558                                                    (audio_output_flags_t)flags);
    559     if (profile != NULL) {
    560 
    561         ALOGV("getOutput() opening direct output device %x", device);
    562 
    563         AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(profile);
    564         outputDesc->mDevice = device;
    565         outputDesc->mSamplingRate = samplingRate;
    566         outputDesc->mFormat = (audio_format_t)format;
    567         outputDesc->mChannelMask = (audio_channel_mask_t)channelMask;
    568         outputDesc->mLatency = 0;
    569         outputDesc->mFlags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);;
    570         outputDesc->mRefCount[stream] = 0;
    571         outputDesc->mStopTime[stream] = 0;
    572         output = mpClientInterface->openOutput(profile->mModule->mHandle,
    573                                         &outputDesc->mDevice,
    574                                         &outputDesc->mSamplingRate,
    575                                         &outputDesc->mFormat,
    576                                         &outputDesc->mChannelMask,
    577                                         &outputDesc->mLatency,
    578                                         outputDesc->mFlags);
    579 
    580         // only accept an output with the requested parameters
    581         if (output == 0 ||
    582             (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
    583             (format != 0 && format != outputDesc->mFormat) ||
    584             (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
    585             ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
    586                     "format %d %d, channelMask %04x %04x", output, samplingRate,
    587                     outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
    588                     outputDesc->mChannelMask);
    589             if (output != 0) {
    590                 mpClientInterface->closeOutput(output);
    591             }
    592             delete outputDesc;
    593             return 0;
    594         }
    595         addOutput(output, outputDesc);
    596         ALOGV("getOutput() returns direct output %d", output);
    597         return output;
    598     }
    599 
    600     // ignoring channel mask due to downmix capability in mixer
    601 
    602     // open a non direct output
    603 
    604     // get which output is suitable for the specified stream. The actual routing change will happen
    605     // when startOutput() will be called
    606     SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
    607 
    608     output = selectOutput(outputs, flags);
    609 
    610     ALOGW_IF((output ==0), "getOutput() could not find output for stream %d, samplingRate %d,"
    611             "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
    612 
    613     ALOGV("getOutput() returns output %d", output);
    614 
    615     return output;
    616 }
    617 
    618 audio_io_handle_t AudioPolicyManagerBase::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
    619                                                        AudioSystem::output_flags flags)
    620 {
    621     // select one output among several that provide a path to a particular device or set of
    622     // devices (the list was previously build by getOutputsForDevice()).
    623     // The priority is as follows:
    624     // 1: the output with the highest number of requested policy flags
    625     // 2: the primary output
    626     // 3: the first output in the list
    627 
    628     if (outputs.size() == 0) {
    629         return 0;
    630     }
    631     if (outputs.size() == 1) {
    632         return outputs[0];
    633     }
    634 
    635     int maxCommonFlags = 0;
    636     audio_io_handle_t outputFlags = 0;
    637     audio_io_handle_t outputPrimary = 0;
    638 
    639     for (size_t i = 0; i < outputs.size(); i++) {
    640         AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
    641         if (!outputDesc->isDuplicated()) {
    642             int commonFlags = (int)AudioSystem::popCount(outputDesc->mProfile->mFlags & flags);
    643             if (commonFlags > maxCommonFlags) {
    644                 outputFlags = outputs[i];
    645                 maxCommonFlags = commonFlags;
    646                 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
    647             }
    648             if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
    649                 outputPrimary = outputs[i];
    650             }
    651         }
    652     }
    653 
    654     if (outputFlags != 0) {
    655         return outputFlags;
    656     }
    657     if (outputPrimary != 0) {
    658         return outputPrimary;
    659     }
    660 
    661     return outputs[0];
    662 }
    663 
    664 status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output,
    665                                              AudioSystem::stream_type stream,
    666                                              int session)
    667 {
    668     ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
    669     ssize_t index = mOutputs.indexOfKey(output);
    670     if (index < 0) {
    671         ALOGW("startOutput() unknow output %d", output);
    672         return BAD_VALUE;
    673     }
    674 
    675     AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
    676 
    677     // increment usage count for this stream on the requested output:
    678     // NOTE that the usage count is the same for duplicated output and hardware output which is
    679     // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
    680     outputDesc->changeRefCount(stream, 1);
    681 
    682     if (outputDesc->mRefCount[stream] == 1) {
    683         audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
    684         routing_strategy strategy = getStrategy(stream);
    685         bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
    686                             (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
    687         uint32_t waitMs = 0;
    688         bool force = false;
    689         for (size_t i = 0; i < mOutputs.size(); i++) {
    690             AudioOutputDescriptor *desc = mOutputs.valueAt(i);
    691             if (desc != outputDesc) {
    692                 // force a device change if any other output is managed by the same hw
    693                 // module and has a current device selection that differs from selected device.
    694                 // In this case, the audio HAL must receive the new device selection so that it can
    695                 // change the device currently selected by the other active output.
    696                 if (outputDesc->sharesHwModuleWith(desc) &&
    697                     desc->device() != newDevice) {
    698                     force = true;
    699                 }
    700                 // wait for audio on other active outputs to be presented when starting
    701                 // a notification so that audio focus effect can propagate.
    702                 if (shouldWait && (desc->refCount() != 0) && (waitMs < desc->latency())) {
    703                     waitMs = desc->latency();
    704                 }
    705             }
    706         }
    707         uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
    708 
    709         // handle special case for sonification while in call
    710         if (isInCall()) {
    711             handleIncallSonification(stream, true, false);
    712         }
    713 
    714         // apply volume rules for current stream and device if necessary
    715         checkAndSetVolume(stream,
    716                           mStreams[stream].getVolumeIndex(newDevice),
    717                           output,
    718                           newDevice);
    719 
    720         // update the outputs if starting an output with a stream that can affect notification
    721         // routing
    722         handleNotificationRoutingForStream(stream);
    723         if (waitMs > muteWaitMs) {
    724             usleep((waitMs - muteWaitMs) * 2 * 1000);
    725         }
    726     }
    727     return NO_ERROR;
    728 }
    729 
    730 
    731 status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
    732                                             AudioSystem::stream_type stream,
    733                                             int session)
    734 {
    735     ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
    736     ssize_t index = mOutputs.indexOfKey(output);
    737     if (index < 0) {
    738         ALOGW("stopOutput() unknow output %d", output);
    739         return BAD_VALUE;
    740     }
    741 
    742     AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
    743 
    744     // handle special case for sonification while in call
    745     if (isInCall()) {
    746         handleIncallSonification(stream, false, false);
    747     }
    748 
    749     if (outputDesc->mRefCount[stream] > 0) {
    750         // decrement usage count of this stream on the output
    751         outputDesc->changeRefCount(stream, -1);
    752         // store time at which the stream was stopped - see isStreamActive()
    753         if (outputDesc->mRefCount[stream] == 0) {
    754             outputDesc->mStopTime[stream] = systemTime();
    755             audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
    756             // delay the device switch by twice the latency because stopOutput() is executed when
    757             // the track stop() command is received and at that time the audio track buffer can
    758             // still contain data that needs to be drained. The latency only covers the audio HAL
    759             // and kernel buffers. Also the latency does not always include additional delay in the
    760             // audio path (audio DSP, CODEC ...)
    761             setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
    762 
    763             // force restoring the device selection on other active outputs if it differs from the
    764             // one being selected for this output
    765             for (size_t i = 0; i < mOutputs.size(); i++) {
    766                 audio_io_handle_t curOutput = mOutputs.keyAt(i);
    767                 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
    768                 if (curOutput != output &&
    769                         desc->refCount() != 0 &&
    770                         outputDesc->sharesHwModuleWith(desc) &&
    771                         newDevice != desc->device()) {
    772                     setOutputDevice(curOutput,
    773                                     getNewDevice(curOutput, false /*fromCache*/),
    774                                     true,
    775                                     outputDesc->mLatency*2);
    776                 }
    777             }
    778             // update the outputs if stopping one with a stream that can affect notification routing
    779             handleNotificationRoutingForStream(stream);
    780         }
    781         return NO_ERROR;
    782     } else {
    783         ALOGW("stopOutput() refcount is already 0 for output %d", output);
    784         return INVALID_OPERATION;
    785     }
    786 }
    787 
    788 void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
    789 {
    790     ALOGV("releaseOutput() %d", output);
    791     ssize_t index = mOutputs.indexOfKey(output);
    792     if (index < 0) {
    793         ALOGW("releaseOutput() releasing unknown output %d", output);
    794         return;
    795     }
    796 
    797 #ifdef AUDIO_POLICY_TEST
    798     int testIndex = testOutputIndex(output);
    799     if (testIndex != 0) {
    800         AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
    801         if (outputDesc->refCount() == 0) {
    802             mpClientInterface->closeOutput(output);
    803             delete mOutputs.valueAt(index);
    804             mOutputs.removeItem(output);
    805             mTestOutputs[testIndex] = 0;
    806         }
    807         return;
    808     }
    809 #endif //AUDIO_POLICY_TEST
    810 
    811     if (mOutputs.valueAt(index)->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
    812         mpClientInterface->closeOutput(output);
    813         delete mOutputs.valueAt(index);
    814         mOutputs.removeItem(output);
    815         mPreviousOutputs = mOutputs;
    816     }
    817 
    818 }
    819 
    820 audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
    821                                     uint32_t samplingRate,
    822                                     uint32_t format,
    823                                     uint32_t channelMask,
    824                                     AudioSystem::audio_in_acoustics acoustics)
    825 {
    826     audio_io_handle_t input = 0;
    827     audio_devices_t device = getDeviceForInputSource(inputSource);
    828 
    829     ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
    830           inputSource, samplingRate, format, channelMask, acoustics);
    831 
    832     if (device == AUDIO_DEVICE_NONE) {
    833         ALOGW("getInput() could not find device for inputSource %d", inputSource);
    834         return 0;
    835     }
    836 
    837     // adapt channel selection to input source
    838     switch(inputSource) {
    839     case AUDIO_SOURCE_VOICE_UPLINK:
    840         channelMask = AudioSystem::CHANNEL_IN_VOICE_UPLINK;
    841         break;
    842     case AUDIO_SOURCE_VOICE_DOWNLINK:
    843         channelMask = AudioSystem::CHANNEL_IN_VOICE_DNLINK;
    844         break;
    845     case AUDIO_SOURCE_VOICE_CALL:
    846         channelMask = (AudioSystem::CHANNEL_IN_VOICE_UPLINK | AudioSystem::CHANNEL_IN_VOICE_DNLINK);
    847         break;
    848     default:
    849         break;
    850     }
    851 
    852     IOProfile *profile = getInputProfile(device,
    853                                          samplingRate,
    854                                          format,
    855                                          channelMask);
    856     if (profile == NULL) {
    857         ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d,"
    858                 "channelMask %04x",
    859                 device, samplingRate, format, channelMask);
    860         return 0;
    861     }
    862 
    863     if (profile->mModule->mHandle == 0) {
    864         ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
    865         return 0;
    866     }
    867 
    868     AudioInputDescriptor *inputDesc = new AudioInputDescriptor(profile);
    869 
    870     inputDesc->mInputSource = inputSource;
    871     inputDesc->mDevice = device;
    872     inputDesc->mSamplingRate = samplingRate;
    873     inputDesc->mFormat = (audio_format_t)format;
    874     inputDesc->mChannelMask = (audio_channel_mask_t)channelMask;
    875     inputDesc->mRefCount = 0;
    876     input = mpClientInterface->openInput(profile->mModule->mHandle,
    877                                     &inputDesc->mDevice,
    878                                     &inputDesc->mSamplingRate,
    879                                     &inputDesc->mFormat,
    880                                     &inputDesc->mChannelMask);
    881 
    882     // only accept input with the exact requested set of parameters
    883     if (input == 0 ||
    884         (samplingRate != inputDesc->mSamplingRate) ||
    885         (format != inputDesc->mFormat) ||
    886         (channelMask != inputDesc->mChannelMask)) {
    887         ALOGV("getInput() failed opening input: samplingRate %d, format %d, channelMask %d",
    888                 samplingRate, format, channelMask);
    889         if (input != 0) {
    890             mpClientInterface->closeInput(input);
    891         }
    892         delete inputDesc;
    893         return 0;
    894     }
    895     mInputs.add(input, inputDesc);
    896     return input;
    897 }
    898 
    899 status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
    900 {
    901     ALOGV("startInput() input %d", input);
    902     ssize_t index = mInputs.indexOfKey(input);
    903     if (index < 0) {
    904         ALOGW("startInput() unknow input %d", input);
    905         return BAD_VALUE;
    906     }
    907     AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
    908 
    909 #ifdef AUDIO_POLICY_TEST
    910     if (mTestInput == 0)
    911 #endif //AUDIO_POLICY_TEST
    912     {
    913         // refuse 2 active AudioRecord clients at the same time
    914         if (getActiveInput() != 0) {
    915             ALOGW("startInput() input %d failed: other input already started", input);
    916             return INVALID_OPERATION;
    917         }
    918     }
    919 
    920     AudioParameter param = AudioParameter();
    921     param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
    922 
    923     param.addInt(String8(AudioParameter::keyInputSource), (int)inputDesc->mInputSource);
    924     ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
    925 
    926     mpClientInterface->setParameters(input, param.toString());
    927 
    928     inputDesc->mRefCount = 1;
    929     return NO_ERROR;
    930 }
    931 
    932 status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
    933 {
    934     ALOGV("stopInput() input %d", input);
    935     ssize_t index = mInputs.indexOfKey(input);
    936     if (index < 0) {
    937         ALOGW("stopInput() unknow input %d", input);
    938         return BAD_VALUE;
    939     }
    940     AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
    941 
    942     if (inputDesc->mRefCount == 0) {
    943         ALOGW("stopInput() input %d already stopped", input);
    944         return INVALID_OPERATION;
    945     } else {
    946         AudioParameter param = AudioParameter();
    947         param.addInt(String8(AudioParameter::keyRouting), 0);
    948         mpClientInterface->setParameters(input, param.toString());
    949         inputDesc->mRefCount = 0;
    950         return NO_ERROR;
    951     }
    952 }
    953 
    954 void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
    955 {
    956     ALOGV("releaseInput() %d", input);
    957     ssize_t index = mInputs.indexOfKey(input);
    958     if (index < 0) {
    959         ALOGW("releaseInput() releasing unknown input %d", input);
    960         return;
    961     }
    962     mpClientInterface->closeInput(input);
    963     delete mInputs.valueAt(index);
    964     mInputs.removeItem(input);
    965     ALOGV("releaseInput() exit");
    966 }
    967 
    968 void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
    969                                             int indexMin,
    970                                             int indexMax)
    971 {
    972     ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
    973     if (indexMin < 0 || indexMin >= indexMax) {
    974         ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
    975         return;
    976     }
    977     mStreams[stream].mIndexMin = indexMin;
    978     mStreams[stream].mIndexMax = indexMax;
    979 }
    980 
    981 status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream,
    982                                                       int index,
    983                                                       audio_devices_t device)
    984 {
    985 
    986     if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
    987         return BAD_VALUE;
    988     }
    989     if (!audio_is_output_device(device)) {
    990         return BAD_VALUE;
    991     }
    992 
    993     // Force max volume if stream cannot be muted
    994     if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
    995 
    996     ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
    997           stream, device, index);
    998 
    999     // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
   1000     // clear all device specific values
   1001     if (device == AUDIO_DEVICE_OUT_DEFAULT) {
   1002         mStreams[stream].mIndexCur.clear();
   1003     }
   1004     mStreams[stream].mIndexCur.add(device, index);
   1005 
   1006     // compute and apply stream volume on all outputs according to connected device
   1007     status_t status = NO_ERROR;
   1008     for (size_t i = 0; i < mOutputs.size(); i++) {
   1009         audio_devices_t curDevice =
   1010                 getDeviceForVolume(mOutputs.valueAt(i)->device());
   1011         if (device == curDevice) {
   1012             status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
   1013             if (volStatus != NO_ERROR) {
   1014                 status = volStatus;
   1015             }
   1016         }
   1017     }
   1018     return status;
   1019 }
   1020 
   1021 status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream,
   1022                                                       int *index,
   1023                                                       audio_devices_t device)
   1024 {
   1025     if (index == NULL) {
   1026         return BAD_VALUE;
   1027     }
   1028     if (!audio_is_output_device(device)) {
   1029         return BAD_VALUE;
   1030     }
   1031     // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
   1032     // the strategy the stream belongs to.
   1033     if (device == AUDIO_DEVICE_OUT_DEFAULT) {
   1034         device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
   1035     }
   1036     device = getDeviceForVolume(device);
   1037 
   1038     *index =  mStreams[stream].getVolumeIndex(device);
   1039     ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
   1040     return NO_ERROR;
   1041 }
   1042 
   1043 audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(const effect_descriptor_t *desc)
   1044 {
   1045     ALOGV("getOutputForEffect()");
   1046     // apply simple rule where global effects are attached to the same output as MUSIC streams
   1047 
   1048     routing_strategy strategy = getStrategy(AudioSystem::MUSIC);
   1049     audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
   1050     SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
   1051     int outIdx = 0;
   1052     for (size_t i = 0; i < dstOutputs.size(); i++) {
   1053         AudioOutputDescriptor *desc = mOutputs.valueFor(dstOutputs[i]);
   1054         if (desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) {
   1055             outIdx = i;
   1056         }
   1057     }
   1058     return dstOutputs[outIdx];
   1059 }
   1060 
   1061 status_t AudioPolicyManagerBase::registerEffect(const effect_descriptor_t *desc,
   1062                                 audio_io_handle_t io,
   1063                                 uint32_t strategy,
   1064                                 int session,
   1065                                 int id)
   1066 {
   1067     ssize_t index = mOutputs.indexOfKey(io);
   1068     if (index < 0) {
   1069         index = mInputs.indexOfKey(io);
   1070         if (index < 0) {
   1071             ALOGW("registerEffect() unknown io %d", io);
   1072             return INVALID_OPERATION;
   1073         }
   1074     }
   1075 
   1076     if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
   1077         ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
   1078                 desc->name, desc->memoryUsage);
   1079         return INVALID_OPERATION;
   1080     }
   1081     mTotalEffectsMemory += desc->memoryUsage;
   1082     ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
   1083             desc->name, io, strategy, session, id);
   1084     ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
   1085 
   1086     EffectDescriptor *pDesc = new EffectDescriptor();
   1087     memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
   1088     pDesc->mIo = io;
   1089     pDesc->mStrategy = (routing_strategy)strategy;
   1090     pDesc->mSession = session;
   1091     pDesc->mEnabled = false;
   1092 
   1093     mEffects.add(id, pDesc);
   1094 
   1095     return NO_ERROR;
   1096 }
   1097 
   1098 status_t AudioPolicyManagerBase::unregisterEffect(int id)
   1099 {
   1100     ssize_t index = mEffects.indexOfKey(id);
   1101     if (index < 0) {
   1102         ALOGW("unregisterEffect() unknown effect ID %d", id);
   1103         return INVALID_OPERATION;
   1104     }
   1105 
   1106     EffectDescriptor *pDesc = mEffects.valueAt(index);
   1107 
   1108     setEffectEnabled(pDesc, false);
   1109 
   1110     if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
   1111         ALOGW("unregisterEffect() memory %d too big for total %d",
   1112                 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
   1113         pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
   1114     }
   1115     mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
   1116     ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
   1117             pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
   1118 
   1119     mEffects.removeItem(id);
   1120     delete pDesc;
   1121 
   1122     return NO_ERROR;
   1123 }
   1124 
   1125 status_t AudioPolicyManagerBase::setEffectEnabled(int id, bool enabled)
   1126 {
   1127     ssize_t index = mEffects.indexOfKey(id);
   1128     if (index < 0) {
   1129         ALOGW("unregisterEffect() unknown effect ID %d", id);
   1130         return INVALID_OPERATION;
   1131     }
   1132 
   1133     return setEffectEnabled(mEffects.valueAt(index), enabled);
   1134 }
   1135 
   1136 status_t AudioPolicyManagerBase::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
   1137 {
   1138     if (enabled == pDesc->mEnabled) {
   1139         ALOGV("setEffectEnabled(%s) effect already %s",
   1140              enabled?"true":"false", enabled?"enabled":"disabled");
   1141         return INVALID_OPERATION;
   1142     }
   1143 
   1144     if (enabled) {
   1145         if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
   1146             ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
   1147                  pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
   1148             return INVALID_OPERATION;
   1149         }
   1150         mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
   1151         ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
   1152     } else {
   1153         if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
   1154             ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
   1155                     pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
   1156             pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
   1157         }
   1158         mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
   1159         ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
   1160     }
   1161     pDesc->mEnabled = enabled;
   1162     return NO_ERROR;
   1163 }
   1164 
   1165 bool AudioPolicyManagerBase::isStreamActive(int stream, uint32_t inPastMs) const
   1166 {
   1167     nsecs_t sysTime = systemTime();
   1168     for (size_t i = 0; i < mOutputs.size(); i++) {
   1169         if (mOutputs.valueAt(i)->mRefCount[stream] != 0 ||
   1170             ns2ms(sysTime - mOutputs.valueAt(i)->mStopTime[stream]) < inPastMs) {
   1171             return true;
   1172         }
   1173     }
   1174     return false;
   1175 }
   1176 
   1177 bool AudioPolicyManagerBase::isSourceActive(audio_source_t source) const
   1178 {
   1179     for (size_t i = 0; i < mInputs.size(); i++) {
   1180         const AudioInputDescriptor * inputDescriptor = mInputs.valueAt(i);
   1181         if ((inputDescriptor->mInputSource == (int) source)
   1182                 && (inputDescriptor->mRefCount > 0)) {
   1183             return true;
   1184         }
   1185     }
   1186     return false;
   1187 }
   1188 
   1189 
   1190 
   1191 status_t AudioPolicyManagerBase::dump(int fd)
   1192 {
   1193     const size_t SIZE = 256;
   1194     char buffer[SIZE];
   1195     String8 result;
   1196 
   1197     snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
   1198     result.append(buffer);
   1199 
   1200     snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
   1201     result.append(buffer);
   1202     snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
   1203     result.append(buffer);
   1204     snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
   1205     result.append(buffer);
   1206     snprintf(buffer, SIZE, " USB audio ALSA %s\n", mUsbCardAndDevice.string());
   1207     result.append(buffer);
   1208     snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
   1209     result.append(buffer);
   1210     snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
   1211     result.append(buffer);
   1212     snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
   1213     result.append(buffer);
   1214     snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
   1215     result.append(buffer);
   1216     snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
   1217     result.append(buffer);
   1218     snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
   1219     result.append(buffer);
   1220     snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
   1221     result.append(buffer);
   1222     snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AudioSystem::FOR_SYSTEM]);
   1223     result.append(buffer);
   1224     write(fd, result.string(), result.size());
   1225 
   1226 
   1227     snprintf(buffer, SIZE, "\nHW Modules dump:\n");
   1228     write(fd, buffer, strlen(buffer));
   1229     for (size_t i = 0; i < mHwModules.size(); i++) {
   1230         snprintf(buffer, SIZE, "- HW Module %d:\n", i + 1);
   1231         write(fd, buffer, strlen(buffer));
   1232         mHwModules[i]->dump(fd);
   1233     }
   1234 
   1235     snprintf(buffer, SIZE, "\nOutputs dump:\n");
   1236     write(fd, buffer, strlen(buffer));
   1237     for (size_t i = 0; i < mOutputs.size(); i++) {
   1238         snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
   1239         write(fd, buffer, strlen(buffer));
   1240         mOutputs.valueAt(i)->dump(fd);
   1241     }
   1242 
   1243     snprintf(buffer, SIZE, "\nInputs dump:\n");
   1244     write(fd, buffer, strlen(buffer));
   1245     for (size_t i = 0; i < mInputs.size(); i++) {
   1246         snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
   1247         write(fd, buffer, strlen(buffer));
   1248         mInputs.valueAt(i)->dump(fd);
   1249     }
   1250 
   1251     snprintf(buffer, SIZE, "\nStreams dump:\n");
   1252     write(fd, buffer, strlen(buffer));
   1253     snprintf(buffer, SIZE,
   1254              " Stream  Can be muted  Index Min  Index Max  Index Cur [device : index]...\n");
   1255     write(fd, buffer, strlen(buffer));
   1256     for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
   1257         snprintf(buffer, SIZE, " %02d      ", i);
   1258         write(fd, buffer, strlen(buffer));
   1259         mStreams[i].dump(fd);
   1260     }
   1261 
   1262     snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
   1263             (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
   1264     write(fd, buffer, strlen(buffer));
   1265 
   1266     snprintf(buffer, SIZE, "Registered effects:\n");
   1267     write(fd, buffer, strlen(buffer));
   1268     for (size_t i = 0; i < mEffects.size(); i++) {
   1269         snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
   1270         write(fd, buffer, strlen(buffer));
   1271         mEffects.valueAt(i)->dump(fd);
   1272     }
   1273 
   1274 
   1275     return NO_ERROR;
   1276 }
   1277 
   1278 // ----------------------------------------------------------------------------
   1279 // AudioPolicyManagerBase
   1280 // ----------------------------------------------------------------------------
   1281 
   1282 AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
   1283     :
   1284 #ifdef AUDIO_POLICY_TEST
   1285     Thread(false),
   1286 #endif //AUDIO_POLICY_TEST
   1287     mPrimaryOutput((audio_io_handle_t)0),
   1288     mAvailableOutputDevices(AUDIO_DEVICE_NONE),
   1289     mPhoneState(AudioSystem::MODE_NORMAL),
   1290     mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
   1291     mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
   1292     mA2dpSuspended(false), mHasA2dp(false), mHasUsb(false), mHasRemoteSubmix(false)
   1293 {
   1294     mpClientInterface = clientInterface;
   1295 
   1296     for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
   1297         mForceUse[i] = AudioSystem::FORCE_NONE;
   1298     }
   1299 
   1300     initializeVolumeCurves();
   1301 
   1302     mA2dpDeviceAddress = String8("");
   1303     mScoDeviceAddress = String8("");
   1304     mUsbCardAndDevice = String8("");
   1305 
   1306     if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
   1307         if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
   1308             ALOGE("could not load audio policy configuration file, setting defaults");
   1309             defaultAudioPolicyConfig();
   1310         }
   1311     }
   1312 
   1313     // open all output streams needed to access attached devices
   1314     for (size_t i = 0; i < mHwModules.size(); i++) {
   1315         mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
   1316         if (mHwModules[i]->mHandle == 0) {
   1317             ALOGW("could not open HW module %s", mHwModules[i]->mName);
   1318             continue;
   1319         }
   1320         // open all output streams needed to access attached devices
   1321         for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
   1322         {
   1323             const IOProfile *outProfile = mHwModules[i]->mOutputProfiles[j];
   1324 
   1325             if (outProfile->mSupportedDevices & mAttachedOutputDevices) {
   1326                 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile);
   1327                 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice &
   1328                                                             outProfile->mSupportedDevices);
   1329                 audio_io_handle_t output = mpClientInterface->openOutput(
   1330                                                 outProfile->mModule->mHandle,
   1331                                                 &outputDesc->mDevice,
   1332                                                 &outputDesc->mSamplingRate,
   1333                                                 &outputDesc->mFormat,
   1334                                                 &outputDesc->mChannelMask,
   1335                                                 &outputDesc->mLatency,
   1336                                                 outputDesc->mFlags);
   1337                 if (output == 0) {
   1338                     delete outputDesc;
   1339                 } else {
   1340                     mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices |
   1341                                             (outProfile->mSupportedDevices & mAttachedOutputDevices));
   1342                     if (mPrimaryOutput == 0 &&
   1343                             outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
   1344                         mPrimaryOutput = output;
   1345                     }
   1346                     addOutput(output, outputDesc);
   1347                     setOutputDevice(output,
   1348                                     (audio_devices_t)(mDefaultOutputDevice &
   1349                                                         outProfile->mSupportedDevices),
   1350                                     true);
   1351                 }
   1352             }
   1353         }
   1354     }
   1355 
   1356     ALOGE_IF((mAttachedOutputDevices & ~mAvailableOutputDevices),
   1357              "Not output found for attached devices %08x",
   1358              (mAttachedOutputDevices & ~mAvailableOutputDevices));
   1359 
   1360     ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
   1361 
   1362     updateDevicesAndOutputs();
   1363 
   1364 #ifdef AUDIO_POLICY_TEST
   1365     if (mPrimaryOutput != 0) {
   1366         AudioParameter outputCmd = AudioParameter();
   1367         outputCmd.addInt(String8("set_id"), 0);
   1368         mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
   1369 
   1370         mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
   1371         mTestSamplingRate = 44100;
   1372         mTestFormat = AudioSystem::PCM_16_BIT;
   1373         mTestChannels =  AudioSystem::CHANNEL_OUT_STEREO;
   1374         mTestLatencyMs = 0;
   1375         mCurOutput = 0;
   1376         mDirectOutput = false;
   1377         for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
   1378             mTestOutputs[i] = 0;
   1379         }
   1380 
   1381         const size_t SIZE = 256;
   1382         char buffer[SIZE];
   1383         snprintf(buffer, SIZE, "AudioPolicyManagerTest");
   1384         run(buffer, ANDROID_PRIORITY_AUDIO);
   1385     }
   1386 #endif //AUDIO_POLICY_TEST
   1387 }
   1388 
   1389 AudioPolicyManagerBase::~AudioPolicyManagerBase()
   1390 {
   1391 #ifdef AUDIO_POLICY_TEST
   1392     exit();
   1393 #endif //AUDIO_POLICY_TEST
   1394    for (size_t i = 0; i < mOutputs.size(); i++) {
   1395         mpClientInterface->closeOutput(mOutputs.keyAt(i));
   1396         delete mOutputs.valueAt(i);
   1397    }
   1398    for (size_t i = 0; i < mInputs.size(); i++) {
   1399         mpClientInterface->closeInput(mInputs.keyAt(i));
   1400         delete mInputs.valueAt(i);
   1401    }
   1402    for (size_t i = 0; i < mHwModules.size(); i++) {
   1403         delete mHwModules[i];
   1404    }
   1405 }
   1406 
   1407 status_t AudioPolicyManagerBase::initCheck()
   1408 {
   1409     return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
   1410 }
   1411 
   1412 #ifdef AUDIO_POLICY_TEST
   1413 bool AudioPolicyManagerBase::threadLoop()
   1414 {
   1415     ALOGV("entering threadLoop()");
   1416     while (!exitPending())
   1417     {
   1418         String8 command;
   1419         int valueInt;
   1420         String8 value;
   1421 
   1422         Mutex::Autolock _l(mLock);
   1423         mWaitWorkCV.waitRelative(mLock, milliseconds(50));
   1424 
   1425         command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
   1426         AudioParameter param = AudioParameter(command);
   1427 
   1428         if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
   1429             valueInt != 0) {
   1430             ALOGV("Test command %s received", command.string());
   1431             String8 target;
   1432             if (param.get(String8("target"), target) != NO_ERROR) {
   1433                 target = "Manager";
   1434             }
   1435             if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
   1436                 param.remove(String8("test_cmd_policy_output"));
   1437                 mCurOutput = valueInt;
   1438             }
   1439             if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
   1440                 param.remove(String8("test_cmd_policy_direct"));
   1441                 if (value == "false") {
   1442                     mDirectOutput = false;
   1443                 } else if (value == "true") {
   1444                     mDirectOutput = true;
   1445                 }
   1446             }
   1447             if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
   1448                 param.remove(String8("test_cmd_policy_input"));
   1449                 mTestInput = valueInt;
   1450             }
   1451 
   1452             if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
   1453                 param.remove(String8("test_cmd_policy_format"));
   1454                 int format = AudioSystem::INVALID_FORMAT;
   1455                 if (value == "PCM 16 bits") {
   1456                     format = AudioSystem::PCM_16_BIT;
   1457                 } else if (value == "PCM 8 bits") {
   1458                     format = AudioSystem::PCM_8_BIT;
   1459                 } else if (value == "Compressed MP3") {
   1460                     format = AudioSystem::MP3;
   1461                 }
   1462                 if (format != AudioSystem::INVALID_FORMAT) {
   1463                     if (target == "Manager") {
   1464                         mTestFormat = format;
   1465                     } else if (mTestOutputs[mCurOutput] != 0) {
   1466                         AudioParameter outputParam = AudioParameter();
   1467                         outputParam.addInt(String8("format"), format);
   1468                         mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
   1469                     }
   1470                 }
   1471             }
   1472             if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
   1473                 param.remove(String8("test_cmd_policy_channels"));
   1474                 int channels = 0;
   1475 
   1476                 if (value == "Channels Stereo") {
   1477                     channels =  AudioSystem::CHANNEL_OUT_STEREO;
   1478                 } else if (value == "Channels Mono") {
   1479                     channels =  AudioSystem::CHANNEL_OUT_MONO;
   1480                 }
   1481                 if (channels != 0) {
   1482                     if (target == "Manager") {
   1483                         mTestChannels = channels;
   1484                     } else if (mTestOutputs[mCurOutput] != 0) {
   1485                         AudioParameter outputParam = AudioParameter();
   1486                         outputParam.addInt(String8("channels"), channels);
   1487                         mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
   1488                     }
   1489                 }
   1490             }
   1491             if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
   1492                 param.remove(String8("test_cmd_policy_sampleRate"));
   1493                 if (valueInt >= 0 && valueInt <= 96000) {
   1494                     int samplingRate = valueInt;
   1495                     if (target == "Manager") {
   1496                         mTestSamplingRate = samplingRate;
   1497                     } else if (mTestOutputs[mCurOutput] != 0) {
   1498                         AudioParameter outputParam = AudioParameter();
   1499                         outputParam.addInt(String8("sampling_rate"), samplingRate);
   1500                         mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
   1501                     }
   1502                 }
   1503             }
   1504 
   1505             if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
   1506                 param.remove(String8("test_cmd_policy_reopen"));
   1507 
   1508                 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
   1509                 mpClientInterface->closeOutput(mPrimaryOutput);
   1510 
   1511                 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
   1512 
   1513                 delete mOutputs.valueFor(mPrimaryOutput);
   1514                 mOutputs.removeItem(mPrimaryOutput);
   1515 
   1516                 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
   1517                 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
   1518                 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
   1519                                                 &outputDesc->mDevice,
   1520                                                 &outputDesc->mSamplingRate,
   1521                                                 &outputDesc->mFormat,
   1522                                                 &outputDesc->mChannelMask,
   1523                                                 &outputDesc->mLatency,
   1524                                                 outputDesc->mFlags);
   1525                 if (mPrimaryOutput == 0) {
   1526                     ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
   1527                             outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
   1528                 } else {
   1529                     AudioParameter outputCmd = AudioParameter();
   1530                     outputCmd.addInt(String8("set_id"), 0);
   1531                     mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
   1532                     addOutput(mPrimaryOutput, outputDesc);
   1533                 }
   1534             }
   1535 
   1536 
   1537             mpClientInterface->setParameters(0, String8("test_cmd_policy="));
   1538         }
   1539     }
   1540     return false;
   1541 }
   1542 
   1543 void AudioPolicyManagerBase::exit()
   1544 {
   1545     {
   1546         AutoMutex _l(mLock);
   1547         requestExit();
   1548         mWaitWorkCV.signal();
   1549     }
   1550     requestExitAndWait();
   1551 }
   1552 
   1553 int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
   1554 {
   1555     for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
   1556         if (output == mTestOutputs[i]) return i;
   1557     }
   1558     return 0;
   1559 }
   1560 #endif //AUDIO_POLICY_TEST
   1561 
   1562 // ---
   1563 
   1564 void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
   1565 {
   1566     outputDesc->mId = id;
   1567     mOutputs.add(id, outputDesc);
   1568 }
   1569 
   1570 
   1571 status_t AudioPolicyManagerBase::checkOutputsForDevice(audio_devices_t device,
   1572                                                        AudioSystem::device_connection_state state,
   1573                                                        SortedVector<audio_io_handle_t>& outputs)
   1574 {
   1575     AudioOutputDescriptor *desc;
   1576 
   1577     if (state == AudioSystem::DEVICE_STATE_AVAILABLE) {
   1578         // first list already open outputs that can be routed to this device
   1579         for (size_t i = 0; i < mOutputs.size(); i++) {
   1580             desc = mOutputs.valueAt(i);
   1581             if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices & device)) {
   1582                 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
   1583                 outputs.add(mOutputs.keyAt(i));
   1584             }
   1585         }
   1586         // then look for output profiles that can be routed to this device
   1587         SortedVector<IOProfile *> profiles;
   1588         for (size_t i = 0; i < mHwModules.size(); i++)
   1589         {
   1590             if (mHwModules[i]->mHandle == 0) {
   1591                 continue;
   1592             }
   1593             for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
   1594             {
   1595                 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices & device) {
   1596                     ALOGV("checkOutputsForDevice(): adding profile %d from module %d", j, i);
   1597                     profiles.add(mHwModules[i]->mOutputProfiles[j]);
   1598                 }
   1599             }
   1600         }
   1601 
   1602         if (profiles.isEmpty() && outputs.isEmpty()) {
   1603             ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
   1604             return BAD_VALUE;
   1605         }
   1606 
   1607         // open outputs for matching profiles if needed. Direct outputs are also opened to
   1608         // query for dynamic parameters and will be closed later by setDeviceConnectionState()
   1609         for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
   1610             IOProfile *profile = profiles[profile_index];
   1611 
   1612             // nothing to do if one output is already opened for this profile
   1613             size_t j;
   1614             for (j = 0; j < mOutputs.size(); j++) {
   1615                 desc = mOutputs.valueAt(j);
   1616                 if (!desc->isDuplicated() && desc->mProfile == profile) {
   1617                     break;
   1618                 }
   1619             }
   1620             if (j != mOutputs.size()) {
   1621                 continue;
   1622             }
   1623 
   1624             ALOGV("opening output for device %08x", device);
   1625             desc = new AudioOutputDescriptor(profile);
   1626             desc->mDevice = device;
   1627             audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
   1628                                                                        &desc->mDevice,
   1629                                                                        &desc->mSamplingRate,
   1630                                                                        &desc->mFormat,
   1631                                                                        &desc->mChannelMask,
   1632                                                                        &desc->mLatency,
   1633                                                                        desc->mFlags);
   1634             if (output != 0) {
   1635                 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
   1636                     String8 reply;
   1637                     char *value;
   1638                     if (profile->mSamplingRates[0] == 0) {
   1639                         reply = mpClientInterface->getParameters(output,
   1640                                                 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
   1641                         ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
   1642                                   reply.string());
   1643                         value = strpbrk((char *)reply.string(), "=");
   1644                         if (value != NULL) {
   1645                             loadSamplingRates(value, profile);
   1646                         }
   1647                     }
   1648                     if (profile->mFormats[0] == 0) {
   1649                         reply = mpClientInterface->getParameters(output,
   1650                                                        String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
   1651                         ALOGV("checkOutputsForDevice() direct output sup formats %s",
   1652                                   reply.string());
   1653                         value = strpbrk((char *)reply.string(), "=");
   1654                         if (value != NULL) {
   1655                             loadFormats(value, profile);
   1656                         }
   1657                     }
   1658                     if (profile->mChannelMasks[0] == 0) {
   1659                         reply = mpClientInterface->getParameters(output,
   1660                                                       String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
   1661                         ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
   1662                                   reply.string());
   1663                         value = strpbrk((char *)reply.string(), "=");
   1664                         if (value != NULL) {
   1665                             loadOutChannels(value + 1, profile);
   1666                         }
   1667                     }
   1668                     if (((profile->mSamplingRates[0] == 0) &&
   1669                              (profile->mSamplingRates.size() < 2)) ||
   1670                          ((profile->mFormats[0] == 0) &&
   1671                              (profile->mFormats.size() < 2)) ||
   1672                          ((profile->mFormats[0] == 0) &&
   1673                              (profile->mChannelMasks.size() < 2))) {
   1674                         ALOGW("checkOutputsForDevice() direct output missing param");
   1675                         output = 0;
   1676                     } else {
   1677                         addOutput(output, desc);
   1678                     }
   1679                 } else {
   1680                     audio_io_handle_t duplicatedOutput = 0;
   1681                     // add output descriptor
   1682                     addOutput(output, desc);
   1683                     // set initial stream volume for device
   1684                     applyStreamVolumes(output, device, 0, true);
   1685 
   1686                     //TODO: configure audio effect output stage here
   1687 
   1688                     // open a duplicating output thread for the new output and the primary output
   1689                     duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
   1690                                                                               mPrimaryOutput);
   1691                     if (duplicatedOutput != 0) {
   1692                         // add duplicated output descriptor
   1693                         AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL);
   1694                         dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
   1695                         dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
   1696                         dupOutputDesc->mSamplingRate = desc->mSamplingRate;
   1697                         dupOutputDesc->mFormat = desc->mFormat;
   1698                         dupOutputDesc->mChannelMask = desc->mChannelMask;
   1699                         dupOutputDesc->mLatency = desc->mLatency;
   1700                         addOutput(duplicatedOutput, dupOutputDesc);
   1701                         applyStreamVolumes(duplicatedOutput, device, 0, true);
   1702                     } else {
   1703                         ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
   1704                                 mPrimaryOutput, output);
   1705                         mpClientInterface->closeOutput(output);
   1706                         mOutputs.removeItem(output);
   1707                         output = 0;
   1708                     }
   1709                 }
   1710             }
   1711             if (output == 0) {
   1712                 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
   1713                 delete desc;
   1714                 profiles.removeAt(profile_index);
   1715                 profile_index--;
   1716             } else {
   1717                 outputs.add(output);
   1718                 ALOGV("checkOutputsForDevice(): adding output %d", output);
   1719             }
   1720         }
   1721 
   1722         if (profiles.isEmpty()) {
   1723             ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
   1724             return BAD_VALUE;
   1725         }
   1726     } else {
   1727         // check if one opened output is not needed any more after disconnecting one device
   1728         for (size_t i = 0; i < mOutputs.size(); i++) {
   1729             desc = mOutputs.valueAt(i);
   1730             if (!desc->isDuplicated() &&
   1731                     !(desc->mProfile->mSupportedDevices & mAvailableOutputDevices)) {
   1732                 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
   1733                 outputs.add(mOutputs.keyAt(i));
   1734             }
   1735         }
   1736         for (size_t i = 0; i < mHwModules.size(); i++)
   1737         {
   1738             if (mHwModules[i]->mHandle == 0) {
   1739                 continue;
   1740             }
   1741             for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
   1742             {
   1743                 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
   1744                 if ((profile->mSupportedDevices & device) &&
   1745                         (profile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
   1746                     ALOGV("checkOutputsForDevice(): clearing direct output profile %d on module %d",
   1747                           j, i);
   1748                     if (profile->mSamplingRates[0] == 0) {
   1749                         profile->mSamplingRates.clear();
   1750                         profile->mSamplingRates.add(0);
   1751                     }
   1752                     if (profile->mFormats[0] == 0) {
   1753                         profile->mFormats.clear();
   1754                         profile->mFormats.add((audio_format_t)0);
   1755                     }
   1756                     if (profile->mChannelMasks[0] == 0) {
   1757                         profile->mChannelMasks.clear();
   1758                         profile->mChannelMasks.add((audio_channel_mask_t)0);
   1759                     }
   1760                 }
   1761             }
   1762         }
   1763     }
   1764     return NO_ERROR;
   1765 }
   1766 
   1767 void AudioPolicyManagerBase::closeOutput(audio_io_handle_t output)
   1768 {
   1769     ALOGV("closeOutput(%d)", output);
   1770 
   1771     AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
   1772     if (outputDesc == NULL) {
   1773         ALOGW("closeOutput() unknown output %d", output);
   1774         return;
   1775     }
   1776 
   1777     // look for duplicated outputs connected to the output being removed.
   1778     for (size_t i = 0; i < mOutputs.size(); i++) {
   1779         AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i);
   1780         if (dupOutputDesc->isDuplicated() &&
   1781                 (dupOutputDesc->mOutput1 == outputDesc ||
   1782                 dupOutputDesc->mOutput2 == outputDesc)) {
   1783             AudioOutputDescriptor *outputDesc2;
   1784             if (dupOutputDesc->mOutput1 == outputDesc) {
   1785                 outputDesc2 = dupOutputDesc->mOutput2;
   1786             } else {
   1787                 outputDesc2 = dupOutputDesc->mOutput1;
   1788             }
   1789             // As all active tracks on duplicated output will be deleted,
   1790             // and as they were also referenced on the other output, the reference
   1791             // count for their stream type must be adjusted accordingly on
   1792             // the other output.
   1793             for (int j = 0; j < (int)AudioSystem::NUM_STREAM_TYPES; j++) {
   1794                 int refCount = dupOutputDesc->mRefCount[j];
   1795                 outputDesc2->changeRefCount((AudioSystem::stream_type)j,-refCount);
   1796             }
   1797             audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
   1798             ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
   1799 
   1800             mpClientInterface->closeOutput(duplicatedOutput);
   1801             delete mOutputs.valueFor(duplicatedOutput);
   1802             mOutputs.removeItem(duplicatedOutput);
   1803         }
   1804     }
   1805 
   1806     AudioParameter param;
   1807     param.add(String8("closing"), String8("true"));
   1808     mpClientInterface->setParameters(output, param.toString());
   1809 
   1810     mpClientInterface->closeOutput(output);
   1811     delete mOutputs.valueFor(output);
   1812     mOutputs.removeItem(output);
   1813 }
   1814 
   1815 SortedVector<audio_io_handle_t> AudioPolicyManagerBase::getOutputsForDevice(audio_devices_t device,
   1816                         DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> openOutputs)
   1817 {
   1818     SortedVector<audio_io_handle_t> outputs;
   1819 
   1820     ALOGVV("getOutputsForDevice() device %04x", device);
   1821     for (size_t i = 0; i < openOutputs.size(); i++) {
   1822         ALOGVV("output %d isDuplicated=%d device=%04x",
   1823                 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
   1824         if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
   1825             ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
   1826             outputs.add(openOutputs.keyAt(i));
   1827         }
   1828     }
   1829     return outputs;
   1830 }
   1831 
   1832 bool AudioPolicyManagerBase::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
   1833                                    SortedVector<audio_io_handle_t>& outputs2)
   1834 {
   1835     if (outputs1.size() != outputs2.size()) {
   1836         return false;
   1837     }
   1838     for (size_t i = 0; i < outputs1.size(); i++) {
   1839         if (outputs1[i] != outputs2[i]) {
   1840             return false;
   1841         }
   1842     }
   1843     return true;
   1844 }
   1845 
   1846 void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy)
   1847 {
   1848     audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
   1849     audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
   1850     SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
   1851     SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
   1852 
   1853     if (!vectorsEqual(srcOutputs,dstOutputs)) {
   1854         ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
   1855               strategy, srcOutputs[0], dstOutputs[0]);
   1856         // mute strategy while moving tracks from one output to another
   1857         for (size_t i = 0; i < srcOutputs.size(); i++) {
   1858             AudioOutputDescriptor *desc = mOutputs.valueFor(srcOutputs[i]);
   1859             if (desc->strategyRefCount(strategy) != 0) {
   1860                 setStrategyMute(strategy, true, srcOutputs[i]);
   1861                 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
   1862             }
   1863         }
   1864 
   1865         // Move effects associated to this strategy from previous output to new output
   1866         if (strategy == STRATEGY_MEDIA) {
   1867             int outIdx = 0;
   1868             for (size_t i = 0; i < dstOutputs.size(); i++) {
   1869                 AudioOutputDescriptor *desc = mOutputs.valueFor(dstOutputs[i]);
   1870                 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) {
   1871                     outIdx = i;
   1872                 }
   1873             }
   1874             SortedVector<audio_io_handle_t> moved;
   1875             for (size_t i = 0; i < mEffects.size(); i++) {
   1876                 EffectDescriptor *desc = mEffects.valueAt(i);
   1877                 if (desc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
   1878                         desc->mIo != dstOutputs[outIdx]) {
   1879                     if (moved.indexOf(desc->mIo) < 0) {
   1880                         ALOGV("checkOutputForStrategy() moving effect %d to output %d",
   1881                               mEffects.keyAt(i), dstOutputs[outIdx]);
   1882                         mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, desc->mIo,
   1883                                                        dstOutputs[outIdx]);
   1884                         moved.add(desc->mIo);
   1885                     }
   1886                     desc->mIo = dstOutputs[outIdx];
   1887                 }
   1888             }
   1889         }
   1890         // Move tracks associated to this strategy from previous output to new output
   1891         for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
   1892             if (getStrategy((AudioSystem::stream_type)i) == strategy) {
   1893                 //FIXME see fixme on name change
   1894                 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i,
   1895                                                    dstOutputs[0] /* ignored */);
   1896             }
   1897         }
   1898     }
   1899 }
   1900 
   1901 void AudioPolicyManagerBase::checkOutputForAllStrategies()
   1902 {
   1903     checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
   1904     checkOutputForStrategy(STRATEGY_PHONE);
   1905     checkOutputForStrategy(STRATEGY_SONIFICATION);
   1906     checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
   1907     checkOutputForStrategy(STRATEGY_MEDIA);
   1908     checkOutputForStrategy(STRATEGY_DTMF);
   1909 }
   1910 
   1911 audio_io_handle_t AudioPolicyManagerBase::getA2dpOutput()
   1912 {
   1913     if (!mHasA2dp) {
   1914         return 0;
   1915     }
   1916 
   1917     for (size_t i = 0; i < mOutputs.size(); i++) {
   1918         AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
   1919         if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
   1920             return mOutputs.keyAt(i);
   1921         }
   1922     }
   1923 
   1924     return 0;
   1925 }
   1926 
   1927 void AudioPolicyManagerBase::checkA2dpSuspend()
   1928 {
   1929     if (!mHasA2dp) {
   1930         return;
   1931     }
   1932     audio_io_handle_t a2dpOutput = getA2dpOutput();
   1933     if (a2dpOutput == 0) {
   1934         return;
   1935     }
   1936 
   1937     // suspend A2DP output if:
   1938     //      (NOT already suspended) &&
   1939     //      ((SCO device is connected &&
   1940     //       (forced usage for communication || for record is SCO))) ||
   1941     //      (phone state is ringing || in call)
   1942     //
   1943     // restore A2DP output if:
   1944     //      (Already suspended) &&
   1945     //      ((SCO device is NOT connected ||
   1946     //       (forced usage NOT for communication && NOT for record is SCO))) &&
   1947     //      (phone state is NOT ringing && NOT in call)
   1948     //
   1949     if (mA2dpSuspended) {
   1950         if (((mScoDeviceAddress == "") ||
   1951              ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) &&
   1952               (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) &&
   1953              ((mPhoneState != AudioSystem::MODE_IN_CALL) &&
   1954               (mPhoneState != AudioSystem::MODE_RINGTONE))) {
   1955 
   1956             mpClientInterface->restoreOutput(a2dpOutput);
   1957             mA2dpSuspended = false;
   1958         }
   1959     } else {
   1960         if (((mScoDeviceAddress != "") &&
   1961              ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
   1962               (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) ||
   1963              ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
   1964               (mPhoneState == AudioSystem::MODE_RINGTONE))) {
   1965 
   1966             mpClientInterface->suspendOutput(a2dpOutput);
   1967             mA2dpSuspended = true;
   1968         }
   1969     }
   1970 }
   1971 
   1972 audio_devices_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
   1973 {
   1974     audio_devices_t device = AUDIO_DEVICE_NONE;
   1975 
   1976     AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
   1977     // check the following by order of priority to request a routing change if necessary:
   1978     // 1: the strategy enforced audible is active on the output:
   1979     //      use device for strategy enforced audible
   1980     // 2: we are in call or the strategy phone is active on the output:
   1981     //      use device for strategy phone
   1982     // 3: the strategy sonification is active on the output:
   1983     //      use device for strategy sonification
   1984     // 4: the strategy "respectful" sonification is active on the output:
   1985     //      use device for strategy "respectful" sonification
   1986     // 5: the strategy media is active on the output:
   1987     //      use device for strategy media
   1988     // 6: the strategy DTMF is active on the output:
   1989     //      use device for strategy DTMF
   1990     if (outputDesc->isUsedByStrategy(STRATEGY_ENFORCED_AUDIBLE)) {
   1991         device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
   1992     } else if (isInCall() ||
   1993                     outputDesc->isUsedByStrategy(STRATEGY_PHONE)) {
   1994         device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
   1995     } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION)) {
   1996         device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
   1997     } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION_RESPECTFUL)) {
   1998         device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
   1999     } else if (outputDesc->isUsedByStrategy(STRATEGY_MEDIA)) {
   2000         device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
   2001     } else if (outputDesc->isUsedByStrategy(STRATEGY_DTMF)) {
   2002         device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
   2003     }
   2004 
   2005     ALOGV("getNewDevice() selected device %x", device);
   2006     return device;
   2007 }
   2008 
   2009 uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
   2010     return (uint32_t)getStrategy(stream);
   2011 }
   2012 
   2013 audio_devices_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) {
   2014     audio_devices_t devices;
   2015     // By checking the range of stream before calling getStrategy, we avoid
   2016     // getStrategy's behavior for invalid streams.  getStrategy would do a ALOGE
   2017     // and then return STRATEGY_MEDIA, but we want to return the empty set.
   2018     if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
   2019         devices = AUDIO_DEVICE_NONE;
   2020     } else {
   2021         AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream);
   2022         devices = getDeviceForStrategy(strategy, true /*fromCache*/);
   2023     }
   2024     return devices;
   2025 }
   2026 
   2027 AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
   2028         AudioSystem::stream_type stream) {
   2029     // stream to strategy mapping
   2030     switch (stream) {
   2031     case AudioSystem::VOICE_CALL:
   2032     case AudioSystem::BLUETOOTH_SCO:
   2033         return STRATEGY_PHONE;
   2034     case AudioSystem::RING:
   2035     case AudioSystem::ALARM:
   2036         return STRATEGY_SONIFICATION;
   2037     case AudioSystem::NOTIFICATION:
   2038         return STRATEGY_SONIFICATION_RESPECTFUL;
   2039     case AudioSystem::DTMF:
   2040         return STRATEGY_DTMF;
   2041     default:
   2042         ALOGE("unknown stream type");
   2043     case AudioSystem::SYSTEM:
   2044         // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
   2045         // while key clicks are played produces a poor result
   2046     case AudioSystem::TTS:
   2047     case AudioSystem::MUSIC:
   2048         return STRATEGY_MEDIA;
   2049     case AudioSystem::ENFORCED_AUDIBLE:
   2050         return STRATEGY_ENFORCED_AUDIBLE;
   2051     }
   2052 }
   2053 
   2054 void AudioPolicyManagerBase::handleNotificationRoutingForStream(AudioSystem::stream_type stream) {
   2055     switch(stream) {
   2056     case AudioSystem::MUSIC:
   2057         checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
   2058         updateDevicesAndOutputs();
   2059         break;
   2060     default:
   2061         break;
   2062     }
   2063 }
   2064 
   2065 audio_devices_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy,
   2066                                                              bool fromCache)
   2067 {
   2068     uint32_t device = AUDIO_DEVICE_NONE;
   2069 
   2070     if (fromCache) {
   2071         ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
   2072               strategy, mDeviceForStrategy[strategy]);
   2073         return mDeviceForStrategy[strategy];
   2074     }
   2075 
   2076     switch (strategy) {
   2077 
   2078     case STRATEGY_SONIFICATION_RESPECTFUL:
   2079         if (isInCall()) {
   2080             device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
   2081         } else if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
   2082             // while media is playing (or has recently played), use the same device
   2083             device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
   2084         } else {
   2085             // when media is not playing anymore, fall back on the sonification behavior
   2086             device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
   2087         }
   2088 
   2089         break;
   2090 
   2091     case STRATEGY_DTMF:
   2092         if (!isInCall()) {
   2093             // when off call, DTMF strategy follows the same rules as MEDIA strategy
   2094             device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
   2095             break;
   2096         }
   2097         // when in call, DTMF and PHONE strategies follow the same rules
   2098         // FALL THROUGH
   2099 
   2100     case STRATEGY_PHONE:
   2101         // for phone strategy, we first consider the forced use and then the available devices by order
   2102         // of priority
   2103         switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
   2104         case AudioSystem::FORCE_BT_SCO:
   2105             if (!isInCall() || strategy != STRATEGY_DTMF) {
   2106                 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
   2107                 if (device) break;
   2108             }
   2109             device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
   2110             if (device) break;
   2111             device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
   2112             if (device) break;
   2113             // if SCO device is requested but no SCO device is available, fall back to default case
   2114             // FALL THROUGH
   2115 
   2116         default:    // FORCE_NONE
   2117             // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
   2118             if (mHasA2dp && !isInCall() &&
   2119                     (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
   2120                     (getA2dpOutput() != 0) && !mA2dpSuspended) {
   2121                 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
   2122                 if (device) break;
   2123                 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
   2124                 if (device) break;
   2125             }
   2126             device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
   2127             if (device) break;
   2128             device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
   2129             if (device) break;
   2130             if (mPhoneState != AudioSystem::MODE_IN_CALL) {
   2131                 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
   2132                 if (device) break;
   2133                 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
   2134                 if (device) break;
   2135                 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
   2136                 if (device) break;
   2137                 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
   2138                 if (device) break;
   2139                 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
   2140                 if (device) break;
   2141             }
   2142             device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_EARPIECE;
   2143             if (device) break;
   2144             device = mDefaultOutputDevice;
   2145             if (device == AUDIO_DEVICE_NONE) {
   2146                 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
   2147             }
   2148             break;
   2149 
   2150         case AudioSystem::FORCE_SPEAKER:
   2151             // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
   2152             // A2DP speaker when forcing to speaker output
   2153             if (mHasA2dp && !isInCall() &&
   2154                     (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
   2155                     (getA2dpOutput() != 0) && !mA2dpSuspended) {
   2156                 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
   2157                 if (device) break;
   2158             }
   2159             if (mPhoneState != AudioSystem::MODE_IN_CALL) {
   2160                 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
   2161                 if (device) break;
   2162                 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
   2163                 if (device) break;
   2164                 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
   2165                 if (device) break;
   2166                 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
   2167                 if (device) break;
   2168                 device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
   2169                 if (device) break;
   2170             }
   2171             device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
   2172             if (device) break;
   2173             device = mDefaultOutputDevice;
   2174             if (device == AUDIO_DEVICE_NONE) {
   2175                 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
   2176             }
   2177             break;
   2178         }
   2179     break;
   2180 
   2181     case STRATEGY_SONIFICATION:
   2182 
   2183         // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
   2184         // handleIncallSonification().
   2185         if (isInCall()) {
   2186             device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
   2187             break;
   2188         }
   2189         // FALL THROUGH
   2190 
   2191     case STRATEGY_ENFORCED_AUDIBLE:
   2192         // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
   2193         // except:
   2194         //   - when in call where it doesn't default to STRATEGY_PHONE behavior
   2195         //   - in countries where not enforced in which case it follows STRATEGY_MEDIA
   2196 
   2197         if ((strategy == STRATEGY_SONIFICATION) ||
   2198                 (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_SYSTEM_ENFORCED)) {
   2199             device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
   2200             if (device == AUDIO_DEVICE_NONE) {
   2201                 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
   2202             }
   2203         }
   2204         // The second device used for sonification is the same as the device used by media strategy
   2205         // FALL THROUGH
   2206 
   2207     case STRATEGY_MEDIA: {
   2208         uint32_t device2 = AUDIO_DEVICE_NONE;
   2209         if (strategy != STRATEGY_SONIFICATION) {
   2210             // no sonification on remote submix (e.g. WFD)
   2211             device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
   2212         }
   2213         if ((device2 == AUDIO_DEVICE_NONE) &&
   2214                 mHasA2dp && (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
   2215                 (getA2dpOutput() != 0) && !mA2dpSuspended) {
   2216             device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
   2217             if (device2 == AUDIO_DEVICE_NONE) {
   2218                 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
   2219             }
   2220             if (device2 == AUDIO_DEVICE_NONE) {
   2221                 device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
   2222             }
   2223         }
   2224         if (device2 == AUDIO_DEVICE_NONE) {
   2225             device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
   2226         }
   2227         if (device2 == AUDIO_DEVICE_NONE) {
   2228             device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
   2229         }
   2230         if (device2 == AUDIO_DEVICE_NONE) {
   2231             device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
   2232         }
   2233         if (device2 == AUDIO_DEVICE_NONE) {
   2234             device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
   2235         }
   2236         if (device2 == AUDIO_DEVICE_NONE) {
   2237             device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
   2238         }
   2239         if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
   2240             // no sonification on aux digital (e.g. HDMI)
   2241             device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
   2242         }
   2243         if ((device2 == AUDIO_DEVICE_NONE) &&
   2244                 (mForceUse[AudioSystem::FOR_DOCK] == AudioSystem::FORCE_ANALOG_DOCK)) {
   2245             device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
   2246         }
   2247         if (device2 == AUDIO_DEVICE_NONE) {
   2248             device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
   2249         }
   2250 
   2251         // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
   2252         // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
   2253         device |= device2;
   2254         if (device) break;
   2255         device = mDefaultOutputDevice;
   2256         if (device == AUDIO_DEVICE_NONE) {
   2257             ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
   2258         }
   2259         } break;
   2260 
   2261     default:
   2262         ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
   2263         break;
   2264     }
   2265 
   2266     ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
   2267     return device;
   2268 }
   2269 
   2270 void AudioPolicyManagerBase::updateDevicesAndOutputs()
   2271 {
   2272     for (int i = 0; i < NUM_STRATEGIES; i++) {
   2273         mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
   2274     }
   2275     mPreviousOutputs = mOutputs;
   2276 }
   2277 
   2278 uint32_t AudioPolicyManagerBase::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
   2279                                                        audio_devices_t prevDevice,
   2280                                                        uint32_t delayMs)
   2281 {
   2282     // mute/unmute strategies using an incompatible device combination
   2283     // if muting, wait for the audio in pcm buffer to be drained before proceeding
   2284     // if unmuting, unmute only after the specified delay
   2285     if (outputDesc->isDuplicated()) {
   2286         return 0;
   2287     }
   2288 
   2289     uint32_t muteWaitMs = 0;
   2290     audio_devices_t device = outputDesc->device();
   2291     bool shouldMute = (outputDesc->refCount() != 0) &&
   2292                     (AudioSystem::popCount(device) >= 2);
   2293     // temporary mute output if device selection changes to avoid volume bursts due to
   2294     // different per device volumes
   2295     bool tempMute = (outputDesc->refCount() != 0) && (device != prevDevice);
   2296 
   2297     for (size_t i = 0; i < NUM_STRATEGIES; i++) {
   2298         audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
   2299         bool mute = shouldMute && (curDevice & device) && (curDevice != device);
   2300         bool doMute = false;
   2301 
   2302         if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
   2303             doMute = true;
   2304             outputDesc->mStrategyMutedByDevice[i] = true;
   2305         } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
   2306             doMute = true;
   2307             outputDesc->mStrategyMutedByDevice[i] = false;
   2308         }
   2309         if (doMute || tempMute) {
   2310             for (size_t j = 0; j < mOutputs.size(); j++) {
   2311                 AudioOutputDescriptor *desc = mOutputs.valueAt(j);
   2312                 if ((desc->supportedDevices() & outputDesc->supportedDevices())
   2313                         == AUDIO_DEVICE_NONE) {
   2314                     continue;
   2315                 }
   2316                 audio_io_handle_t curOutput = mOutputs.keyAt(j);
   2317                 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
   2318                       mute ? "muting" : "unmuting", i, curDevice, curOutput);
   2319                 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
   2320                 if (desc->strategyRefCount((routing_strategy)i) != 0) {
   2321                     if (tempMute) {
   2322                         setStrategyMute((routing_strategy)i, true, curOutput);
   2323                         setStrategyMute((routing_strategy)i, false, curOutput,
   2324                                             desc->latency() * 2, device);
   2325                     }
   2326                     if (tempMute || mute) {
   2327                         if (muteWaitMs < desc->latency()) {
   2328                             muteWaitMs = desc->latency();
   2329                         }
   2330                     }
   2331                 }
   2332             }
   2333         }
   2334     }
   2335 
   2336     // FIXME: should not need to double latency if volume could be applied immediately by the
   2337     // audioflinger mixer. We must account for the delay between now and the next time
   2338     // the audioflinger thread for this output will process a buffer (which corresponds to
   2339     // one buffer size, usually 1/2 or 1/4 of the latency).
   2340     muteWaitMs *= 2;
   2341     // wait for the PCM output buffers to empty before proceeding with the rest of the command
   2342     if (muteWaitMs > delayMs) {
   2343         muteWaitMs -= delayMs;
   2344         usleep(muteWaitMs * 1000);
   2345         return muteWaitMs;
   2346     }
   2347     return 0;
   2348 }
   2349 
   2350 uint32_t AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output,
   2351                                              audio_devices_t device,
   2352                                              bool force,
   2353                                              int delayMs)
   2354 {
   2355     ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
   2356     AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
   2357     AudioParameter param;
   2358     uint32_t muteWaitMs = 0;
   2359 
   2360     if (outputDesc->isDuplicated()) {
   2361         muteWaitMs = setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
   2362         muteWaitMs += setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
   2363         return muteWaitMs;
   2364     }
   2365     // filter devices according to output selected
   2366     device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices);
   2367 
   2368     audio_devices_t prevDevice = outputDesc->mDevice;
   2369 
   2370     ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
   2371 
   2372     if (device != AUDIO_DEVICE_NONE) {
   2373         outputDesc->mDevice = device;
   2374     }
   2375     muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
   2376 
   2377     // Do not change the routing if:
   2378     //  - the requested device is AUDIO_DEVICE_NONE
   2379     //  - the requested device is the same as current device and force is not specified.
   2380     // Doing this check here allows the caller to call setOutputDevice() without conditions
   2381     if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
   2382         ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
   2383         return muteWaitMs;
   2384     }
   2385 
   2386     ALOGV("setOutputDevice() changing device");
   2387     // do the routing
   2388     param.addInt(String8(AudioParameter::keyRouting), (int)device);
   2389     mpClientInterface->setParameters(output, param.toString(), delayMs);
   2390 
   2391     // update stream volumes according to new device
   2392     applyStreamVolumes(output, device, delayMs);
   2393 
   2394     return muteWaitMs;
   2395 }
   2396 
   2397 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getInputProfile(audio_devices_t device,
   2398                                                    uint32_t samplingRate,
   2399                                                    uint32_t format,
   2400                                                    uint32_t channelMask)
   2401 {
   2402     // Choose an input profile based on the requested capture parameters: select the first available
   2403     // profile supporting all requested parameters.
   2404 
   2405     for (size_t i = 0; i < mHwModules.size(); i++)
   2406     {
   2407         if (mHwModules[i]->mHandle == 0) {
   2408             continue;
   2409         }
   2410         for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
   2411         {
   2412             IOProfile *profile = mHwModules[i]->mInputProfiles[j];
   2413             if (profile->isCompatibleProfile(device, samplingRate, format,
   2414                                              channelMask,(audio_output_flags_t)0)) {
   2415                 return profile;
   2416             }
   2417         }
   2418     }
   2419     return NULL;
   2420 }
   2421 
   2422 audio_devices_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
   2423 {
   2424     uint32_t device = AUDIO_DEVICE_NONE;
   2425 
   2426     switch(inputSource) {
   2427     case AUDIO_SOURCE_DEFAULT:
   2428     case AUDIO_SOURCE_MIC:
   2429     case AUDIO_SOURCE_VOICE_RECOGNITION:
   2430     case AUDIO_SOURCE_VOICE_COMMUNICATION:
   2431         if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
   2432             mAvailableInputDevices & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
   2433             device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
   2434         } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_WIRED_HEADSET) {
   2435             device = AUDIO_DEVICE_IN_WIRED_HEADSET;
   2436         } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
   2437             device = AUDIO_DEVICE_IN_BUILTIN_MIC;
   2438         }
   2439         break;
   2440     case AUDIO_SOURCE_CAMCORDER:
   2441         if (mAvailableInputDevices & AUDIO_DEVICE_IN_BACK_MIC) {
   2442             device = AUDIO_DEVICE_IN_BACK_MIC;
   2443         } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
   2444             device = AUDIO_DEVICE_IN_BUILTIN_MIC;
   2445         }
   2446         break;
   2447     case AUDIO_SOURCE_VOICE_UPLINK:
   2448     case AUDIO_SOURCE_VOICE_DOWNLINK:
   2449     case AUDIO_SOURCE_VOICE_CALL:
   2450         if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) {
   2451             device = AUDIO_DEVICE_IN_VOICE_CALL;
   2452         }
   2453         break;
   2454     case AUDIO_SOURCE_REMOTE_SUBMIX:
   2455         if (mAvailableInputDevices & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
   2456             device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
   2457         }
   2458         break;
   2459     default:
   2460         ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
   2461         break;
   2462     }
   2463     ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
   2464     return device;
   2465 }
   2466 
   2467 bool AudioPolicyManagerBase::isVirtualInputDevice(audio_devices_t device)
   2468 {
   2469     if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
   2470         device &= ~AUDIO_DEVICE_BIT_IN;
   2471         if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
   2472             return true;
   2473     }
   2474     return false;
   2475 }
   2476 
   2477 audio_io_handle_t AudioPolicyManagerBase::getActiveInput(bool ignoreVirtualInputs)
   2478 {
   2479     for (size_t i = 0; i < mInputs.size(); i++) {
   2480         const AudioInputDescriptor * input_descriptor = mInputs.valueAt(i);
   2481         if ((input_descriptor->mRefCount > 0)
   2482                 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
   2483             return mInputs.keyAt(i);
   2484         }
   2485     }
   2486     return 0;
   2487 }
   2488 
   2489 
   2490 audio_devices_t AudioPolicyManagerBase::getDeviceForVolume(audio_devices_t device)
   2491 {
   2492     if (device == AUDIO_DEVICE_NONE) {
   2493         // this happens when forcing a route update and no track is active on an output.
   2494         // In this case the returned category is not important.
   2495         device =  AUDIO_DEVICE_OUT_SPEAKER;
   2496     } else if (AudioSystem::popCount(device) > 1) {
   2497         // Multiple device selection is either:
   2498         //  - speaker + one other device: give priority to speaker in this case.
   2499         //  - one A2DP device + another device: happens with duplicated output. In this case
   2500         // retain the device on the A2DP output as the other must not correspond to an active
   2501         // selection if not the speaker.
   2502         if (device & AUDIO_DEVICE_OUT_SPEAKER) {
   2503             device = AUDIO_DEVICE_OUT_SPEAKER;
   2504         } else {
   2505             device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
   2506         }
   2507     }
   2508 
   2509     ALOGW_IF(AudioSystem::popCount(device) != 1,
   2510             "getDeviceForVolume() invalid device combination: %08x",
   2511             device);
   2512 
   2513     return device;
   2514 }
   2515 
   2516 AudioPolicyManagerBase::device_category AudioPolicyManagerBase::getDeviceCategory(audio_devices_t device)
   2517 {
   2518     switch(getDeviceForVolume(device)) {
   2519         case AUDIO_DEVICE_OUT_EARPIECE:
   2520             return DEVICE_CATEGORY_EARPIECE;
   2521         case AUDIO_DEVICE_OUT_WIRED_HEADSET:
   2522         case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
   2523         case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
   2524         case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
   2525         case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
   2526         case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
   2527             return DEVICE_CATEGORY_HEADSET;
   2528         case AUDIO_DEVICE_OUT_SPEAKER:
   2529         case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
   2530         case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
   2531         case AUDIO_DEVICE_OUT_AUX_DIGITAL:
   2532         case AUDIO_DEVICE_OUT_USB_ACCESSORY:
   2533         case AUDIO_DEVICE_OUT_USB_DEVICE:
   2534         case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
   2535         default:
   2536             return DEVICE_CATEGORY_SPEAKER;
   2537     }
   2538 }
   2539 
   2540 float AudioPolicyManagerBase::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
   2541         int indexInUi)
   2542 {
   2543     device_category deviceCategory = getDeviceCategory(device);
   2544     const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
   2545 
   2546     // the volume index in the UI is relative to the min and max volume indices for this stream type
   2547     int nbSteps = 1 + curve[VOLMAX].mIndex -
   2548             curve[VOLMIN].mIndex;
   2549     int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
   2550             (streamDesc.mIndexMax - streamDesc.mIndexMin);
   2551 
   2552     // find what part of the curve this index volume belongs to, or if it's out of bounds
   2553     int segment = 0;
   2554     if (volIdx < curve[VOLMIN].mIndex) {         // out of bounds
   2555         return 0.0f;
   2556     } else if (volIdx < curve[VOLKNEE1].mIndex) {
   2557         segment = 0;
   2558     } else if (volIdx < curve[VOLKNEE2].mIndex) {
   2559         segment = 1;
   2560     } else if (volIdx <= curve[VOLMAX].mIndex) {
   2561         segment = 2;
   2562     } else {                                                               // out of bounds
   2563         return 1.0f;
   2564     }
   2565 
   2566     // linear interpolation in the attenuation table in dB
   2567     float decibels = curve[segment].mDBAttenuation +
   2568             ((float)(volIdx - curve[segment].mIndex)) *
   2569                 ( (curve[segment+1].mDBAttenuation -
   2570                         curve[segment].mDBAttenuation) /
   2571                     ((float)(curve[segment+1].mIndex -
   2572                             curve[segment].mIndex)) );
   2573 
   2574     float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
   2575 
   2576     ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
   2577             curve[segment].mIndex, volIdx,
   2578             curve[segment+1].mIndex,
   2579             curve[segment].mDBAttenuation,
   2580             decibels,
   2581             curve[segment+1].mDBAttenuation,
   2582             amplification);
   2583 
   2584     return amplification;
   2585 }
   2586 
   2587 const AudioPolicyManagerBase::VolumeCurvePoint
   2588     AudioPolicyManagerBase::sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
   2589     {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
   2590 };
   2591 
   2592 const AudioPolicyManagerBase::VolumeCurvePoint
   2593     AudioPolicyManagerBase::sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
   2594     {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
   2595 };
   2596 
   2597 const AudioPolicyManagerBase::VolumeCurvePoint
   2598     AudioPolicyManagerBase::sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
   2599     {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
   2600 };
   2601 
   2602 const AudioPolicyManagerBase::VolumeCurvePoint
   2603     AudioPolicyManagerBase::sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
   2604     {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
   2605 };
   2606 
   2607 // AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
   2608 // AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets (See AudioService.java).
   2609 // The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
   2610 const AudioPolicyManagerBase::VolumeCurvePoint
   2611     AudioPolicyManagerBase::sDefaultSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
   2612     {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
   2613 };
   2614 
   2615 const AudioPolicyManagerBase::VolumeCurvePoint
   2616     AudioPolicyManagerBase::sHeadsetSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
   2617     {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
   2618 };
   2619 
   2620 const AudioPolicyManagerBase::VolumeCurvePoint
   2621     AudioPolicyManagerBase::sDefaultVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
   2622     {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
   2623 };
   2624 
   2625 const AudioPolicyManagerBase::VolumeCurvePoint
   2626     AudioPolicyManagerBase::sSpeakerVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
   2627     {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
   2628 };
   2629 
   2630 const AudioPolicyManagerBase::VolumeCurvePoint
   2631             *AudioPolicyManagerBase::sVolumeProfiles[AUDIO_STREAM_CNT]
   2632                                                    [AudioPolicyManagerBase::DEVICE_CATEGORY_CNT] = {
   2633     { // AUDIO_STREAM_VOICE_CALL
   2634         sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
   2635         sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
   2636         sDefaultVoiceVolumeCurve  // DEVICE_CATEGORY_EARPIECE
   2637     },
   2638     { // AUDIO_STREAM_SYSTEM
   2639         sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
   2640         sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
   2641         sDefaultSystemVolumeCurve  // DEVICE_CATEGORY_EARPIECE
   2642     },
   2643     { // AUDIO_STREAM_RING
   2644         sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
   2645         sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
   2646         sDefaultVolumeCurve  // DEVICE_CATEGORY_EARPIECE
   2647     },
   2648     { // AUDIO_STREAM_MUSIC
   2649         sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
   2650         sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
   2651         sDefaultMediaVolumeCurve  // DEVICE_CATEGORY_EARPIECE
   2652     },
   2653     { // AUDIO_STREAM_ALARM
   2654         sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
   2655         sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
   2656         sDefaultVolumeCurve  // DEVICE_CATEGORY_EARPIECE
   2657     },
   2658     { // AUDIO_STREAM_NOTIFICATION
   2659         sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
   2660         sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
   2661         sDefaultVolumeCurve  // DEVICE_CATEGORY_EARPIECE
   2662     },
   2663     { // AUDIO_STREAM_BLUETOOTH_SCO
   2664         sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
   2665         sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
   2666         sDefaultVoiceVolumeCurve  // DEVICE_CATEGORY_EARPIECE
   2667     },
   2668     { // AUDIO_STREAM_ENFORCED_AUDIBLE
   2669         sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
   2670         sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
   2671         sDefaultSystemVolumeCurve  // DEVICE_CATEGORY_EARPIECE
   2672     },
   2673     {  // AUDIO_STREAM_DTMF
   2674         sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
   2675         sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
   2676         sDefaultSystemVolumeCurve  // DEVICE_CATEGORY_EARPIECE
   2677     },
   2678     { // AUDIO_STREAM_TTS
   2679         sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
   2680         sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
   2681         sDefaultMediaVolumeCurve  // DEVICE_CATEGORY_EARPIECE
   2682     },
   2683 };
   2684 
   2685 void AudioPolicyManagerBase::initializeVolumeCurves()
   2686 {
   2687     for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
   2688         for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
   2689             mStreams[i].mVolumeCurve[j] =
   2690                     sVolumeProfiles[i][j];
   2691         }
   2692     }
   2693 }
   2694 
   2695 float AudioPolicyManagerBase::computeVolume(int stream,
   2696                                             int index,
   2697                                             audio_io_handle_t output,
   2698                                             audio_devices_t device)
   2699 {
   2700     float volume = 1.0;
   2701     AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
   2702     StreamDescriptor &streamDesc = mStreams[stream];
   2703 
   2704     if (device == AUDIO_DEVICE_NONE) {
   2705         device = outputDesc->device();
   2706     }
   2707 
   2708     // if volume is not 0 (not muted), force media volume to max on digital output
   2709     if (stream == AudioSystem::MUSIC &&
   2710         index != mStreams[stream].mIndexMin &&
   2711         (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
   2712          device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET ||
   2713          device == AUDIO_DEVICE_OUT_USB_ACCESSORY ||
   2714          device == AUDIO_DEVICE_OUT_USB_DEVICE)) {
   2715         return 1.0;
   2716     }
   2717 
   2718     volume = volIndexToAmpl(device, streamDesc, index);
   2719 
   2720     // if a headset is connected, apply the following rules to ring tones and notifications
   2721     // to avoid sound level bursts in user's ears:
   2722     // - always attenuate ring tones and notifications volume by 6dB
   2723     // - if music is playing, always limit the volume to current music volume,
   2724     // with a minimum threshold at -36dB so that notification is always perceived.
   2725     const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
   2726     if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
   2727             AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
   2728             AUDIO_DEVICE_OUT_WIRED_HEADSET |
   2729             AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
   2730         ((stream_strategy == STRATEGY_SONIFICATION)
   2731                 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
   2732                 || (stream == AudioSystem::SYSTEM)
   2733                 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
   2734                     (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) &&
   2735         streamDesc.mCanBeMuted) {
   2736         volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
   2737         // when the phone is ringing we must consider that music could have been paused just before
   2738         // by the music application and behave as if music was active if the last music track was
   2739         // just stopped
   2740         if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
   2741                 mLimitRingtoneVolume) {
   2742             audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
   2743             float musicVol = computeVolume(AudioSystem::MUSIC,
   2744                                mStreams[AudioSystem::MUSIC].getVolumeIndex(musicDevice),
   2745                                output,
   2746                                musicDevice);
   2747             float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
   2748                                 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
   2749             if (volume > minVol) {
   2750                 volume = minVol;
   2751                 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
   2752             }
   2753         }
   2754     }
   2755 
   2756     return volume;
   2757 }
   2758 
   2759 status_t AudioPolicyManagerBase::checkAndSetVolume(int stream,
   2760                                                    int index,
   2761                                                    audio_io_handle_t output,
   2762                                                    audio_devices_t device,
   2763                                                    int delayMs,
   2764                                                    bool force)
   2765 {
   2766 
   2767     // do not change actual stream volume if the stream is muted
   2768     if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
   2769         ALOGVV("checkAndSetVolume() stream %d muted count %d",
   2770               stream, mOutputs.valueFor(output)->mMuteCount[stream]);
   2771         return NO_ERROR;
   2772     }
   2773 
   2774     // do not change in call volume if bluetooth is connected and vice versa
   2775     if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
   2776         (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
   2777         ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
   2778              stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
   2779         return INVALID_OPERATION;
   2780     }
   2781 
   2782     float volume = computeVolume(stream, index, output, device);
   2783     // We actually change the volume if:
   2784     // - the float value returned by computeVolume() changed
   2785     // - the force flag is set
   2786     if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
   2787             force) {
   2788         mOutputs.valueFor(output)->mCurVolume[stream] = volume;
   2789         ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
   2790         // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
   2791         // enabled
   2792         if (stream == AudioSystem::BLUETOOTH_SCO) {
   2793             mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs);
   2794         }
   2795         mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
   2796     }
   2797 
   2798     if (stream == AudioSystem::VOICE_CALL ||
   2799         stream == AudioSystem::BLUETOOTH_SCO) {
   2800         float voiceVolume;
   2801         // Force voice volume to max for bluetooth SCO as volume is managed by the headset
   2802         if (stream == AudioSystem::VOICE_CALL) {
   2803             voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
   2804         } else {
   2805             voiceVolume = 1.0;
   2806         }
   2807 
   2808         if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
   2809             mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
   2810             mLastVoiceVolume = voiceVolume;
   2811         }
   2812     }
   2813 
   2814     return NO_ERROR;
   2815 }
   2816 
   2817 void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output,
   2818                                                 audio_devices_t device,
   2819                                                 int delayMs,
   2820                                                 bool force)
   2821 {
   2822     ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
   2823 
   2824     for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
   2825         checkAndSetVolume(stream,
   2826                           mStreams[stream].getVolumeIndex(device),
   2827                           output,
   2828                           device,
   2829                           delayMs,
   2830                           force);
   2831     }
   2832 }
   2833 
   2834 void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy,
   2835                                              bool on,
   2836                                              audio_io_handle_t output,
   2837                                              int delayMs,
   2838                                              audio_devices_t device)
   2839 {
   2840     ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
   2841     for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
   2842         if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
   2843             setStreamMute(stream, on, output, delayMs, device);
   2844         }
   2845     }
   2846 }
   2847 
   2848 void AudioPolicyManagerBase::setStreamMute(int stream,
   2849                                            bool on,
   2850                                            audio_io_handle_t output,
   2851                                            int delayMs,
   2852                                            audio_devices_t device)
   2853 {
   2854     StreamDescriptor &streamDesc = mStreams[stream];
   2855     AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
   2856     if (device == AUDIO_DEVICE_NONE) {
   2857         device = outputDesc->device();
   2858     }
   2859 
   2860     ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
   2861           stream, on, output, outputDesc->mMuteCount[stream], device);
   2862 
   2863     if (on) {
   2864         if (outputDesc->mMuteCount[stream] == 0) {
   2865             if (streamDesc.mCanBeMuted &&
   2866                     ((stream != AudioSystem::ENFORCED_AUDIBLE) ||
   2867                      (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) {
   2868                 checkAndSetVolume(stream, 0, output, device, delayMs);
   2869             }
   2870         }
   2871         // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
   2872         outputDesc->mMuteCount[stream]++;
   2873     } else {
   2874         if (outputDesc->mMuteCount[stream] == 0) {
   2875             ALOGV("setStreamMute() unmuting non muted stream!");
   2876             return;
   2877         }
   2878         if (--outputDesc->mMuteCount[stream] == 0) {
   2879             checkAndSetVolume(stream,
   2880                               streamDesc.getVolumeIndex(device),
   2881                               output,
   2882                               device,
   2883                               delayMs);
   2884         }
   2885     }
   2886 }
   2887 
   2888 void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
   2889 {
   2890     // if the stream pertains to sonification strategy and we are in call we must
   2891     // mute the stream if it is low visibility. If it is high visibility, we must play a tone
   2892     // in the device used for phone strategy and play the tone if the selected device does not
   2893     // interfere with the device used for phone strategy
   2894     // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
   2895     // many times as there are active tracks on the output
   2896     const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
   2897     if ((stream_strategy == STRATEGY_SONIFICATION) ||
   2898             ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
   2899         AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
   2900         ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
   2901                 stream, starting, outputDesc->mDevice, stateChange);
   2902         if (outputDesc->mRefCount[stream]) {
   2903             int muteCount = 1;
   2904             if (stateChange) {
   2905                 muteCount = outputDesc->mRefCount[stream];
   2906             }
   2907             if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
   2908                 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
   2909                 for (int i = 0; i < muteCount; i++) {
   2910                     setStreamMute(stream, starting, mPrimaryOutput);
   2911                 }
   2912             } else {
   2913                 ALOGV("handleIncallSonification() high visibility");
   2914                 if (outputDesc->device() &
   2915                         getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
   2916                     ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
   2917                     for (int i = 0; i < muteCount; i++) {
   2918                         setStreamMute(stream, starting, mPrimaryOutput);
   2919                     }
   2920                 }
   2921                 if (starting) {
   2922                     mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
   2923                 } else {
   2924                     mpClientInterface->stopTone();
   2925                 }
   2926             }
   2927         }
   2928     }
   2929 }
   2930 
   2931 bool AudioPolicyManagerBase::isInCall()
   2932 {
   2933     return isStateInCall(mPhoneState);
   2934 }
   2935 
   2936 bool AudioPolicyManagerBase::isStateInCall(int state) {
   2937     return ((state == AudioSystem::MODE_IN_CALL) ||
   2938             (state == AudioSystem::MODE_IN_COMMUNICATION));
   2939 }
   2940 
   2941 bool AudioPolicyManagerBase::needsDirectOuput(audio_stream_type_t stream,
   2942                                               uint32_t samplingRate,
   2943                                               audio_format_t format,
   2944                                               audio_channel_mask_t channelMask,
   2945                                               audio_output_flags_t flags,
   2946                                               audio_devices_t device)
   2947 {
   2948    return ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
   2949           (format != 0 && !AudioSystem::isLinearPCM(format)));
   2950 }
   2951 
   2952 uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
   2953 {
   2954     return MAX_EFFECTS_CPU_LOAD;
   2955 }
   2956 
   2957 uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
   2958 {
   2959     return MAX_EFFECTS_MEMORY;
   2960 }
   2961 
   2962 // --- AudioOutputDescriptor class implementation
   2963 
   2964 AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor(
   2965         const IOProfile *profile)
   2966     : mId(0), mSamplingRate(0), mFormat((audio_format_t)0),
   2967       mChannelMask((audio_channel_mask_t)0), mLatency(0),
   2968     mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE),
   2969     mOutput1(0), mOutput2(0), mProfile(profile)
   2970 {
   2971     // clear usage count for all stream types
   2972     for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
   2973         mRefCount[i] = 0;
   2974         mCurVolume[i] = -1.0;
   2975         mMuteCount[i] = 0;
   2976         mStopTime[i] = 0;
   2977     }
   2978     for (int i = 0; i < NUM_STRATEGIES; i++) {
   2979         mStrategyMutedByDevice[i] = false;
   2980     }
   2981     if (profile != NULL) {
   2982         mSamplingRate = profile->mSamplingRates[0];
   2983         mFormat = profile->mFormats[0];
   2984         mChannelMask = profile->mChannelMasks[0];
   2985         mFlags = profile->mFlags;
   2986     }
   2987 }
   2988 
   2989 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::device()
   2990 {
   2991     if (isDuplicated()) {
   2992         return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
   2993     } else {
   2994         return mDevice;
   2995     }
   2996 }
   2997 
   2998 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::latency()
   2999 {
   3000     if (isDuplicated()) {
   3001         return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
   3002     } else {
   3003         return mLatency;
   3004     }
   3005 }
   3006 
   3007 bool AudioPolicyManagerBase::AudioOutputDescriptor::sharesHwModuleWith(
   3008         const AudioOutputDescriptor *outputDesc)
   3009 {
   3010     if (isDuplicated()) {
   3011         return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
   3012     } else if (outputDesc->isDuplicated()){
   3013         return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
   3014     } else {
   3015         return (mProfile->mModule == outputDesc->mProfile->mModule);
   3016     }
   3017 }
   3018 
   3019 void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
   3020 {
   3021     // forward usage count change to attached outputs
   3022     if (isDuplicated()) {
   3023         mOutput1->changeRefCount(stream, delta);
   3024         mOutput2->changeRefCount(stream, delta);
   3025     }
   3026     if ((delta + (int)mRefCount[stream]) < 0) {
   3027         ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
   3028         mRefCount[stream] = 0;
   3029         return;
   3030     }
   3031     mRefCount[stream] += delta;
   3032     ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
   3033 }
   3034 
   3035 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::refCount()
   3036 {
   3037     uint32_t refcount = 0;
   3038     for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
   3039         refcount += mRefCount[i];
   3040     }
   3041     return refcount;
   3042 }
   3043 
   3044 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::strategyRefCount(routing_strategy strategy)
   3045 {
   3046     uint32_t refCount = 0;
   3047     for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
   3048         if (getStrategy((AudioSystem::stream_type)i) == strategy) {
   3049             refCount += mRefCount[i];
   3050         }
   3051     }
   3052     return refCount;
   3053 }
   3054 
   3055 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::supportedDevices()
   3056 {
   3057     if (isDuplicated()) {
   3058         return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
   3059     } else {
   3060         return mProfile->mSupportedDevices ;
   3061     }
   3062 }
   3063 
   3064 status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
   3065 {
   3066     const size_t SIZE = 256;
   3067     char buffer[SIZE];
   3068     String8 result;
   3069 
   3070     snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
   3071     result.append(buffer);
   3072     snprintf(buffer, SIZE, " Format: %d\n", mFormat);
   3073     result.append(buffer);
   3074     snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
   3075     result.append(buffer);
   3076     snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
   3077     result.append(buffer);
   3078     snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
   3079     result.append(buffer);
   3080     snprintf(buffer, SIZE, " Devices %08x\n", device());
   3081     result.append(buffer);
   3082     snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
   3083     result.append(buffer);
   3084     for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
   3085         snprintf(buffer, SIZE, " %02d     %.03f     %02d       %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
   3086         result.append(buffer);
   3087     }
   3088     write(fd, result.string(), result.size());
   3089 
   3090     return NO_ERROR;
   3091 }
   3092 
   3093 // --- AudioInputDescriptor class implementation
   3094 
   3095 AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor(const IOProfile *profile)
   3096     : mSamplingRate(0), mFormat((audio_format_t)0), mChannelMask((audio_channel_mask_t)0),
   3097       mDevice(AUDIO_DEVICE_NONE), mRefCount(0),
   3098       mInputSource(0), mProfile(profile)
   3099 {
   3100 }
   3101 
   3102 status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
   3103 {
   3104     const size_t SIZE = 256;
   3105     char buffer[SIZE];
   3106     String8 result;
   3107 
   3108     snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
   3109     result.append(buffer);
   3110     snprintf(buffer, SIZE, " Format: %d\n", mFormat);
   3111     result.append(buffer);
   3112     snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
   3113     result.append(buffer);
   3114     snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
   3115     result.append(buffer);
   3116     snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
   3117     result.append(buffer);
   3118     write(fd, result.string(), result.size());
   3119 
   3120     return NO_ERROR;
   3121 }
   3122 
   3123 // --- StreamDescriptor class implementation
   3124 
   3125 AudioPolicyManagerBase::StreamDescriptor::StreamDescriptor()
   3126     :   mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
   3127 {
   3128     mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
   3129 }
   3130 
   3131 int AudioPolicyManagerBase::StreamDescriptor::getVolumeIndex(audio_devices_t device)
   3132 {
   3133     device = AudioPolicyManagerBase::getDeviceForVolume(device);
   3134     // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
   3135     if (mIndexCur.indexOfKey(device) < 0) {
   3136         device = AUDIO_DEVICE_OUT_DEFAULT;
   3137     }
   3138     return mIndexCur.valueFor(device);
   3139 }
   3140 
   3141 void AudioPolicyManagerBase::StreamDescriptor::dump(int fd)
   3142 {
   3143     const size_t SIZE = 256;
   3144     char buffer[SIZE];
   3145     String8 result;
   3146 
   3147     snprintf(buffer, SIZE, "%s         %02d         %02d         ",
   3148              mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
   3149     result.append(buffer);
   3150     for (size_t i = 0; i < mIndexCur.size(); i++) {
   3151         snprintf(buffer, SIZE, "%04x : %02d, ",
   3152                  mIndexCur.keyAt(i),
   3153                  mIndexCur.valueAt(i));
   3154         result.append(buffer);
   3155     }
   3156     result.append("\n");
   3157 
   3158     write(fd, result.string(), result.size());
   3159 }
   3160 
   3161 // --- EffectDescriptor class implementation
   3162 
   3163 status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
   3164 {
   3165     const size_t SIZE = 256;
   3166     char buffer[SIZE];
   3167     String8 result;
   3168 
   3169     snprintf(buffer, SIZE, " I/O: %d\n", mIo);
   3170     result.append(buffer);
   3171     snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
   3172     result.append(buffer);
   3173     snprintf(buffer, SIZE, " Session: %d\n", mSession);
   3174     result.append(buffer);
   3175     snprintf(buffer, SIZE, " Name: %s\n",  mDesc.name);
   3176     result.append(buffer);
   3177     snprintf(buffer, SIZE, " %s\n",  mEnabled ? "Enabled" : "Disabled");
   3178     result.append(buffer);
   3179     write(fd, result.string(), result.size());
   3180 
   3181     return NO_ERROR;
   3182 }
   3183 
   3184 // --- IOProfile class implementation
   3185 
   3186 AudioPolicyManagerBase::HwModule::HwModule(const char *name)
   3187     : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0)
   3188 {
   3189 }
   3190 
   3191 AudioPolicyManagerBase::HwModule::~HwModule()
   3192 {
   3193     for (size_t i = 0; i < mOutputProfiles.size(); i++) {
   3194          delete mOutputProfiles[i];
   3195     }
   3196     for (size_t i = 0; i < mInputProfiles.size(); i++) {
   3197          delete mInputProfiles[i];
   3198     }
   3199     free((void *)mName);
   3200 }
   3201 
   3202 void AudioPolicyManagerBase::HwModule::dump(int fd)
   3203 {
   3204     const size_t SIZE = 256;
   3205     char buffer[SIZE];
   3206     String8 result;
   3207 
   3208     snprintf(buffer, SIZE, "  - name: %s\n", mName);
   3209     result.append(buffer);
   3210     snprintf(buffer, SIZE, "  - handle: %d\n", mHandle);
   3211     result.append(buffer);
   3212     write(fd, result.string(), result.size());
   3213     if (mOutputProfiles.size()) {
   3214         write(fd, "  - outputs:\n", sizeof("  - outputs:\n"));
   3215         for (size_t i = 0; i < mOutputProfiles.size(); i++) {
   3216             snprintf(buffer, SIZE, "    output %d:\n", i);
   3217             write(fd, buffer, strlen(buffer));
   3218             mOutputProfiles[i]->dump(fd);
   3219         }
   3220     }
   3221     if (mInputProfiles.size()) {
   3222         write(fd, "  - inputs:\n", sizeof("  - inputs:\n"));
   3223         for (size_t i = 0; i < mInputProfiles.size(); i++) {
   3224             snprintf(buffer, SIZE, "    input %d:\n", i);
   3225             write(fd, buffer, strlen(buffer));
   3226             mInputProfiles[i]->dump(fd);
   3227         }
   3228     }
   3229 }
   3230 
   3231 AudioPolicyManagerBase::IOProfile::IOProfile(HwModule *module)
   3232     : mFlags((audio_output_flags_t)0), mModule(module)
   3233 {
   3234 }
   3235 
   3236 AudioPolicyManagerBase::IOProfile::~IOProfile()
   3237 {
   3238 }
   3239 
   3240 // checks if the IO profile is compatible with specified parameters. By convention a value of 0
   3241 // means a parameter is don't care
   3242 bool AudioPolicyManagerBase::IOProfile::isCompatibleProfile(audio_devices_t device,
   3243                                                             uint32_t samplingRate,
   3244                                                             uint32_t format,
   3245                                                             uint32_t channelMask,
   3246                                                             audio_output_flags_t flags) const
   3247 {
   3248     if ((mSupportedDevices & device) != device) {
   3249         return false;
   3250     }
   3251     if ((mFlags & flags) != flags) {
   3252         return false;
   3253     }
   3254     if (samplingRate != 0) {
   3255         size_t i;
   3256         for (i = 0; i < mSamplingRates.size(); i++)
   3257         {
   3258             if (mSamplingRates[i] == samplingRate) {
   3259                 break;
   3260             }
   3261         }
   3262         if (i == mSamplingRates.size()) {
   3263             return false;
   3264         }
   3265     }
   3266     if (format != 0) {
   3267         size_t i;
   3268         for (i = 0; i < mFormats.size(); i++)
   3269         {
   3270             if (mFormats[i] == format) {
   3271                 break;
   3272             }
   3273         }
   3274         if (i == mFormats.size()) {
   3275             return false;
   3276         }
   3277     }
   3278     if (channelMask != 0) {
   3279         size_t i;
   3280         for (i = 0; i < mChannelMasks.size(); i++)
   3281         {
   3282             if (mChannelMasks[i] == channelMask) {
   3283                 break;
   3284             }
   3285         }
   3286         if (i == mChannelMasks.size()) {
   3287             return false;
   3288         }
   3289     }
   3290     return true;
   3291 }
   3292 
   3293 void AudioPolicyManagerBase::IOProfile::dump(int fd)
   3294 {
   3295     const size_t SIZE = 256;
   3296     char buffer[SIZE];
   3297     String8 result;
   3298 
   3299     snprintf(buffer, SIZE, "    - sampling rates: ");
   3300     result.append(buffer);
   3301     for (size_t i = 0; i < mSamplingRates.size(); i++) {
   3302         snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
   3303         result.append(buffer);
   3304         result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", ");
   3305     }
   3306 
   3307     snprintf(buffer, SIZE, "    - channel masks: ");
   3308     result.append(buffer);
   3309     for (size_t i = 0; i < mChannelMasks.size(); i++) {
   3310         snprintf(buffer, SIZE, "%04x", mChannelMasks[i]);
   3311         result.append(buffer);
   3312         result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", ");
   3313     }
   3314 
   3315     snprintf(buffer, SIZE, "    - formats: ");
   3316     result.append(buffer);
   3317     for (size_t i = 0; i < mFormats.size(); i++) {
   3318         snprintf(buffer, SIZE, "%d", mFormats[i]);
   3319         result.append(buffer);
   3320         result.append(i == (mFormats.size() - 1) ? "\n" : ", ");
   3321     }
   3322 
   3323     snprintf(buffer, SIZE, "    - devices: %04x\n", mSupportedDevices);
   3324     result.append(buffer);
   3325     snprintf(buffer, SIZE, "    - flags: %04x\n", mFlags);
   3326     result.append(buffer);
   3327 
   3328     write(fd, result.string(), result.size());
   3329 }
   3330 
   3331 // --- audio_policy.conf file parsing
   3332 
   3333 struct StringToEnum {
   3334     const char *name;
   3335     uint32_t value;
   3336 };
   3337 
   3338 #define STRING_TO_ENUM(string) { #string, string }
   3339 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
   3340 
   3341 const struct StringToEnum sDeviceNameToEnumTable[] = {
   3342     STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
   3343     STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
   3344     STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
   3345     STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
   3346     STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
   3347     STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
   3348     STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
   3349     STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
   3350     STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
   3351     STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
   3352     STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
   3353     STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
   3354     STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
   3355     STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
   3356     STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
   3357     STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
   3358     STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
   3359     STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
   3360     STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
   3361     STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
   3362     STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
   3363     STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
   3364     STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
   3365 };
   3366 
   3367 const struct StringToEnum sFlagNameToEnumTable[] = {
   3368     STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
   3369     STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
   3370     STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
   3371     STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
   3372 };
   3373 
   3374 const struct StringToEnum sFormatNameToEnumTable[] = {
   3375     STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
   3376     STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
   3377     STRING_TO_ENUM(AUDIO_FORMAT_MP3),
   3378     STRING_TO_ENUM(AUDIO_FORMAT_AAC),
   3379     STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
   3380 };
   3381 
   3382 const struct StringToEnum sOutChannelsNameToEnumTable[] = {
   3383     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
   3384     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
   3385     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
   3386     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
   3387 };
   3388 
   3389 const struct StringToEnum sInChannelsNameToEnumTable[] = {
   3390     STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
   3391     STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
   3392 };
   3393 
   3394 
   3395 uint32_t AudioPolicyManagerBase::stringToEnum(const struct StringToEnum *table,
   3396                                               size_t size,
   3397                                               const char *name)
   3398 {
   3399     for (size_t i = 0; i < size; i++) {
   3400         if (strcmp(table[i].name, name) == 0) {
   3401             ALOGV("stringToEnum() found %s", table[i].name);
   3402             return table[i].value;
   3403         }
   3404     }
   3405     return 0;
   3406 }
   3407 
   3408 audio_output_flags_t AudioPolicyManagerBase::parseFlagNames(char *name)
   3409 {
   3410     uint32_t flag = 0;
   3411 
   3412     // it is OK to cast name to non const here as we are not going to use it after
   3413     // strtok() modifies it
   3414     char *flagName = strtok(name, "|");
   3415     while (flagName != NULL) {
   3416         if (strlen(flagName) != 0) {
   3417             flag |= stringToEnum(sFlagNameToEnumTable,
   3418                                ARRAY_SIZE(sFlagNameToEnumTable),
   3419                                flagName);
   3420         }
   3421         flagName = strtok(NULL, "|");
   3422     }
   3423     return (audio_output_flags_t)flag;
   3424 }
   3425 
   3426 audio_devices_t AudioPolicyManagerBase::parseDeviceNames(char *name)
   3427 {
   3428     uint32_t device = 0;
   3429 
   3430     char *devName = strtok(name, "|");
   3431     while (devName != NULL) {
   3432         if (strlen(devName) != 0) {
   3433             device |= stringToEnum(sDeviceNameToEnumTable,
   3434                                  ARRAY_SIZE(sDeviceNameToEnumTable),
   3435                                  devName);
   3436         }
   3437         devName = strtok(NULL, "|");
   3438     }
   3439     return device;
   3440 }
   3441 
   3442 void AudioPolicyManagerBase::loadSamplingRates(char *name, IOProfile *profile)
   3443 {
   3444     char *str = strtok(name, "|");
   3445 
   3446     // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
   3447     // rates should be read from the output stream after it is opened for the first time
   3448     if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
   3449         profile->mSamplingRates.add(0);
   3450         return;
   3451     }
   3452 
   3453     while (str != NULL) {
   3454         uint32_t rate = atoi(str);
   3455         if (rate != 0) {
   3456             ALOGV("loadSamplingRates() adding rate %d", rate);
   3457             profile->mSamplingRates.add(rate);
   3458         }
   3459         str = strtok(NULL, "|");
   3460     }
   3461     return;
   3462 }
   3463 
   3464 void AudioPolicyManagerBase::loadFormats(char *name, IOProfile *profile)
   3465 {
   3466     char *str = strtok(name, "|");
   3467 
   3468     // by convention, "0' in the first entry in mFormats indicates the supported formats
   3469     // should be read from the output stream after it is opened for the first time
   3470     if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
   3471         profile->mFormats.add((audio_format_t)0);
   3472         return;
   3473     }
   3474 
   3475     while (str != NULL) {
   3476         audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
   3477                                                              ARRAY_SIZE(sFormatNameToEnumTable),
   3478                                                              str);
   3479         if (format != 0) {
   3480             profile->mFormats.add(format);
   3481         }
   3482         str = strtok(NULL, "|");
   3483     }
   3484     return;
   3485 }
   3486 
   3487 void AudioPolicyManagerBase::loadInChannels(char *name, IOProfile *profile)
   3488 {
   3489     const char *str = strtok(name, "|");
   3490 
   3491     ALOGV("loadInChannels() %s", name);
   3492 
   3493     if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
   3494         profile->mChannelMasks.add((audio_channel_mask_t)0);
   3495         return;
   3496     }
   3497 
   3498     while (str != NULL) {
   3499         audio_channel_mask_t channelMask =
   3500                 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
   3501                                                    ARRAY_SIZE(sInChannelsNameToEnumTable),
   3502                                                    str);
   3503         if (channelMask != 0) {
   3504             ALOGV("loadInChannels() adding channelMask %04x", channelMask);
   3505             profile->mChannelMasks.add(channelMask);
   3506         }
   3507         str = strtok(NULL, "|");
   3508     }
   3509     return;
   3510 }
   3511 
   3512 void AudioPolicyManagerBase::loadOutChannels(char *name, IOProfile *profile)
   3513 {
   3514     const char *str = strtok(name, "|");
   3515 
   3516     ALOGV("loadOutChannels() %s", name);
   3517 
   3518     // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
   3519     // masks should be read from the output stream after it is opened for the first time
   3520     if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
   3521         profile->mChannelMasks.add((audio_channel_mask_t)0);
   3522         return;
   3523     }
   3524 
   3525     while (str != NULL) {
   3526         audio_channel_mask_t channelMask =
   3527                 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
   3528                                                    ARRAY_SIZE(sOutChannelsNameToEnumTable),
   3529                                                    str);
   3530         if (channelMask != 0) {
   3531             profile->mChannelMasks.add(channelMask);
   3532         }
   3533         str = strtok(NULL, "|");
   3534     }
   3535     return;
   3536 }
   3537 
   3538 status_t AudioPolicyManagerBase::loadInput(cnode *root, HwModule *module)
   3539 {
   3540     cnode *node = root->first_child;
   3541 
   3542     IOProfile *profile = new IOProfile(module);
   3543 
   3544     while (node) {
   3545         if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
   3546             loadSamplingRates((char *)node->value, profile);
   3547         } else if (strcmp(node->name, FORMATS_TAG) == 0) {
   3548             loadFormats((char *)node->value, profile);
   3549         } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
   3550             loadInChannels((char *)node->value, profile);
   3551         } else if (strcmp(node->name, DEVICES_TAG) == 0) {
   3552             profile->mSupportedDevices = parseDeviceNames((char *)node->value);
   3553         }
   3554         node = node->next;
   3555     }
   3556     ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE,
   3557             "loadInput() invalid supported devices");
   3558     ALOGW_IF(profile->mChannelMasks.size() == 0,
   3559             "loadInput() invalid supported channel masks");
   3560     ALOGW_IF(profile->mSamplingRates.size() == 0,
   3561             "loadInput() invalid supported sampling rates");
   3562     ALOGW_IF(profile->mFormats.size() == 0,
   3563             "loadInput() invalid supported formats");
   3564     if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) &&
   3565             (profile->mChannelMasks.size() != 0) &&
   3566             (profile->mSamplingRates.size() != 0) &&
   3567             (profile->mFormats.size() != 0)) {
   3568 
   3569         ALOGV("loadInput() adding input mSupportedDevices %04x", profile->mSupportedDevices);
   3570 
   3571         module->mInputProfiles.add(profile);
   3572         return NO_ERROR;
   3573     } else {
   3574         delete profile;
   3575         return BAD_VALUE;
   3576     }
   3577 }
   3578 
   3579 status_t AudioPolicyManagerBase::loadOutput(cnode *root, HwModule *module)
   3580 {
   3581     cnode *node = root->first_child;
   3582 
   3583     IOProfile *profile = new IOProfile(module);
   3584 
   3585     while (node) {
   3586         if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
   3587             loadSamplingRates((char *)node->value, profile);
   3588         } else if (strcmp(node->name, FORMATS_TAG) == 0) {
   3589             loadFormats((char *)node->value, profile);
   3590         } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
   3591             loadOutChannels((char *)node->value, profile);
   3592         } else if (strcmp(node->name, DEVICES_TAG) == 0) {
   3593             profile->mSupportedDevices = parseDeviceNames((char *)node->value);
   3594         } else if (strcmp(node->name, FLAGS_TAG) == 0) {
   3595             profile->mFlags = parseFlagNames((char *)node->value);
   3596         }
   3597         node = node->next;
   3598     }
   3599     ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE,
   3600             "loadOutput() invalid supported devices");
   3601     ALOGW_IF(profile->mChannelMasks.size() == 0,
   3602             "loadOutput() invalid supported channel masks");
   3603     ALOGW_IF(profile->mSamplingRates.size() == 0,
   3604             "loadOutput() invalid supported sampling rates");
   3605     ALOGW_IF(profile->mFormats.size() == 0,
   3606             "loadOutput() invalid supported formats");
   3607     if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) &&
   3608             (profile->mChannelMasks.size() != 0) &&
   3609             (profile->mSamplingRates.size() != 0) &&
   3610             (profile->mFormats.size() != 0)) {
   3611 
   3612         ALOGV("loadOutput() adding output mSupportedDevices %04x, mFlags %04x",
   3613               profile->mSupportedDevices, profile->mFlags);
   3614 
   3615         module->mOutputProfiles.add(profile);
   3616         return NO_ERROR;
   3617     } else {
   3618         delete profile;
   3619         return BAD_VALUE;
   3620     }
   3621 }
   3622 
   3623 void AudioPolicyManagerBase::loadHwModule(cnode *root)
   3624 {
   3625     cnode *node = config_find(root, OUTPUTS_TAG);
   3626     status_t status = NAME_NOT_FOUND;
   3627 
   3628     HwModule *module = new HwModule(root->name);
   3629 
   3630     if (node != NULL) {
   3631         if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_A2DP) == 0) {
   3632             mHasA2dp = true;
   3633         } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_USB) == 0) {
   3634             mHasUsb = true;
   3635         } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX) == 0) {
   3636             mHasRemoteSubmix = true;
   3637         }
   3638 
   3639         node = node->first_child;
   3640         while (node) {
   3641             ALOGV("loadHwModule() loading output %s", node->name);
   3642             status_t tmpStatus = loadOutput(node, module);
   3643             if (status == NAME_NOT_FOUND || status == NO_ERROR) {
   3644                 status = tmpStatus;
   3645             }
   3646             node = node->next;
   3647         }
   3648     }
   3649     node = config_find(root, INPUTS_TAG);
   3650     if (node != NULL) {
   3651         node = node->first_child;
   3652         while (node) {
   3653             ALOGV("loadHwModule() loading input %s", node->name);
   3654             status_t tmpStatus = loadInput(node, module);
   3655             if (status == NAME_NOT_FOUND || status == NO_ERROR) {
   3656                 status = tmpStatus;
   3657             }
   3658             node = node->next;
   3659         }
   3660     }
   3661     if (status == NO_ERROR) {
   3662         mHwModules.add(module);
   3663     } else {
   3664         delete module;
   3665     }
   3666 }
   3667 
   3668 void AudioPolicyManagerBase::loadHwModules(cnode *root)
   3669 {
   3670     cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
   3671     if (node == NULL) {
   3672         return;
   3673     }
   3674 
   3675     node = node->first_child;
   3676     while (node) {
   3677         ALOGV("loadHwModules() loading module %s", node->name);
   3678         loadHwModule(node);
   3679         node = node->next;
   3680     }
   3681 }
   3682 
   3683 void AudioPolicyManagerBase::loadGlobalConfig(cnode *root)
   3684 {
   3685     cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
   3686     if (node == NULL) {
   3687         return;
   3688     }
   3689     node = node->first_child;
   3690     while (node) {
   3691         if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
   3692             mAttachedOutputDevices = parseDeviceNames((char *)node->value);
   3693             ALOGW_IF(mAttachedOutputDevices == AUDIO_DEVICE_NONE,
   3694                     "loadGlobalConfig() no attached output devices");
   3695             ALOGV("loadGlobalConfig() mAttachedOutputDevices %04x", mAttachedOutputDevices);
   3696         } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
   3697             mDefaultOutputDevice = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
   3698                                               ARRAY_SIZE(sDeviceNameToEnumTable),
   3699                                               (char *)node->value);
   3700             ALOGW_IF(mDefaultOutputDevice == AUDIO_DEVICE_NONE,
   3701                     "loadGlobalConfig() default device not specified");
   3702             ALOGV("loadGlobalConfig() mDefaultOutputDevice %04x", mDefaultOutputDevice);
   3703         } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
   3704             mAvailableInputDevices = parseDeviceNames((char *)node->value) & ~AUDIO_DEVICE_BIT_IN;
   3705             ALOGV("loadGlobalConfig() mAvailableInputDevices %04x", mAvailableInputDevices);
   3706         }
   3707         node = node->next;
   3708     }
   3709 }
   3710 
   3711 status_t AudioPolicyManagerBase::loadAudioPolicyConfig(const char *path)
   3712 {
   3713     cnode *root;
   3714     char *data;
   3715 
   3716     data = (char *)load_file(path, NULL);
   3717     if (data == NULL) {
   3718         return -ENODEV;
   3719     }
   3720     root = config_node("", "");
   3721     config_load(root, data);
   3722 
   3723     loadGlobalConfig(root);
   3724     loadHwModules(root);
   3725 
   3726     config_free(root);
   3727     free(root);
   3728     free(data);
   3729 
   3730     ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
   3731 
   3732     return NO_ERROR;
   3733 }
   3734 
   3735 void AudioPolicyManagerBase::defaultAudioPolicyConfig(void)
   3736 {
   3737     HwModule *module;
   3738     IOProfile *profile;
   3739 
   3740     mDefaultOutputDevice = AUDIO_DEVICE_OUT_SPEAKER;
   3741     mAttachedOutputDevices = AUDIO_DEVICE_OUT_SPEAKER;
   3742     mAvailableInputDevices = AUDIO_DEVICE_IN_BUILTIN_MIC & ~AUDIO_DEVICE_BIT_IN;
   3743 
   3744     module = new HwModule("primary");
   3745 
   3746     profile = new IOProfile(module);
   3747     profile->mSamplingRates.add(44100);
   3748     profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
   3749     profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
   3750     profile->mSupportedDevices = AUDIO_DEVICE_OUT_SPEAKER;
   3751     profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
   3752     module->mOutputProfiles.add(profile);
   3753 
   3754     profile = new IOProfile(module);
   3755     profile->mSamplingRates.add(8000);
   3756     profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
   3757     profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
   3758     profile->mSupportedDevices = AUDIO_DEVICE_IN_BUILTIN_MIC;
   3759     module->mInputProfiles.add(profile);
   3760 
   3761     mHwModules.add(module);
   3762 }
   3763 
   3764 }; // namespace android
   3765