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