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