Home | History | Annotate | Download | only in managerdefault
      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 "APM_AudioPolicyManager"
     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 #define AUDIO_POLICY_XML_CONFIG_FILE "/system/etc/audio_policy_configuration.xml"
     28 
     29 #include <inttypes.h>
     30 #include <math.h>
     31 
     32 #include <AudioPolicyManagerInterface.h>
     33 #include <AudioPolicyEngineInstance.h>
     34 #include <cutils/properties.h>
     35 #include <utils/Log.h>
     36 #include <hardware/audio.h>
     37 #include <hardware/audio_effect.h>
     38 #include <media/AudioParameter.h>
     39 #include <media/AudioPolicyHelper.h>
     40 #include <soundtrigger/SoundTrigger.h>
     41 #include "AudioPolicyManager.h"
     42 #ifndef USE_XML_AUDIO_POLICY_CONF
     43 #include <ConfigParsingUtils.h>
     44 #include <StreamDescriptor.h>
     45 #endif
     46 #include <Serializer.h>
     47 #include "TypeConverter.h"
     48 #include <policy.h>
     49 
     50 namespace android {
     51 
     52 // ----------------------------------------------------------------------------
     53 // AudioPolicyInterface implementation
     54 // ----------------------------------------------------------------------------
     55 
     56 status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
     57                                                       audio_policy_dev_state_t state,
     58                                                       const char *device_address,
     59                                                       const char *device_name)
     60 {
     61     return setDeviceConnectionStateInt(device, state, device_address, device_name);
     62 }
     63 
     64 status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
     65                                                          audio_policy_dev_state_t state,
     66                                                          const char *device_address,
     67                                                          const char *device_name)
     68 {
     69     ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
     70 -            device, state, device_address, device_name);
     71 
     72     // connect/disconnect only 1 device at a time
     73     if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
     74 
     75     sp<DeviceDescriptor> devDesc =
     76             mHwModules.getDeviceDescriptor(device, device_address, device_name);
     77 
     78     // handle output devices
     79     if (audio_is_output_device(device)) {
     80         SortedVector <audio_io_handle_t> outputs;
     81 
     82         ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
     83 
     84         // save a copy of the opened output descriptors before any output is opened or closed
     85         // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
     86         mPreviousOutputs = mOutputs;
     87         switch (state)
     88         {
     89         // handle output device connection
     90         case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
     91             if (index >= 0) {
     92                 ALOGW("setDeviceConnectionState() device already connected: %x", device);
     93                 return INVALID_OPERATION;
     94             }
     95             ALOGV("setDeviceConnectionState() connecting device %x", device);
     96 
     97             // register new device as available
     98             index = mAvailableOutputDevices.add(devDesc);
     99             if (index >= 0) {
    100                 sp<HwModule> module = mHwModules.getModuleForDevice(device);
    101                 if (module == 0) {
    102                     ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
    103                           device);
    104                     mAvailableOutputDevices.remove(devDesc);
    105                     return INVALID_OPERATION;
    106                 }
    107                 mAvailableOutputDevices[index]->attach(module);
    108             } else {
    109                 return NO_MEMORY;
    110             }
    111 
    112             if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
    113                 mAvailableOutputDevices.remove(devDesc);
    114                 return INVALID_OPERATION;
    115             }
    116             // Propagate device availability to Engine
    117             mEngine->setDeviceConnectionState(devDesc, state);
    118 
    119             // outputs should never be empty here
    120             ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
    121                     "checkOutputsForDevice() returned no outputs but status OK");
    122             ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
    123                   outputs.size());
    124 
    125             // Send connect to HALs
    126             AudioParameter param = AudioParameter(devDesc->mAddress);
    127             param.addInt(String8(AUDIO_PARAMETER_DEVICE_CONNECT), device);
    128             mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
    129 
    130             } break;
    131         // handle output device disconnection
    132         case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
    133             if (index < 0) {
    134                 ALOGW("setDeviceConnectionState() device not connected: %x", device);
    135                 return INVALID_OPERATION;
    136             }
    137 
    138             ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
    139 
    140             // Send Disconnect to HALs
    141             AudioParameter param = AudioParameter(devDesc->mAddress);
    142             param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
    143             mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
    144 
    145             // remove device from available output devices
    146             mAvailableOutputDevices.remove(devDesc);
    147 
    148             checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
    149 
    150             // Propagate device availability to Engine
    151             mEngine->setDeviceConnectionState(devDesc, state);
    152             } break;
    153 
    154         default:
    155             ALOGE("setDeviceConnectionState() invalid state: %x", state);
    156             return BAD_VALUE;
    157         }
    158 
    159         // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
    160         // output is suspended before any tracks are moved to it
    161         checkA2dpSuspend();
    162         checkOutputForAllStrategies();
    163         // outputs must be closed after checkOutputForAllStrategies() is executed
    164         if (!outputs.isEmpty()) {
    165             for (size_t i = 0; i < outputs.size(); i++) {
    166                 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
    167                 // close unused outputs after device disconnection or direct outputs that have been
    168                 // opened by checkOutputsForDevice() to query dynamic parameters
    169                 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
    170                         (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
    171                          (desc->mDirectOpenCount == 0))) {
    172                     closeOutput(outputs[i]);
    173                 }
    174             }
    175             // check again after closing A2DP output to reset mA2dpSuspended if needed
    176             checkA2dpSuspend();
    177         }
    178 
    179         updateDevicesAndOutputs();
    180         if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
    181             audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
    182             updateCallRouting(newDevice);
    183         }
    184         for (size_t i = 0; i < mOutputs.size(); i++) {
    185             sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
    186             if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
    187                 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
    188                 // do not force device change on duplicated output because if device is 0, it will
    189                 // also force a device 0 for the two outputs it is duplicated to which may override
    190                 // a valid device selection on those outputs.
    191                 bool force = !desc->isDuplicated()
    192                         && (!device_distinguishes_on_address(device)
    193                                 // always force when disconnecting (a non-duplicated device)
    194                                 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
    195                 setOutputDevice(desc, newDevice, force, 0);
    196             }
    197         }
    198 
    199         if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
    200             cleanUpForDevice(devDesc);
    201         }
    202 
    203         mpClientInterface->onAudioPortListUpdate();
    204         return NO_ERROR;
    205     }  // end if is output device
    206 
    207     // handle input devices
    208     if (audio_is_input_device(device)) {
    209         SortedVector <audio_io_handle_t> inputs;
    210 
    211         ssize_t index = mAvailableInputDevices.indexOf(devDesc);
    212         switch (state)
    213         {
    214         // handle input device connection
    215         case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
    216             if (index >= 0) {
    217                 ALOGW("setDeviceConnectionState() device already connected: %d", device);
    218                 return INVALID_OPERATION;
    219             }
    220             sp<HwModule> module = mHwModules.getModuleForDevice(device);
    221             if (module == NULL) {
    222                 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
    223                       device);
    224                 return INVALID_OPERATION;
    225             }
    226             if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
    227                 return INVALID_OPERATION;
    228             }
    229 
    230             index = mAvailableInputDevices.add(devDesc);
    231             if (index >= 0) {
    232                 mAvailableInputDevices[index]->attach(module);
    233             } else {
    234                 return NO_MEMORY;
    235             }
    236 
    237             // Set connect to HALs
    238             AudioParameter param = AudioParameter(devDesc->mAddress);
    239             param.addInt(String8(AUDIO_PARAMETER_DEVICE_CONNECT), device);
    240             mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
    241 
    242             // Propagate device availability to Engine
    243             mEngine->setDeviceConnectionState(devDesc, state);
    244         } break;
    245 
    246         // handle input device disconnection
    247         case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
    248             if (index < 0) {
    249                 ALOGW("setDeviceConnectionState() device not connected: %d", device);
    250                 return INVALID_OPERATION;
    251             }
    252 
    253             ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
    254 
    255             // Set Disconnect to HALs
    256             AudioParameter param = AudioParameter(devDesc->mAddress);
    257             param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
    258             mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
    259 
    260             checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
    261             mAvailableInputDevices.remove(devDesc);
    262 
    263             // Propagate device availability to Engine
    264             mEngine->setDeviceConnectionState(devDesc, state);
    265         } break;
    266 
    267         default:
    268             ALOGE("setDeviceConnectionState() invalid state: %x", state);
    269             return BAD_VALUE;
    270         }
    271 
    272         closeAllInputs();
    273 
    274         if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
    275             audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
    276             updateCallRouting(newDevice);
    277         }
    278 
    279         if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
    280             cleanUpForDevice(devDesc);
    281         }
    282 
    283         mpClientInterface->onAudioPortListUpdate();
    284         return NO_ERROR;
    285     } // end if is input device
    286 
    287     ALOGW("setDeviceConnectionState() invalid device: %x", device);
    288     return BAD_VALUE;
    289 }
    290 
    291 audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
    292                                                                       const char *device_address)
    293 {
    294     sp<DeviceDescriptor> devDesc =
    295             mHwModules.getDeviceDescriptor(device, device_address, "",
    296                                            (strlen(device_address) != 0)/*matchAddress*/);
    297 
    298     if (devDesc == 0) {
    299         ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
    300               device, device_address);
    301         return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
    302     }
    303 
    304     DeviceVector *deviceVector;
    305 
    306     if (audio_is_output_device(device)) {
    307         deviceVector = &mAvailableOutputDevices;
    308     } else if (audio_is_input_device(device)) {
    309         deviceVector = &mAvailableInputDevices;
    310     } else {
    311         ALOGW("getDeviceConnectionState() invalid device type %08x", device);
    312         return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
    313     }
    314 
    315     return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
    316             AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
    317 }
    318 
    319 void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
    320 {
    321     bool createTxPatch = false;
    322     status_t status;
    323     audio_patch_handle_t afPatchHandle;
    324     DeviceVector deviceList;
    325 
    326     if(!hasPrimaryOutput()) {
    327         return;
    328     }
    329     audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
    330     ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
    331 
    332     // release existing RX patch if any
    333     if (mCallRxPatch != 0) {
    334         mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
    335         mCallRxPatch.clear();
    336     }
    337     // release TX patch if any
    338     if (mCallTxPatch != 0) {
    339         mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
    340         mCallTxPatch.clear();
    341     }
    342 
    343     // If the RX device is on the primary HW module, then use legacy routing method for voice calls
    344     // via setOutputDevice() on primary output.
    345     // Otherwise, create two audio patches for TX and RX path.
    346     if (availablePrimaryOutputDevices() & rxDevice) {
    347         setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
    348         // If the TX device is also on the primary HW module, setOutputDevice() will take care
    349         // of it due to legacy implementation. If not, create a patch.
    350         if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
    351                 == AUDIO_DEVICE_NONE) {
    352             createTxPatch = true;
    353         }
    354     } else { // create RX path audio patch
    355         struct audio_patch patch;
    356 
    357         patch.num_sources = 1;
    358         patch.num_sinks = 1;
    359         deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
    360         ALOG_ASSERT(!deviceList.isEmpty(),
    361                     "updateCallRouting() selected device not in output device list");
    362         sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
    363         deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
    364         ALOG_ASSERT(!deviceList.isEmpty(),
    365                     "updateCallRouting() no telephony RX device");
    366         sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
    367 
    368         rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
    369         rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
    370 
    371         // request to reuse existing output stream if one is already opened to reach the RX device
    372         SortedVector<audio_io_handle_t> outputs =
    373                                 getOutputsForDevice(rxDevice, mOutputs);
    374         audio_io_handle_t output = selectOutput(outputs,
    375                                                 AUDIO_OUTPUT_FLAG_NONE,
    376                                                 AUDIO_FORMAT_INVALID);
    377         if (output != AUDIO_IO_HANDLE_NONE) {
    378             sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
    379             ALOG_ASSERT(!outputDesc->isDuplicated(),
    380                         "updateCallRouting() RX device output is duplicated");
    381             outputDesc->toAudioPortConfig(&patch.sources[1]);
    382             patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
    383             patch.num_sources = 2;
    384         }
    385 
    386         afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
    387         status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
    388         ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
    389                                                status);
    390         if (status == NO_ERROR) {
    391             mCallRxPatch = new AudioPatch(&patch, mUidCached);
    392             mCallRxPatch->mAfPatchHandle = afPatchHandle;
    393             mCallRxPatch->mUid = mUidCached;
    394         }
    395         createTxPatch = true;
    396     }
    397     if (createTxPatch) { // create TX path audio patch
    398         struct audio_patch patch;
    399 
    400         patch.num_sources = 1;
    401         patch.num_sinks = 1;
    402         deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
    403         ALOG_ASSERT(!deviceList.isEmpty(),
    404                     "updateCallRouting() selected device not in input device list");
    405         sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
    406         txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
    407         deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
    408         ALOG_ASSERT(!deviceList.isEmpty(),
    409                     "updateCallRouting() no telephony TX device");
    410         sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
    411         txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
    412 
    413         SortedVector<audio_io_handle_t> outputs =
    414                                 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
    415         audio_io_handle_t output = selectOutput(outputs,
    416                                                 AUDIO_OUTPUT_FLAG_NONE,
    417                                                 AUDIO_FORMAT_INVALID);
    418         // request to reuse existing output stream if one is already opened to reach the TX
    419         // path output device
    420         if (output != AUDIO_IO_HANDLE_NONE) {
    421             sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
    422             ALOG_ASSERT(!outputDesc->isDuplicated(),
    423                         "updateCallRouting() RX device output is duplicated");
    424             outputDesc->toAudioPortConfig(&patch.sources[1]);
    425             patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
    426             patch.num_sources = 2;
    427         }
    428 
    429         // terminate active capture if on the same HW module as the call TX source device
    430         // FIXME: would be better to refine to only inputs whose profile connects to the
    431         // call TX device but this information is not in the audio patch and logic here must be
    432         // symmetric to the one in startInput()
    433         audio_io_handle_t activeInput = mInputs.getActiveInput();
    434         if (activeInput != 0) {
    435             sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
    436             if (activeDesc->getModuleHandle() == txSourceDeviceDesc->getModuleHandle()) {
    437                 //FIXME: consider all active sessions
    438                 AudioSessionCollection activeSessions = activeDesc->getActiveAudioSessions();
    439                 audio_session_t activeSession = activeSessions.keyAt(0);
    440                 stopInput(activeInput, activeSession);
    441                 releaseInput(activeInput, activeSession);
    442             }
    443         }
    444 
    445         afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
    446         status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
    447         ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
    448                                                status);
    449         if (status == NO_ERROR) {
    450             mCallTxPatch = new AudioPatch(&patch, mUidCached);
    451             mCallTxPatch->mAfPatchHandle = afPatchHandle;
    452             mCallTxPatch->mUid = mUidCached;
    453         }
    454     }
    455 }
    456 
    457 void AudioPolicyManager::setPhoneState(audio_mode_t state)
    458 {
    459     ALOGV("setPhoneState() state %d", state);
    460     // store previous phone state for management of sonification strategy below
    461     int oldState = mEngine->getPhoneState();
    462 
    463     if (mEngine->setPhoneState(state) != NO_ERROR) {
    464         ALOGW("setPhoneState() invalid or same state %d", state);
    465         return;
    466     }
    467     /// Opens: can these line be executed after the switch of volume curves???
    468     // if leaving call state, handle special case of active streams
    469     // pertaining to sonification strategy see handleIncallSonification()
    470     if (isStateInCall(oldState)) {
    471         ALOGV("setPhoneState() in call state management: new state is %d", state);
    472         for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
    473             handleIncallSonification((audio_stream_type_t)stream, false, true);
    474         }
    475 
    476         // force reevaluating accessibility routing when call stops
    477         mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
    478     }
    479 
    480     /**
    481      * Switching to or from incall state or switching between telephony and VoIP lead to force
    482      * routing command.
    483      */
    484     bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
    485                   || (is_state_in_call(state) && (state != oldState)));
    486 
    487     // check for device and output changes triggered by new phone state
    488     checkA2dpSuspend();
    489     checkOutputForAllStrategies();
    490     updateDevicesAndOutputs();
    491 
    492     int delayMs = 0;
    493     if (isStateInCall(state)) {
    494         nsecs_t sysTime = systemTime();
    495         for (size_t i = 0; i < mOutputs.size(); i++) {
    496             sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
    497             // mute media and sonification strategies and delay device switch by the largest
    498             // latency of any output where either strategy is active.
    499             // This avoid sending the ring tone or music tail into the earpiece or headset.
    500             if ((isStrategyActive(desc, STRATEGY_MEDIA,
    501                                   SONIFICATION_HEADSET_MUSIC_DELAY,
    502                                   sysTime) ||
    503                  isStrategyActive(desc, STRATEGY_SONIFICATION,
    504                                   SONIFICATION_HEADSET_MUSIC_DELAY,
    505                                   sysTime)) &&
    506                     (delayMs < (int)desc->latency()*2)) {
    507                 delayMs = desc->latency()*2;
    508             }
    509             setStrategyMute(STRATEGY_MEDIA, true, desc);
    510             setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
    511                 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
    512             setStrategyMute(STRATEGY_SONIFICATION, true, desc);
    513             setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
    514                 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
    515         }
    516     }
    517 
    518     if (hasPrimaryOutput()) {
    519         // Note that despite the fact that getNewOutputDevice() is called on the primary output,
    520         // the device returned is not necessarily reachable via this output
    521         audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
    522         // force routing command to audio hardware when ending call
    523         // even if no device change is needed
    524         if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
    525             rxDevice = mPrimaryOutput->device();
    526         }
    527 
    528         if (state == AUDIO_MODE_IN_CALL) {
    529             updateCallRouting(rxDevice, delayMs);
    530         } else if (oldState == AUDIO_MODE_IN_CALL) {
    531             if (mCallRxPatch != 0) {
    532                 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
    533                 mCallRxPatch.clear();
    534             }
    535             if (mCallTxPatch != 0) {
    536                 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
    537                 mCallTxPatch.clear();
    538             }
    539             setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
    540         } else {
    541             setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
    542         }
    543     }
    544     // if entering in call state, handle special case of active streams
    545     // pertaining to sonification strategy see handleIncallSonification()
    546     if (isStateInCall(state)) {
    547         ALOGV("setPhoneState() in call state management: new state is %d", state);
    548         for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
    549             handleIncallSonification((audio_stream_type_t)stream, true, true);
    550         }
    551 
    552         // force reevaluating accessibility routing when call starts
    553         mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
    554     }
    555 
    556     // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
    557     if (state == AUDIO_MODE_RINGTONE &&
    558         isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
    559         mLimitRingtoneVolume = true;
    560     } else {
    561         mLimitRingtoneVolume = false;
    562     }
    563 }
    564 
    565 audio_mode_t AudioPolicyManager::getPhoneState() {
    566     return mEngine->getPhoneState();
    567 }
    568 
    569 void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
    570                                          audio_policy_forced_cfg_t config)
    571 {
    572     ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
    573 
    574     if (mEngine->setForceUse(usage, config) != NO_ERROR) {
    575         ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
    576         return;
    577     }
    578     bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
    579             (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
    580             (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
    581 
    582     // check for device and output changes triggered by new force usage
    583     checkA2dpSuspend();
    584     checkOutputForAllStrategies();
    585     updateDevicesAndOutputs();
    586 
    587     if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
    588         audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
    589         updateCallRouting(newDevice);
    590     }
    591     for (size_t i = 0; i < mOutputs.size(); i++) {
    592         sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
    593         audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
    594         if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
    595             setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE));
    596         }
    597         if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
    598             applyStreamVolumes(outputDesc, newDevice, 0, true);
    599         }
    600     }
    601 
    602     audio_io_handle_t activeInput = mInputs.getActiveInput();
    603     if (activeInput != 0) {
    604         sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
    605         audio_devices_t newDevice = getNewInputDevice(activeInput);
    606         // Force new input selection if the new device can not be reached via current input
    607         if (activeDesc->mProfile->getSupportedDevices().types() & (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
    608             setInputDevice(activeInput, newDevice);
    609         } else {
    610             closeInput(activeInput);
    611         }
    612     }
    613 }
    614 
    615 void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
    616 {
    617     ALOGV("setSystemProperty() property %s, value %s", property, value);
    618 }
    619 
    620 // Find a direct output profile compatible with the parameters passed, even if the input flags do
    621 // not explicitly request a direct output
    622 sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
    623                                                                audio_devices_t device,
    624                                                                uint32_t samplingRate,
    625                                                                audio_format_t format,
    626                                                                audio_channel_mask_t channelMask,
    627                                                                audio_output_flags_t flags)
    628 {
    629     // only retain flags that will drive the direct output profile selection
    630     // if explicitly requested
    631     static const uint32_t kRelevantFlags =
    632             (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
    633     flags =
    634         (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
    635 
    636     sp<IOProfile> profile;
    637 
    638     for (size_t i = 0; i < mHwModules.size(); i++) {
    639         if (mHwModules[i]->mHandle == 0) {
    640             continue;
    641         }
    642         for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
    643             sp<IOProfile> curProfile = mHwModules[i]->mOutputProfiles[j];
    644             if (!curProfile->isCompatibleProfile(device, String8(""),
    645                     samplingRate, NULL /*updatedSamplingRate*/,
    646                     format, NULL /*updatedFormat*/,
    647                     channelMask, NULL /*updatedChannelMask*/,
    648                     flags)) {
    649                 continue;
    650             }
    651             // reject profiles not corresponding to a device currently available
    652             if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
    653                 continue;
    654             }
    655             // if several profiles are compatible, give priority to one with offload capability
    656             if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
    657                 continue;
    658             }
    659             profile = curProfile;
    660             if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
    661                 break;
    662             }
    663         }
    664     }
    665     return profile;
    666 }
    667 
    668 audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
    669                                                 uint32_t samplingRate,
    670                                                 audio_format_t format,
    671                                                 audio_channel_mask_t channelMask,
    672                                                 audio_output_flags_t flags,
    673                                                 const audio_offload_info_t *offloadInfo)
    674 {
    675     routing_strategy strategy = getStrategy(stream);
    676     audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
    677     ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
    678           device, stream, samplingRate, format, channelMask, flags);
    679 
    680     return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
    681                               stream, samplingRate,format, channelMask,
    682                               flags, offloadInfo);
    683 }
    684 
    685 status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
    686                                               audio_io_handle_t *output,
    687                                               audio_session_t session,
    688                                               audio_stream_type_t *stream,
    689                                               uid_t uid,
    690                                               uint32_t samplingRate,
    691                                               audio_format_t format,
    692                                               audio_channel_mask_t channelMask,
    693                                               audio_output_flags_t flags,
    694                                               audio_port_handle_t selectedDeviceId,
    695                                               const audio_offload_info_t *offloadInfo)
    696 {
    697     audio_attributes_t attributes;
    698     if (attr != NULL) {
    699         if (!isValidAttributes(attr)) {
    700             ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
    701                   attr->usage, attr->content_type, attr->flags,
    702                   attr->tags);
    703             return BAD_VALUE;
    704         }
    705         attributes = *attr;
    706     } else {
    707         if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
    708             ALOGE("getOutputForAttr():  invalid stream type");
    709             return BAD_VALUE;
    710         }
    711         stream_type_to_audio_attributes(*stream, &attributes);
    712     }
    713     sp<SwAudioOutputDescriptor> desc;
    714     if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
    715         ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
    716         if (!audio_has_proportional_frames(format)) {
    717             return BAD_VALUE;
    718         }
    719         *stream = streamTypefromAttributesInt(&attributes);
    720         *output = desc->mIoHandle;
    721         ALOGV("getOutputForAttr() returns output %d", *output);
    722         return NO_ERROR;
    723     }
    724     if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
    725         ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
    726         return BAD_VALUE;
    727     }
    728 
    729     ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
    730             " session %d selectedDeviceId %d",
    731             attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
    732             session, selectedDeviceId);
    733 
    734     *stream = streamTypefromAttributesInt(&attributes);
    735 
    736     // Explicit routing?
    737     sp<DeviceDescriptor> deviceDesc;
    738     for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
    739         if (mAvailableOutputDevices[i]->getId() == selectedDeviceId) {
    740             deviceDesc = mAvailableOutputDevices[i];
    741             break;
    742         }
    743     }
    744     mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
    745 
    746     routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
    747     audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
    748 
    749     if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
    750         flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
    751     }
    752 
    753     ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
    754           device, samplingRate, format, channelMask, flags);
    755 
    756     *output = getOutputForDevice(device, session, *stream,
    757                                  samplingRate, format, channelMask,
    758                                  flags, offloadInfo);
    759     if (*output == AUDIO_IO_HANDLE_NONE) {
    760         mOutputRoutes.removeRoute(session);
    761         return INVALID_OPERATION;
    762     }
    763 
    764     return NO_ERROR;
    765 }
    766 
    767 audio_io_handle_t AudioPolicyManager::getOutputForDevice(
    768         audio_devices_t device,
    769         audio_session_t session __unused,
    770         audio_stream_type_t stream,
    771         uint32_t samplingRate,
    772         audio_format_t format,
    773         audio_channel_mask_t channelMask,
    774         audio_output_flags_t flags,
    775         const audio_offload_info_t *offloadInfo)
    776 {
    777     audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
    778     uint32_t latency = 0;
    779     status_t status;
    780 
    781 #ifdef AUDIO_POLICY_TEST
    782     if (mCurOutput != 0) {
    783         ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
    784                 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
    785 
    786         if (mTestOutputs[mCurOutput] == 0) {
    787             ALOGV("getOutput() opening test output");
    788             sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
    789                                                                                mpClientInterface);
    790             outputDesc->mDevice = mTestDevice;
    791             outputDesc->mLatency = mTestLatencyMs;
    792             outputDesc->mFlags =
    793                     (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
    794             outputDesc->mRefCount[stream] = 0;
    795             audio_config_t config = AUDIO_CONFIG_INITIALIZER;
    796             config.sample_rate = mTestSamplingRate;
    797             config.channel_mask = mTestChannels;
    798             config.format = mTestFormat;
    799             if (offloadInfo != NULL) {
    800                 config.offload_info = *offloadInfo;
    801             }
    802             status = mpClientInterface->openOutput(0,
    803                                                   &mTestOutputs[mCurOutput],
    804                                                   &config,
    805                                                   &outputDesc->mDevice,
    806                                                   String8(""),
    807                                                   &outputDesc->mLatency,
    808                                                   outputDesc->mFlags);
    809             if (status == NO_ERROR) {
    810                 outputDesc->mSamplingRate = config.sample_rate;
    811                 outputDesc->mFormat = config.format;
    812                 outputDesc->mChannelMask = config.channel_mask;
    813                 AudioParameter outputCmd = AudioParameter();
    814                 outputCmd.addInt(String8("set_id"),mCurOutput);
    815                 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
    816                 addOutput(mTestOutputs[mCurOutput], outputDesc);
    817             }
    818         }
    819         return mTestOutputs[mCurOutput];
    820     }
    821 #endif //AUDIO_POLICY_TEST
    822 
    823     // open a direct output if required by specified parameters
    824     //force direct flag if offload flag is set: offloading implies a direct output stream
    825     // and all common behaviors are driven by checking only the direct flag
    826     // this should normally be set appropriately in the policy configuration file
    827     if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
    828         flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
    829     }
    830     if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
    831         flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
    832     }
    833     // only allow deep buffering for music stream type
    834     if (stream != AUDIO_STREAM_MUSIC) {
    835         flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
    836     } else if (/* stream == AUDIO_STREAM_MUSIC && */
    837             flags == AUDIO_OUTPUT_FLAG_NONE &&
    838             property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
    839         // use DEEP_BUFFER as default output for music stream type
    840         flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
    841     }
    842     if (stream == AUDIO_STREAM_TTS) {
    843         flags = AUDIO_OUTPUT_FLAG_TTS;
    844     }
    845 
    846     sp<IOProfile> profile;
    847 
    848     // skip direct output selection if the request can obviously be attached to a mixed output
    849     // and not explicitly requested
    850     if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
    851             audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX &&
    852             audio_channel_count_from_out_mask(channelMask) <= 2) {
    853         goto non_direct_output;
    854     }
    855 
    856     // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
    857     // This prevents creating an offloaded track and tearing it down immediately after start
    858     // when audioflinger detects there is an active non offloadable effect.
    859     // FIXME: We should check the audio session here but we do not have it in this context.
    860     // This may prevent offloading in rare situations where effects are left active by apps
    861     // in the background.
    862 
    863     if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
    864             !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
    865         profile = getProfileForDirectOutput(device,
    866                                            samplingRate,
    867                                            format,
    868                                            channelMask,
    869                                            (audio_output_flags_t)flags);
    870     }
    871 
    872     if (profile != 0) {
    873         sp<SwAudioOutputDescriptor> outputDesc = NULL;
    874 
    875         for (size_t i = 0; i < mOutputs.size(); i++) {
    876             sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
    877             if (!desc->isDuplicated() && (profile == desc->mProfile)) {
    878                 outputDesc = desc;
    879                 // reuse direct output if currently open and configured with same parameters
    880                 if ((samplingRate == outputDesc->mSamplingRate) &&
    881                         audio_formats_match(format, outputDesc->mFormat) &&
    882                         (channelMask == outputDesc->mChannelMask)) {
    883                     outputDesc->mDirectOpenCount++;
    884                     ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
    885                     return mOutputs.keyAt(i);
    886                 }
    887             }
    888         }
    889         // close direct output if currently open and configured with different parameters
    890         if (outputDesc != NULL) {
    891             closeOutput(outputDesc->mIoHandle);
    892         }
    893 
    894         // if the selected profile is offloaded and no offload info was specified,
    895         // create a default one
    896         audio_offload_info_t defaultOffloadInfo = AUDIO_INFO_INITIALIZER;
    897         if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) && !offloadInfo) {
    898             flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
    899             defaultOffloadInfo.sample_rate = samplingRate;
    900             defaultOffloadInfo.channel_mask = channelMask;
    901             defaultOffloadInfo.format = format;
    902             defaultOffloadInfo.stream_type = stream;
    903             defaultOffloadInfo.bit_rate = 0;
    904             defaultOffloadInfo.duration_us = -1;
    905             defaultOffloadInfo.has_video = true; // conservative
    906             defaultOffloadInfo.is_streaming = true; // likely
    907             offloadInfo = &defaultOffloadInfo;
    908         }
    909 
    910         outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
    911         outputDesc->mDevice = device;
    912         outputDesc->mLatency = 0;
    913         outputDesc->mFlags = (audio_output_flags_t)(outputDesc->mFlags | flags);
    914         audio_config_t config = AUDIO_CONFIG_INITIALIZER;
    915         config.sample_rate = samplingRate;
    916         config.channel_mask = channelMask;
    917         config.format = format;
    918         if (offloadInfo != NULL) {
    919             config.offload_info = *offloadInfo;
    920         }
    921         status = mpClientInterface->openOutput(profile->getModuleHandle(),
    922                                                &output,
    923                                                &config,
    924                                                &outputDesc->mDevice,
    925                                                String8(""),
    926                                                &outputDesc->mLatency,
    927                                                outputDesc->mFlags);
    928 
    929         // only accept an output with the requested parameters
    930         if (status != NO_ERROR ||
    931             (samplingRate != 0 && samplingRate != config.sample_rate) ||
    932             (format != AUDIO_FORMAT_DEFAULT && !audio_formats_match(format, config.format)) ||
    933             (channelMask != 0 && channelMask != config.channel_mask)) {
    934             ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
    935                     "format %d %d, channelMask %04x %04x", output, samplingRate,
    936                     outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
    937                     outputDesc->mChannelMask);
    938             if (output != AUDIO_IO_HANDLE_NONE) {
    939                 mpClientInterface->closeOutput(output);
    940             }
    941             // fall back to mixer output if possible when the direct output could not be open
    942             if (audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX) {
    943                 goto non_direct_output;
    944             }
    945             return AUDIO_IO_HANDLE_NONE;
    946         }
    947         outputDesc->mSamplingRate = config.sample_rate;
    948         outputDesc->mChannelMask = config.channel_mask;
    949         outputDesc->mFormat = config.format;
    950         outputDesc->mRefCount[stream] = 0;
    951         outputDesc->mStopTime[stream] = 0;
    952         outputDesc->mDirectOpenCount = 1;
    953 
    954         audio_io_handle_t srcOutput = getOutputForEffect();
    955         addOutput(output, outputDesc);
    956         audio_io_handle_t dstOutput = getOutputForEffect();
    957         if (dstOutput == output) {
    958             mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
    959         }
    960         mPreviousOutputs = mOutputs;
    961         ALOGV("getOutput() returns new direct output %d", output);
    962         mpClientInterface->onAudioPortListUpdate();
    963         return output;
    964     }
    965 
    966 non_direct_output:
    967 
    968     // A request for HW A/V sync cannot fallback to a mixed output because time
    969     // stamps are embedded in audio data
    970     if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
    971         return AUDIO_IO_HANDLE_NONE;
    972     }
    973 
    974     // ignoring channel mask due to downmix capability in mixer
    975 
    976     // open a non direct output
    977 
    978     // for non direct outputs, only PCM is supported
    979     if (audio_is_linear_pcm(format)) {
    980         // get which output is suitable for the specified stream. The actual
    981         // routing change will happen when startOutput() will be called
    982         SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
    983 
    984         // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
    985         flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
    986         output = selectOutput(outputs, flags, format);
    987     }
    988     ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
    989             "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
    990 
    991     ALOGV("  getOutputForDevice() returns output %d", output);
    992 
    993     return output;
    994 }
    995 
    996 audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
    997                                                        audio_output_flags_t flags,
    998                                                        audio_format_t format)
    999 {
   1000     // select one output among several that provide a path to a particular device or set of
   1001     // devices (the list was previously build by getOutputsForDevice()).
   1002     // The priority is as follows:
   1003     // 1: the output with the highest number of requested policy flags
   1004     // 2: the output with the bit depth the closest to the requested one
   1005     // 3: the primary output
   1006     // 4: the first output in the list
   1007 
   1008     if (outputs.size() == 0) {
   1009         return 0;
   1010     }
   1011     if (outputs.size() == 1) {
   1012         return outputs[0];
   1013     }
   1014 
   1015     int maxCommonFlags = 0;
   1016     audio_io_handle_t outputForFlags = 0;
   1017     audio_io_handle_t outputForPrimary = 0;
   1018     audio_io_handle_t outputForFormat = 0;
   1019     audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
   1020     audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
   1021 
   1022     for (size_t i = 0; i < outputs.size(); i++) {
   1023         sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
   1024         if (!outputDesc->isDuplicated()) {
   1025             // if a valid format is specified, skip output if not compatible
   1026             if (format != AUDIO_FORMAT_INVALID) {
   1027                 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
   1028                     if (!audio_formats_match(format, outputDesc->mFormat)) {
   1029                         continue;
   1030                     }
   1031                 } else if (!audio_is_linear_pcm(format)) {
   1032                     continue;
   1033                 }
   1034                 if (AudioPort::isBetterFormatMatch(
   1035                         outputDesc->mFormat, bestFormat, format)) {
   1036                     outputForFormat = outputs[i];
   1037                     bestFormat = outputDesc->mFormat;
   1038                 }
   1039             }
   1040 
   1041             int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
   1042             if (commonFlags >= maxCommonFlags) {
   1043                 if (commonFlags == maxCommonFlags) {
   1044                     if (AudioPort::isBetterFormatMatch(
   1045                             outputDesc->mFormat, bestFormatForFlags, format)) {
   1046                         outputForFlags = outputs[i];
   1047                         bestFormatForFlags = outputDesc->mFormat;
   1048                     }
   1049                 } else {
   1050                     outputForFlags = outputs[i];
   1051                     maxCommonFlags = commonFlags;
   1052                     bestFormatForFlags = outputDesc->mFormat;
   1053                 }
   1054                 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
   1055             }
   1056             if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
   1057                 outputForPrimary = outputs[i];
   1058             }
   1059         }
   1060     }
   1061 
   1062     if (outputForFlags != 0) {
   1063         return outputForFlags;
   1064     }
   1065     if (outputForFormat != 0) {
   1066         return outputForFormat;
   1067     }
   1068     if (outputForPrimary != 0) {
   1069         return outputForPrimary;
   1070     }
   1071 
   1072     return outputs[0];
   1073 }
   1074 
   1075 status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
   1076                                              audio_stream_type_t stream,
   1077                                              audio_session_t session)
   1078 {
   1079     ALOGV("startOutput() output %d, stream %d, session %d",
   1080           output, stream, session);
   1081     ssize_t index = mOutputs.indexOfKey(output);
   1082     if (index < 0) {
   1083         ALOGW("startOutput() unknown output %d", output);
   1084         return BAD_VALUE;
   1085     }
   1086 
   1087     sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
   1088 
   1089     // Routing?
   1090     mOutputRoutes.incRouteActivity(session);
   1091 
   1092     audio_devices_t newDevice;
   1093     AudioMix *policyMix = NULL;
   1094     const char *address = NULL;
   1095     if (outputDesc->mPolicyMix != NULL) {
   1096         policyMix = outputDesc->mPolicyMix;
   1097         address = policyMix->mDeviceAddress.string();
   1098         if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
   1099             newDevice = policyMix->mDeviceType;
   1100         } else {
   1101             newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
   1102         }
   1103     } else if (mOutputRoutes.hasRouteChanged(session)) {
   1104         newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
   1105         checkStrategyRoute(getStrategy(stream), output);
   1106     } else {
   1107         newDevice = AUDIO_DEVICE_NONE;
   1108     }
   1109 
   1110     uint32_t delayMs = 0;
   1111 
   1112     status_t status = startSource(outputDesc, stream, newDevice, address, &delayMs);
   1113 
   1114     if (status != NO_ERROR) {
   1115         mOutputRoutes.decRouteActivity(session);
   1116         return status;
   1117     }
   1118     // Automatically enable the remote submix input when output is started on a re routing mix
   1119     // of type MIX_TYPE_RECORDERS
   1120     if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
   1121             policyMix->mMixType == MIX_TYPE_RECORDERS) {
   1122             setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
   1123                     AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
   1124                     address,
   1125                     "remote-submix");
   1126     }
   1127 
   1128     if (delayMs != 0) {
   1129         usleep(delayMs * 1000);
   1130     }
   1131 
   1132     return status;
   1133 }
   1134 
   1135 status_t AudioPolicyManager::startSource(sp<AudioOutputDescriptor> outputDesc,
   1136                                              audio_stream_type_t stream,
   1137                                              audio_devices_t device,
   1138                                              const char *address,
   1139                                              uint32_t *delayMs)
   1140 {
   1141     // cannot start playback of STREAM_TTS if any other output is being used
   1142     uint32_t beaconMuteLatency = 0;
   1143 
   1144     *delayMs = 0;
   1145     if (stream == AUDIO_STREAM_TTS) {
   1146         ALOGV("\t found BEACON stream");
   1147         if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
   1148             return INVALID_OPERATION;
   1149         } else {
   1150             beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
   1151         }
   1152     } else {
   1153         // some playback other than beacon starts
   1154         beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
   1155     }
   1156 
   1157     // check active before incrementing usage count
   1158     bool force = !outputDesc->isActive();
   1159 
   1160     // increment usage count for this stream on the requested output:
   1161     // NOTE that the usage count is the same for duplicated output and hardware output which is
   1162     // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
   1163     outputDesc->changeRefCount(stream, 1);
   1164 
   1165     if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
   1166         // starting an output being rerouted?
   1167         if (device == AUDIO_DEVICE_NONE) {
   1168             device = getNewOutputDevice(outputDesc, false /*fromCache*/);
   1169         }
   1170         routing_strategy strategy = getStrategy(stream);
   1171         bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
   1172                             (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
   1173                             (beaconMuteLatency > 0);
   1174         uint32_t waitMs = beaconMuteLatency;
   1175         for (size_t i = 0; i < mOutputs.size(); i++) {
   1176             sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
   1177             if (desc != outputDesc) {
   1178                 // force a device change if any other output is managed by the same hw
   1179                 // module and has a current device selection that differs from selected device.
   1180                 // In this case, the audio HAL must receive the new device selection so that it can
   1181                 // change the device currently selected by the other active output.
   1182                 if (outputDesc->sharesHwModuleWith(desc) &&
   1183                     desc->device() != device) {
   1184                     force = true;
   1185                 }
   1186                 // wait for audio on other active outputs to be presented when starting
   1187                 // a notification so that audio focus effect can propagate, or that a mute/unmute
   1188                 // event occurred for beacon
   1189                 uint32_t latency = desc->latency();
   1190                 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
   1191                     waitMs = latency;
   1192                 }
   1193             }
   1194         }
   1195         uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force, 0, NULL, address);
   1196 
   1197         // handle special case for sonification while in call
   1198         if (isInCall()) {
   1199             handleIncallSonification(stream, true, false);
   1200         }
   1201 
   1202         // apply volume rules for current stream and device if necessary
   1203         checkAndSetVolume(stream,
   1204                           mVolumeCurves->getVolumeIndex(stream, device),
   1205                           outputDesc,
   1206                           device);
   1207 
   1208         // update the outputs if starting an output with a stream that can affect notification
   1209         // routing
   1210         handleNotificationRoutingForStream(stream);
   1211 
   1212         // force reevaluating accessibility routing when ringtone or alarm starts
   1213         if (strategy == STRATEGY_SONIFICATION) {
   1214             mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
   1215         }
   1216     }
   1217     return NO_ERROR;
   1218 }
   1219 
   1220 
   1221 status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
   1222                                             audio_stream_type_t stream,
   1223                                             audio_session_t session)
   1224 {
   1225     ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
   1226     ssize_t index = mOutputs.indexOfKey(output);
   1227     if (index < 0) {
   1228         ALOGW("stopOutput() unknown output %d", output);
   1229         return BAD_VALUE;
   1230     }
   1231 
   1232     sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
   1233 
   1234     if (outputDesc->mRefCount[stream] == 1) {
   1235         // Automatically disable the remote submix input when output is stopped on a
   1236         // re routing mix of type MIX_TYPE_RECORDERS
   1237         if (audio_is_remote_submix_device(outputDesc->mDevice) &&
   1238                 outputDesc->mPolicyMix != NULL &&
   1239                 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
   1240             setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
   1241                     AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
   1242                     outputDesc->mPolicyMix->mDeviceAddress,
   1243                     "remote-submix");
   1244         }
   1245     }
   1246 
   1247     // Routing?
   1248     bool forceDeviceUpdate = false;
   1249     if (outputDesc->mRefCount[stream] > 0) {
   1250         int activityCount = mOutputRoutes.decRouteActivity(session);
   1251         forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
   1252 
   1253         if (forceDeviceUpdate) {
   1254             checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
   1255         }
   1256     }
   1257 
   1258     return stopSource(outputDesc, stream, forceDeviceUpdate);
   1259 }
   1260 
   1261 status_t AudioPolicyManager::stopSource(sp<AudioOutputDescriptor> outputDesc,
   1262                                             audio_stream_type_t stream,
   1263                                             bool forceDeviceUpdate)
   1264 {
   1265     // always handle stream stop, check which stream type is stopping
   1266     handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
   1267 
   1268     // handle special case for sonification while in call
   1269     if (isInCall()) {
   1270         handleIncallSonification(stream, false, false);
   1271     }
   1272 
   1273     if (outputDesc->mRefCount[stream] > 0) {
   1274         // decrement usage count of this stream on the output
   1275         outputDesc->changeRefCount(stream, -1);
   1276 
   1277         // store time at which the stream was stopped - see isStreamActive()
   1278         if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
   1279             outputDesc->mStopTime[stream] = systemTime();
   1280             audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
   1281             // delay the device switch by twice the latency because stopOutput() is executed when
   1282             // the track stop() command is received and at that time the audio track buffer can
   1283             // still contain data that needs to be drained. The latency only covers the audio HAL
   1284             // and kernel buffers. Also the latency does not always include additional delay in the
   1285             // audio path (audio DSP, CODEC ...)
   1286             setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
   1287 
   1288             // force restoring the device selection on other active outputs if it differs from the
   1289             // one being selected for this output
   1290             for (size_t i = 0; i < mOutputs.size(); i++) {
   1291                 audio_io_handle_t curOutput = mOutputs.keyAt(i);
   1292                 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
   1293                 if (desc != outputDesc &&
   1294                         desc->isActive() &&
   1295                         outputDesc->sharesHwModuleWith(desc) &&
   1296                         (newDevice != desc->device())) {
   1297                     setOutputDevice(desc,
   1298                                     getNewOutputDevice(desc, false /*fromCache*/),
   1299                                     true,
   1300                                     outputDesc->latency()*2);
   1301                 }
   1302             }
   1303             // update the outputs if stopping one with a stream that can affect notification routing
   1304             handleNotificationRoutingForStream(stream);
   1305         }
   1306         return NO_ERROR;
   1307     } else {
   1308         ALOGW("stopOutput() refcount is already 0");
   1309         return INVALID_OPERATION;
   1310     }
   1311 }
   1312 
   1313 void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
   1314                                        audio_stream_type_t stream __unused,
   1315                                        audio_session_t session __unused)
   1316 {
   1317     ALOGV("releaseOutput() %d", output);
   1318     ssize_t index = mOutputs.indexOfKey(output);
   1319     if (index < 0) {
   1320         ALOGW("releaseOutput() releasing unknown output %d", output);
   1321         return;
   1322     }
   1323 
   1324 #ifdef AUDIO_POLICY_TEST
   1325     int testIndex = testOutputIndex(output);
   1326     if (testIndex != 0) {
   1327         sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
   1328         if (outputDesc->isActive()) {
   1329             mpClientInterface->closeOutput(output);
   1330             removeOutput(output);
   1331             mTestOutputs[testIndex] = 0;
   1332         }
   1333         return;
   1334     }
   1335 #endif //AUDIO_POLICY_TEST
   1336 
   1337     // Routing
   1338     mOutputRoutes.removeRoute(session);
   1339 
   1340     sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
   1341     if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
   1342         if (desc->mDirectOpenCount <= 0) {
   1343             ALOGW("releaseOutput() invalid open count %d for output %d",
   1344                                                               desc->mDirectOpenCount, output);
   1345             return;
   1346         }
   1347         if (--desc->mDirectOpenCount == 0) {
   1348             closeOutput(output);
   1349             // If effects where present on the output, audioflinger moved them to the primary
   1350             // output by default: move them back to the appropriate output.
   1351             audio_io_handle_t dstOutput = getOutputForEffect();
   1352             if (hasPrimaryOutput() && dstOutput != mPrimaryOutput->mIoHandle) {
   1353                 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX,
   1354                                                mPrimaryOutput->mIoHandle, dstOutput);
   1355             }
   1356             mpClientInterface->onAudioPortListUpdate();
   1357         }
   1358     }
   1359 }
   1360 
   1361 
   1362 status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
   1363                                              audio_io_handle_t *input,
   1364                                              audio_session_t session,
   1365                                              uid_t uid,
   1366                                              uint32_t samplingRate,
   1367                                              audio_format_t format,
   1368                                              audio_channel_mask_t channelMask,
   1369                                              audio_input_flags_t flags,
   1370                                              audio_port_handle_t selectedDeviceId,
   1371                                              input_type_t *inputType)
   1372 {
   1373     ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
   1374             "session %d, flags %#x",
   1375           attr->source, samplingRate, format, channelMask, session, flags);
   1376 
   1377     *input = AUDIO_IO_HANDLE_NONE;
   1378     *inputType = API_INPUT_INVALID;
   1379     audio_devices_t device;
   1380     // handle legacy remote submix case where the address was not always specified
   1381     String8 address = String8("");
   1382     audio_source_t inputSource = attr->source;
   1383     audio_source_t halInputSource;
   1384     AudioMix *policyMix = NULL;
   1385 
   1386     if (inputSource == AUDIO_SOURCE_DEFAULT) {
   1387         inputSource = AUDIO_SOURCE_MIC;
   1388     }
   1389     halInputSource = inputSource;
   1390 
   1391     // Explicit routing?
   1392     sp<DeviceDescriptor> deviceDesc;
   1393     for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
   1394         if (mAvailableInputDevices[i]->getId() == selectedDeviceId) {
   1395             deviceDesc = mAvailableInputDevices[i];
   1396             break;
   1397         }
   1398     }
   1399     mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
   1400 
   1401     if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
   1402             strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
   1403         status_t ret = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
   1404         if (ret != NO_ERROR) {
   1405             return ret;
   1406         }
   1407         *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
   1408         device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
   1409         address = String8(attr->tags + strlen("addr="));
   1410     } else {
   1411         device = getDeviceAndMixForInputSource(inputSource, &policyMix);
   1412         if (device == AUDIO_DEVICE_NONE) {
   1413             ALOGW("getInputForAttr() could not find device for source %d", inputSource);
   1414             return BAD_VALUE;
   1415         }
   1416         if (policyMix != NULL) {
   1417             address = policyMix->mDeviceAddress;
   1418             if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
   1419                 // there is an external policy, but this input is attached to a mix of recorders,
   1420                 // meaning it receives audio injected into the framework, so the recorder doesn't
   1421                 // know about it and is therefore considered "legacy"
   1422                 *inputType = API_INPUT_LEGACY;
   1423             } else {
   1424                 // recording a mix of players defined by an external policy, we're rerouting for
   1425                 // an external policy
   1426                 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
   1427             }
   1428         } else if (audio_is_remote_submix_device(device)) {
   1429             address = String8("0");
   1430             *inputType = API_INPUT_MIX_CAPTURE;
   1431         } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
   1432             *inputType = API_INPUT_TELEPHONY_RX;
   1433         } else {
   1434             *inputType = API_INPUT_LEGACY;
   1435         }
   1436 
   1437     }
   1438 
   1439     *input = getInputForDevice(device, address, session, uid, inputSource,
   1440                                samplingRate, format, channelMask, flags,
   1441                                policyMix);
   1442     if (*input == AUDIO_IO_HANDLE_NONE) {
   1443         mInputRoutes.removeRoute(session);
   1444         return INVALID_OPERATION;
   1445     }
   1446     ALOGV("getInputForAttr() returns input type = %d", *inputType);
   1447     return NO_ERROR;
   1448 }
   1449 
   1450 
   1451 audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
   1452                                                         String8 address,
   1453                                                         audio_session_t session,
   1454                                                         uid_t uid,
   1455                                                         audio_source_t inputSource,
   1456                                                         uint32_t samplingRate,
   1457                                                         audio_format_t format,
   1458                                                         audio_channel_mask_t channelMask,
   1459                                                         audio_input_flags_t flags,
   1460                                                         AudioMix *policyMix)
   1461 {
   1462     audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
   1463     audio_source_t halInputSource = inputSource;
   1464     bool isSoundTrigger = false;
   1465 
   1466     if (inputSource == AUDIO_SOURCE_HOTWORD) {
   1467         ssize_t index = mSoundTriggerSessions.indexOfKey(session);
   1468         if (index >= 0) {
   1469             input = mSoundTriggerSessions.valueFor(session);
   1470             isSoundTrigger = true;
   1471             flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
   1472             ALOGV("SoundTrigger capture on session %d input %d", session, input);
   1473         } else {
   1474             halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
   1475         }
   1476     }
   1477 
   1478     // find a compatible input profile (not necessarily identical in parameters)
   1479     sp<IOProfile> profile;
   1480     // samplingRate and flags may be updated by getInputProfile
   1481     uint32_t profileSamplingRate = (samplingRate == 0) ? SAMPLE_RATE_HZ_DEFAULT : samplingRate;
   1482     audio_format_t profileFormat = format;
   1483     audio_channel_mask_t profileChannelMask = channelMask;
   1484     audio_input_flags_t profileFlags = flags;
   1485     for (;;) {
   1486         profile = getInputProfile(device, address,
   1487                                   profileSamplingRate, profileFormat, profileChannelMask,
   1488                                   profileFlags);
   1489         if (profile != 0) {
   1490             break; // success
   1491         } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
   1492             profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
   1493         } else { // fail
   1494             ALOGW("getInputForDevice() could not find profile for device 0x%X,"
   1495                   "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
   1496                     device, samplingRate, format, channelMask, flags);
   1497             return input;
   1498         }
   1499     }
   1500     // Pick input sampling rate if not specified by client
   1501     if (samplingRate == 0) {
   1502         samplingRate = profileSamplingRate;
   1503     }
   1504 
   1505     if (profile->getModuleHandle() == 0) {
   1506         ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
   1507         return input;
   1508     }
   1509 
   1510     sp<AudioSession> audioSession = new AudioSession(session,
   1511                                                               inputSource,
   1512                                                               format,
   1513                                                               samplingRate,
   1514                                                               channelMask,
   1515                                                               flags,
   1516                                                               uid,
   1517                                                               isSoundTrigger,
   1518                                                               policyMix, mpClientInterface);
   1519 
   1520 // TODO enable input reuse
   1521 #if 0
   1522     // reuse an open input if possible
   1523     for (size_t i = 0; i < mInputs.size(); i++) {
   1524         sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
   1525         // reuse input if it shares the same profile and same sound trigger attribute
   1526         if (profile == desc->mProfile &&
   1527             isSoundTrigger == desc->isSoundTrigger()) {
   1528 
   1529             sp<AudioSession> as = desc->getAudioSession(session);
   1530             if (as != 0) {
   1531                 // do not allow unmatching properties on same session
   1532                 if (as->matches(audioSession)) {
   1533                     as->changeOpenCount(1);
   1534                 } else {
   1535                     ALOGW("getInputForDevice() record with different attributes"
   1536                           " exists for session %d", session);
   1537                     return input;
   1538                 }
   1539             } else {
   1540                 desc->addAudioSession(session, audioSession);
   1541             }
   1542             ALOGV("getInputForDevice() reusing input %d", mInputs.keyAt(i));
   1543             return mInputs.keyAt(i);
   1544         }
   1545     }
   1546 #endif
   1547 
   1548     audio_config_t config = AUDIO_CONFIG_INITIALIZER;
   1549     config.sample_rate = profileSamplingRate;
   1550     config.channel_mask = profileChannelMask;
   1551     config.format = profileFormat;
   1552 
   1553     status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
   1554                                                    &input,
   1555                                                    &config,
   1556                                                    &device,
   1557                                                    address,
   1558                                                    halInputSource,
   1559                                                    profileFlags);
   1560 
   1561     // only accept input with the exact requested set of parameters
   1562     if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
   1563         (profileSamplingRate != config.sample_rate) ||
   1564         !audio_formats_match(profileFormat, config.format) ||
   1565         (profileChannelMask != config.channel_mask)) {
   1566         ALOGW("getInputForAttr() failed opening input: samplingRate %d"
   1567               ", format %d, channelMask %x",
   1568                 samplingRate, format, channelMask);
   1569         if (input != AUDIO_IO_HANDLE_NONE) {
   1570             mpClientInterface->closeInput(input);
   1571         }
   1572         return AUDIO_IO_HANDLE_NONE;
   1573     }
   1574 
   1575     sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
   1576     inputDesc->mSamplingRate = profileSamplingRate;
   1577     inputDesc->mFormat = profileFormat;
   1578     inputDesc->mChannelMask = profileChannelMask;
   1579     inputDesc->mDevice = device;
   1580     inputDesc->mPolicyMix = policyMix;
   1581     inputDesc->addAudioSession(session, audioSession);
   1582 
   1583     addInput(input, inputDesc);
   1584     mpClientInterface->onAudioPortListUpdate();
   1585 
   1586     return input;
   1587 }
   1588 
   1589 status_t AudioPolicyManager::startInput(audio_io_handle_t input,
   1590                                         audio_session_t session)
   1591 {
   1592     ALOGV("startInput() input %d", input);
   1593     ssize_t index = mInputs.indexOfKey(input);
   1594     if (index < 0) {
   1595         ALOGW("startInput() unknown input %d", input);
   1596         return BAD_VALUE;
   1597     }
   1598     sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
   1599 
   1600     sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
   1601     if (audioSession == 0) {
   1602         ALOGW("startInput() unknown session %d on input %d", session, input);
   1603         return BAD_VALUE;
   1604     }
   1605 
   1606     // virtual input devices are compatible with other input devices
   1607     if (!is_virtual_input_device(inputDesc->mDevice)) {
   1608 
   1609         // for a non-virtual input device, check if there is another (non-virtual) active input
   1610         audio_io_handle_t activeInput = mInputs.getActiveInput();
   1611         if (activeInput != 0 && activeInput != input) {
   1612 
   1613             // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
   1614             // otherwise the active input continues and the new input cannot be started.
   1615             sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
   1616             if ((activeDesc->inputSource() == AUDIO_SOURCE_HOTWORD) &&
   1617                     !activeDesc->hasPreemptedSession(session)) {
   1618                 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
   1619                 //FIXME: consider all active sessions
   1620                 AudioSessionCollection activeSessions = activeDesc->getActiveAudioSessions();
   1621                 audio_session_t activeSession = activeSessions.keyAt(0);
   1622                 SortedVector<audio_session_t> sessions =
   1623                                            activeDesc->getPreemptedSessions();
   1624                 sessions.add(activeSession);
   1625                 inputDesc->setPreemptedSessions(sessions);
   1626                 stopInput(activeInput, activeSession);
   1627                 releaseInput(activeInput, activeSession);
   1628             } else {
   1629                 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
   1630                 return INVALID_OPERATION;
   1631             }
   1632         }
   1633 
   1634         // Do not allow capture if an active voice call is using a software patch and
   1635         // the call TX source device is on the same HW module.
   1636         // FIXME: would be better to refine to only inputs whose profile connects to the
   1637         // call TX device but this information is not in the audio patch
   1638         if (mCallTxPatch != 0 &&
   1639             inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
   1640             return INVALID_OPERATION;
   1641         }
   1642     }
   1643 
   1644     // Routing?
   1645     mInputRoutes.incRouteActivity(session);
   1646 
   1647     if (!inputDesc->isActive() || mInputRoutes.hasRouteChanged(session)) {
   1648         // if input maps to a dynamic policy with an activity listener, notify of state change
   1649         if ((inputDesc->mPolicyMix != NULL)
   1650                 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
   1651             mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
   1652                     MIX_STATE_MIXING);
   1653         }
   1654 
   1655         if (mInputs.activeInputsCount() == 0) {
   1656             SoundTrigger::setCaptureState(true);
   1657         }
   1658         setInputDevice(input, getNewInputDevice(input), true /* force */);
   1659 
   1660         // automatically enable the remote submix output when input is started if not
   1661         // used by a policy mix of type MIX_TYPE_RECORDERS
   1662         // For remote submix (a virtual device), we open only one input per capture request.
   1663         if (audio_is_remote_submix_device(inputDesc->mDevice)) {
   1664             String8 address = String8("");
   1665             if (inputDesc->mPolicyMix == NULL) {
   1666                 address = String8("0");
   1667             } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
   1668                 address = inputDesc->mPolicyMix->mDeviceAddress;
   1669             }
   1670             if (address != "") {
   1671                 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
   1672                         AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
   1673                         address, "remote-submix");
   1674             }
   1675         }
   1676     }
   1677 
   1678     ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
   1679 
   1680     audioSession->changeActiveCount(1);
   1681     return NO_ERROR;
   1682 }
   1683 
   1684 status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
   1685                                        audio_session_t session)
   1686 {
   1687     ALOGV("stopInput() input %d", input);
   1688     ssize_t index = mInputs.indexOfKey(input);
   1689     if (index < 0) {
   1690         ALOGW("stopInput() unknown input %d", input);
   1691         return BAD_VALUE;
   1692     }
   1693     sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
   1694 
   1695     sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
   1696     if (index < 0) {
   1697         ALOGW("stopInput() unknown session %d on input %d", session, input);
   1698         return BAD_VALUE;
   1699     }
   1700 
   1701     if (audioSession->activeCount() == 0) {
   1702         ALOGW("stopInput() input %d already stopped", input);
   1703         return INVALID_OPERATION;
   1704     }
   1705 
   1706     audioSession->changeActiveCount(-1);
   1707 
   1708     // Routing?
   1709     mInputRoutes.decRouteActivity(session);
   1710 
   1711     if (!inputDesc->isActive()) {
   1712         // if input maps to a dynamic policy with an activity listener, notify of state change
   1713         if ((inputDesc->mPolicyMix != NULL)
   1714                 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
   1715             mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
   1716                     MIX_STATE_IDLE);
   1717         }
   1718 
   1719         // automatically disable the remote submix output when input is stopped if not
   1720         // used by a policy mix of type MIX_TYPE_RECORDERS
   1721         if (audio_is_remote_submix_device(inputDesc->mDevice)) {
   1722             String8 address = String8("");
   1723             if (inputDesc->mPolicyMix == NULL) {
   1724                 address = String8("0");
   1725             } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
   1726                 address = inputDesc->mPolicyMix->mDeviceAddress;
   1727             }
   1728             if (address != "") {
   1729                 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
   1730                                          AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
   1731                                          address, "remote-submix");
   1732             }
   1733         }
   1734 
   1735         resetInputDevice(input);
   1736 
   1737         if (mInputs.activeInputsCount() == 0) {
   1738             SoundTrigger::setCaptureState(false);
   1739         }
   1740         inputDesc->clearPreemptedSessions();
   1741     }
   1742     return NO_ERROR;
   1743 }
   1744 
   1745 void AudioPolicyManager::releaseInput(audio_io_handle_t input,
   1746                                       audio_session_t session)
   1747 {
   1748 
   1749     ALOGV("releaseInput() %d", input);
   1750     ssize_t index = mInputs.indexOfKey(input);
   1751     if (index < 0) {
   1752         ALOGW("releaseInput() releasing unknown input %d", input);
   1753         return;
   1754     }
   1755 
   1756     // Routing
   1757     mInputRoutes.removeRoute(session);
   1758 
   1759     sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
   1760     ALOG_ASSERT(inputDesc != 0);
   1761 
   1762     sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
   1763     if (index < 0) {
   1764         ALOGW("releaseInput() unknown session %d on input %d", session, input);
   1765         return;
   1766     }
   1767 
   1768     if (audioSession->openCount() == 0) {
   1769         ALOGW("releaseInput() invalid open count %d on session %d",
   1770               audioSession->openCount(), session);
   1771         return;
   1772     }
   1773 
   1774     if (audioSession->changeOpenCount(-1) == 0) {
   1775         inputDesc->removeAudioSession(session);
   1776     }
   1777 
   1778     if (inputDesc->getOpenRefCount() > 0) {
   1779         ALOGV("releaseInput() exit > 0");
   1780         return;
   1781     }
   1782 
   1783     closeInput(input);
   1784     mpClientInterface->onAudioPortListUpdate();
   1785     ALOGV("releaseInput() exit");
   1786 }
   1787 
   1788 void AudioPolicyManager::closeAllInputs() {
   1789     bool patchRemoved = false;
   1790 
   1791     for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
   1792         sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
   1793         ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
   1794         if (patch_index >= 0) {
   1795             sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
   1796             status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
   1797             mAudioPatches.removeItemsAt(patch_index);
   1798             patchRemoved = true;
   1799         }
   1800         mpClientInterface->closeInput(mInputs.keyAt(input_index));
   1801     }
   1802     mInputs.clear();
   1803     SoundTrigger::setCaptureState(false);
   1804     nextAudioPortGeneration();
   1805 
   1806     if (patchRemoved) {
   1807         mpClientInterface->onAudioPatchListUpdate();
   1808     }
   1809 }
   1810 
   1811 void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
   1812                                             int indexMin,
   1813                                             int indexMax)
   1814 {
   1815     ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
   1816     mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
   1817 
   1818     // initialize other private stream volumes which follow this one
   1819     for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
   1820         if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
   1821             continue;
   1822         }
   1823         mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
   1824     }
   1825 }
   1826 
   1827 status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
   1828                                                   int index,
   1829                                                   audio_devices_t device)
   1830 {
   1831 
   1832     if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
   1833             (index > mVolumeCurves->getVolumeIndexMax(stream))) {
   1834         return BAD_VALUE;
   1835     }
   1836     if (!audio_is_output_device(device)) {
   1837         return BAD_VALUE;
   1838     }
   1839 
   1840     // Force max volume if stream cannot be muted
   1841     if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
   1842 
   1843     ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
   1844           stream, device, index);
   1845 
   1846     // update other private stream volumes which follow this one
   1847     for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
   1848         if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
   1849             continue;
   1850         }
   1851         mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
   1852     }
   1853 
   1854     // update volume on all outputs and streams matching the following:
   1855     // - The requested stream (or a stream matching for volume control) is active on the output
   1856     // - The device (or devices) selected by the strategy corresponding to this stream includes
   1857     // the requested device
   1858     // - For non default requested device, currently selected device on the output is either the
   1859     // requested device or one of the devices selected by the strategy
   1860     // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
   1861     // no specific device volume value exists for currently selected device.
   1862     status_t status = NO_ERROR;
   1863     for (size_t i = 0; i < mOutputs.size(); i++) {
   1864         sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
   1865         audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
   1866         for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
   1867             if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
   1868                 continue;
   1869             }
   1870             if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
   1871                     (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
   1872                 continue;
   1873             }
   1874             routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
   1875             audio_devices_t curStreamDevice = getDeviceForStrategy(curStrategy, true /*fromCache*/);
   1876             if ((curStreamDevice & device) == 0) {
   1877                 continue;
   1878             }
   1879             bool applyDefault = false;
   1880             if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
   1881                 curStreamDevice |= device;
   1882             } else if (!mVolumeCurves->hasVolumeIndexForDevice(
   1883                     stream, Volume::getDeviceForVolume(curStreamDevice))) {
   1884                 applyDefault = true;
   1885             }
   1886 
   1887             if (applyDefault || ((curDevice & curStreamDevice) != 0)) {
   1888                 status_t volStatus =
   1889                         checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice);
   1890                 if (volStatus != NO_ERROR) {
   1891                     status = volStatus;
   1892                 }
   1893             }
   1894         }
   1895     }
   1896     return status;
   1897 }
   1898 
   1899 status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
   1900                                                       int *index,
   1901                                                       audio_devices_t device)
   1902 {
   1903     if (index == NULL) {
   1904         return BAD_VALUE;
   1905     }
   1906     if (!audio_is_output_device(device)) {
   1907         return BAD_VALUE;
   1908     }
   1909     // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
   1910     // the strategy the stream belongs to.
   1911     if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
   1912         device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
   1913     }
   1914     device = Volume::getDeviceForVolume(device);
   1915 
   1916     *index =  mVolumeCurves->getVolumeIndex(stream, device);
   1917     ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
   1918     return NO_ERROR;
   1919 }
   1920 
   1921 audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
   1922                                             const SortedVector<audio_io_handle_t>& outputs)
   1923 {
   1924     // select one output among several suitable for global effects.
   1925     // The priority is as follows:
   1926     // 1: An offloaded output. If the effect ends up not being offloadable,
   1927     //    AudioFlinger will invalidate the track and the offloaded output
   1928     //    will be closed causing the effect to be moved to a PCM output.
   1929     // 2: A deep buffer output
   1930     // 3: the first output in the list
   1931 
   1932     if (outputs.size() == 0) {
   1933         return 0;
   1934     }
   1935 
   1936     audio_io_handle_t outputOffloaded = 0;
   1937     audio_io_handle_t outputDeepBuffer = 0;
   1938 
   1939     for (size_t i = 0; i < outputs.size(); i++) {
   1940         sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
   1941         ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
   1942         if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
   1943             outputOffloaded = outputs[i];
   1944         }
   1945         if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
   1946             outputDeepBuffer = outputs[i];
   1947         }
   1948     }
   1949 
   1950     ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
   1951           outputOffloaded, outputDeepBuffer);
   1952     if (outputOffloaded != 0) {
   1953         return outputOffloaded;
   1954     }
   1955     if (outputDeepBuffer != 0) {
   1956         return outputDeepBuffer;
   1957     }
   1958 
   1959     return outputs[0];
   1960 }
   1961 
   1962 audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
   1963 {
   1964     // apply simple rule where global effects are attached to the same output as MUSIC streams
   1965 
   1966     routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
   1967     audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
   1968     SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
   1969 
   1970     audio_io_handle_t output = selectOutputForEffects(dstOutputs);
   1971     ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
   1972           output, (desc == NULL) ? "unspecified" : desc->name,  (desc == NULL) ? 0 : desc->flags);
   1973 
   1974     return output;
   1975 }
   1976 
   1977 status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
   1978                                 audio_io_handle_t io,
   1979                                 uint32_t strategy,
   1980                                 int session,
   1981                                 int id)
   1982 {
   1983     ssize_t index = mOutputs.indexOfKey(io);
   1984     if (index < 0) {
   1985         index = mInputs.indexOfKey(io);
   1986         if (index < 0) {
   1987             ALOGW("registerEffect() unknown io %d", io);
   1988             return INVALID_OPERATION;
   1989         }
   1990     }
   1991     return mEffects.registerEffect(desc, io, strategy, session, id);
   1992 }
   1993 
   1994 bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
   1995 {
   1996     bool active = false;
   1997     for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
   1998         if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
   1999             continue;
   2000         }
   2001         active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
   2002     }
   2003     return active;
   2004 }
   2005 
   2006 bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
   2007 {
   2008     return mOutputs.isStreamActiveRemotely(stream, inPastMs);
   2009 }
   2010 
   2011 bool AudioPolicyManager::isSourceActive(audio_source_t source) const
   2012 {
   2013     for (size_t i = 0; i < mInputs.size(); i++) {
   2014         const sp<AudioInputDescriptor>  inputDescriptor = mInputs.valueAt(i);
   2015         if (inputDescriptor->isSourceActive(source)) {
   2016             return true;
   2017         }
   2018     }
   2019     return false;
   2020 }
   2021 
   2022 // Register a list of custom mixes with their attributes and format.
   2023 // When a mix is registered, corresponding input and output profiles are
   2024 // added to the remote submix hw module. The profile contains only the
   2025 // parameters (sampling rate, format...) specified by the mix.
   2026 // The corresponding input remote submix device is also connected.
   2027 //
   2028 // When a remote submix device is connected, the address is checked to select the
   2029 // appropriate profile and the corresponding input or output stream is opened.
   2030 //
   2031 // When capture starts, getInputForAttr() will:
   2032 //  - 1 look for a mix matching the address passed in attribtutes tags if any
   2033 //  - 2 if none found, getDeviceForInputSource() will:
   2034 //     - 2.1 look for a mix matching the attributes source
   2035 //     - 2.2 if none found, default to device selection by policy rules
   2036 // At this time, the corresponding output remote submix device is also connected
   2037 // and active playback use cases can be transferred to this mix if needed when reconnecting
   2038 // after AudioTracks are invalidated
   2039 //
   2040 // When playback starts, getOutputForAttr() will:
   2041 //  - 1 look for a mix matching the address passed in attribtutes tags if any
   2042 //  - 2 if none found, look for a mix matching the attributes usage
   2043 //  - 3 if none found, default to device and output selection by policy rules.
   2044 
   2045 status_t AudioPolicyManager::registerPolicyMixes(Vector<AudioMix> mixes)
   2046 {
   2047     ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
   2048     status_t res = NO_ERROR;
   2049 
   2050     sp<HwModule> rSubmixModule;
   2051     // examine each mix's route type
   2052     for (size_t i = 0; i < mixes.size(); i++) {
   2053         // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
   2054         if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
   2055             res = INVALID_OPERATION;
   2056             break;
   2057         }
   2058         if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
   2059             // Loop back through "remote submix"
   2060             if (rSubmixModule == 0) {
   2061                 for (size_t j = 0; i < mHwModules.size(); j++) {
   2062                     if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
   2063                             && mHwModules[j]->mHandle != 0) {
   2064                         rSubmixModule = mHwModules[j];
   2065                         break;
   2066                     }
   2067                 }
   2068             }
   2069 
   2070             ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
   2071 
   2072             if (rSubmixModule == 0) {
   2073                 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration", i);
   2074                 res = INVALID_OPERATION;
   2075                 break;
   2076             }
   2077 
   2078             String8 address = mixes[i].mDeviceAddress;
   2079 
   2080             if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
   2081                 ALOGE(" Error registering mix %zu for address %s", i, address.string());
   2082                 res = INVALID_OPERATION;
   2083                 break;
   2084             }
   2085             audio_config_t outputConfig = mixes[i].mFormat;
   2086             audio_config_t inputConfig = mixes[i].mFormat;
   2087             // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
   2088             // stereo and let audio flinger do the channel conversion if needed.
   2089             outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
   2090             inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
   2091             rSubmixModule->addOutputProfile(address, &outputConfig,
   2092                     AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
   2093             rSubmixModule->addInputProfile(address, &inputConfig,
   2094                     AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
   2095 
   2096             if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
   2097                 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
   2098                         AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
   2099                         address.string(), "remote-submix");
   2100             } else {
   2101                 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
   2102                         AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
   2103                         address.string(), "remote-submix");
   2104             }
   2105         } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
   2106             String8 address = mixes[i].mDeviceAddress;
   2107             audio_devices_t device = mixes[i].mDeviceType;
   2108             ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
   2109                     i, mixes.size(), device, address.string());
   2110 
   2111             bool foundOutput = false;
   2112             for (size_t j = 0 ; j < mOutputs.size() ; j++) {
   2113                 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
   2114                 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
   2115                 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
   2116                         && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
   2117                         && (patch->mPatch.sinks[0].ext.device.type == device)
   2118                         && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
   2119                                 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
   2120                     if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
   2121                         res = INVALID_OPERATION;
   2122                     } else {
   2123                         foundOutput = true;
   2124                     }
   2125                     break;
   2126                 }
   2127             }
   2128 
   2129             if (res != NO_ERROR) {
   2130                 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
   2131                         i, device, address.string());
   2132                 res = INVALID_OPERATION;
   2133                 break;
   2134             } else if (!foundOutput) {
   2135                 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
   2136                         i, device, address.string());
   2137                 res = INVALID_OPERATION;
   2138                 break;
   2139             }
   2140         }
   2141     }
   2142     if (res != NO_ERROR) {
   2143         unregisterPolicyMixes(mixes);
   2144     }
   2145     return res;
   2146 }
   2147 
   2148 status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
   2149 {
   2150     ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
   2151     status_t res = NO_ERROR;
   2152     sp<HwModule> rSubmixModule;
   2153     // examine each mix's route type
   2154     for (size_t i = 0; i < mixes.size(); i++) {
   2155         if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
   2156 
   2157             if (rSubmixModule == 0) {
   2158                 for (size_t j = 0; i < mHwModules.size(); j++) {
   2159                     if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
   2160                             && mHwModules[j]->mHandle != 0) {
   2161                         rSubmixModule = mHwModules[j];
   2162                         break;
   2163                     }
   2164                 }
   2165             }
   2166             if (rSubmixModule == 0) {
   2167                 res = INVALID_OPERATION;
   2168                 continue;
   2169             }
   2170 
   2171             String8 address = mixes[i].mDeviceAddress;
   2172 
   2173             if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
   2174                 res = INVALID_OPERATION;
   2175                 continue;
   2176             }
   2177 
   2178             if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
   2179                     AUDIO_POLICY_DEVICE_STATE_AVAILABLE)  {
   2180                 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
   2181                         AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
   2182                         address.string(), "remote-submix");
   2183             }
   2184             if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
   2185                     AUDIO_POLICY_DEVICE_STATE_AVAILABLE)  {
   2186                 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
   2187                         AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
   2188                         address.string(), "remote-submix");
   2189             }
   2190             rSubmixModule->removeOutputProfile(address);
   2191             rSubmixModule->removeInputProfile(address);
   2192 
   2193         } if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
   2194             if (mPolicyMixes.unregisterMix(mixes[i].mDeviceAddress) != NO_ERROR) {
   2195                 res = INVALID_OPERATION;
   2196                 continue;
   2197             }
   2198         }
   2199     }
   2200     return res;
   2201 }
   2202 
   2203 
   2204 status_t AudioPolicyManager::dump(int fd)
   2205 {
   2206     const size_t SIZE = 256;
   2207     char buffer[SIZE];
   2208     String8 result;
   2209 
   2210     snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
   2211     result.append(buffer);
   2212 
   2213     snprintf(buffer, SIZE, " Primary Output: %d\n",
   2214              hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
   2215     result.append(buffer);
   2216     snprintf(buffer, SIZE, " Phone state: %d\n", mEngine->getPhoneState());
   2217     result.append(buffer);
   2218     snprintf(buffer, SIZE, " Force use for communications %d\n",
   2219              mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
   2220     result.append(buffer);
   2221     snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
   2222     result.append(buffer);
   2223     snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
   2224     result.append(buffer);
   2225     snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
   2226     result.append(buffer);
   2227     snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
   2228     result.append(buffer);
   2229     snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
   2230             mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
   2231     result.append(buffer);
   2232     snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
   2233             mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
   2234     result.append(buffer);
   2235     snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
   2236     result.append(buffer);
   2237     snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
   2238     result.append(buffer);
   2239 
   2240     write(fd, result.string(), result.size());
   2241 
   2242     mAvailableOutputDevices.dump(fd, String8("Available output"));
   2243     mAvailableInputDevices.dump(fd, String8("Available input"));
   2244     mHwModules.dump(fd);
   2245     mOutputs.dump(fd);
   2246     mInputs.dump(fd);
   2247     mVolumeCurves->dump(fd);
   2248     mEffects.dump(fd);
   2249     mAudioPatches.dump(fd);
   2250 
   2251     return NO_ERROR;
   2252 }
   2253 
   2254 // This function checks for the parameters which can be offloaded.
   2255 // This can be enhanced depending on the capability of the DSP and policy
   2256 // of the system.
   2257 bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
   2258 {
   2259     ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
   2260      " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
   2261      offloadInfo.sample_rate, offloadInfo.channel_mask,
   2262      offloadInfo.format,
   2263      offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
   2264      offloadInfo.has_video);
   2265 
   2266     if (mMasterMono) {
   2267         return false; // no offloading if mono is set.
   2268     }
   2269 
   2270     // Check if offload has been disabled
   2271     char propValue[PROPERTY_VALUE_MAX];
   2272     if (property_get("audio.offload.disable", propValue, "0")) {
   2273         if (atoi(propValue) != 0) {
   2274             ALOGV("offload disabled by audio.offload.disable=%s", propValue );
   2275             return false;
   2276         }
   2277     }
   2278 
   2279     // Check if stream type is music, then only allow offload as of now.
   2280     if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
   2281     {
   2282         ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
   2283         return false;
   2284     }
   2285 
   2286     //TODO: enable audio offloading with video when ready
   2287     const bool allowOffloadWithVideo =
   2288             property_get_bool("audio.offload.video", false /* default_value */);
   2289     if (offloadInfo.has_video && !allowOffloadWithVideo) {
   2290         ALOGV("isOffloadSupported: has_video == true, returning false");
   2291         return false;
   2292     }
   2293 
   2294     //If duration is less than minimum value defined in property, return false
   2295     if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
   2296         if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
   2297             ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
   2298             return false;
   2299         }
   2300     } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
   2301         ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
   2302         return false;
   2303     }
   2304 
   2305     // Do not allow offloading if one non offloadable effect is enabled. This prevents from
   2306     // creating an offloaded track and tearing it down immediately after start when audioflinger
   2307     // detects there is an active non offloadable effect.
   2308     // FIXME: We should check the audio session here but we do not have it in this context.
   2309     // This may prevent offloading in rare situations where effects are left active by apps
   2310     // in the background.
   2311     if (mEffects.isNonOffloadableEffectEnabled()) {
   2312         return false;
   2313     }
   2314 
   2315     // See if there is a profile to support this.
   2316     // AUDIO_DEVICE_NONE
   2317     sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
   2318                                             offloadInfo.sample_rate,
   2319                                             offloadInfo.format,
   2320                                             offloadInfo.channel_mask,
   2321                                             AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
   2322     ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
   2323     return (profile != 0);
   2324 }
   2325 
   2326 status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
   2327                                             audio_port_type_t type,
   2328                                             unsigned int *num_ports,
   2329                                             struct audio_port *ports,
   2330                                             unsigned int *generation)
   2331 {
   2332     if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
   2333             generation == NULL) {
   2334         return BAD_VALUE;
   2335     }
   2336     ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
   2337     if (ports == NULL) {
   2338         *num_ports = 0;
   2339     }
   2340 
   2341     size_t portsWritten = 0;
   2342     size_t portsMax = *num_ports;
   2343     *num_ports = 0;
   2344     if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
   2345         // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
   2346         // as they are used by stub HALs by convention
   2347         if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
   2348             for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
   2349                 if (mAvailableOutputDevices[i]->type() == AUDIO_DEVICE_OUT_STUB) {
   2350                     continue;
   2351                 }
   2352                 if (portsWritten < portsMax) {
   2353                     mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
   2354                 }
   2355                 (*num_ports)++;
   2356             }
   2357         }
   2358         if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
   2359             for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
   2360                 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_STUB) {
   2361                     continue;
   2362                 }
   2363                 if (portsWritten < portsMax) {
   2364                     mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
   2365                 }
   2366                 (*num_ports)++;
   2367             }
   2368         }
   2369     }
   2370     if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
   2371         if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
   2372             for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
   2373                 mInputs[i]->toAudioPort(&ports[portsWritten++]);
   2374             }
   2375             *num_ports += mInputs.size();
   2376         }
   2377         if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
   2378             size_t numOutputs = 0;
   2379             for (size_t i = 0; i < mOutputs.size(); i++) {
   2380                 if (!mOutputs[i]->isDuplicated()) {
   2381                     numOutputs++;
   2382                     if (portsWritten < portsMax) {
   2383                         mOutputs[i]->toAudioPort(&ports[portsWritten++]);
   2384                     }
   2385                 }
   2386             }
   2387             *num_ports += numOutputs;
   2388         }
   2389     }
   2390     *generation = curAudioPortGeneration();
   2391     ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
   2392     return NO_ERROR;
   2393 }
   2394 
   2395 status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
   2396 {
   2397     return NO_ERROR;
   2398 }
   2399 
   2400 status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
   2401                                                audio_patch_handle_t *handle,
   2402                                                uid_t uid)
   2403 {
   2404     ALOGV("createAudioPatch()");
   2405 
   2406     if (handle == NULL || patch == NULL) {
   2407         return BAD_VALUE;
   2408     }
   2409     ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
   2410 
   2411     if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
   2412             patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
   2413         return BAD_VALUE;
   2414     }
   2415     // only one source per audio patch supported for now
   2416     if (patch->num_sources > 1) {
   2417         return INVALID_OPERATION;
   2418     }
   2419 
   2420     if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
   2421         return INVALID_OPERATION;
   2422     }
   2423     for (size_t i = 0; i < patch->num_sinks; i++) {
   2424         if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
   2425             return INVALID_OPERATION;
   2426         }
   2427     }
   2428 
   2429     sp<AudioPatch> patchDesc;
   2430     ssize_t index = mAudioPatches.indexOfKey(*handle);
   2431 
   2432     ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
   2433                                                            patch->sources[0].role,
   2434                                                            patch->sources[0].type);
   2435 #if LOG_NDEBUG == 0
   2436     for (size_t i = 0; i < patch->num_sinks; i++) {
   2437         ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
   2438                                                              patch->sinks[i].role,
   2439                                                              patch->sinks[i].type);
   2440     }
   2441 #endif
   2442 
   2443     if (index >= 0) {
   2444         patchDesc = mAudioPatches.valueAt(index);
   2445         ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
   2446                                                                   mUidCached, patchDesc->mUid, uid);
   2447         if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
   2448             return INVALID_OPERATION;
   2449         }
   2450     } else {
   2451         *handle = AUDIO_PATCH_HANDLE_NONE;
   2452     }
   2453 
   2454     if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
   2455         sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
   2456         if (outputDesc == NULL) {
   2457             ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
   2458             return BAD_VALUE;
   2459         }
   2460         ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
   2461                                                 outputDesc->mIoHandle);
   2462         if (patchDesc != 0) {
   2463             if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
   2464                 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
   2465                                           patchDesc->mPatch.sources[0].id, patch->sources[0].id);
   2466                 return BAD_VALUE;
   2467             }
   2468         }
   2469         DeviceVector devices;
   2470         for (size_t i = 0; i < patch->num_sinks; i++) {
   2471             // Only support mix to devices connection
   2472             // TODO add support for mix to mix connection
   2473             if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
   2474                 ALOGV("createAudioPatch() source mix but sink is not a device");
   2475                 return INVALID_OPERATION;
   2476             }
   2477             sp<DeviceDescriptor> devDesc =
   2478                     mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
   2479             if (devDesc == 0) {
   2480                 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
   2481                 return BAD_VALUE;
   2482             }
   2483 
   2484             if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
   2485                                                            devDesc->mAddress,
   2486                                                            patch->sources[0].sample_rate,
   2487                                                            NULL,  // updatedSamplingRate
   2488                                                            patch->sources[0].format,
   2489                                                            NULL,  // updatedFormat
   2490                                                            patch->sources[0].channel_mask,
   2491                                                            NULL,  // updatedChannelMask
   2492                                                            AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
   2493                 ALOGV("createAudioPatch() profile not supported for device %08x",
   2494                         devDesc->type());
   2495                 return INVALID_OPERATION;
   2496             }
   2497             devices.add(devDesc);
   2498         }
   2499         if (devices.size() == 0) {
   2500             return INVALID_OPERATION;
   2501         }
   2502 
   2503         // TODO: reconfigure output format and channels here
   2504         ALOGV("createAudioPatch() setting device %08x on output %d",
   2505               devices.types(), outputDesc->mIoHandle);
   2506         setOutputDevice(outputDesc, devices.types(), true, 0, handle);
   2507         index = mAudioPatches.indexOfKey(*handle);
   2508         if (index >= 0) {
   2509             if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
   2510                 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
   2511             }
   2512             patchDesc = mAudioPatches.valueAt(index);
   2513             patchDesc->mUid = uid;
   2514             ALOGV("createAudioPatch() success");
   2515         } else {
   2516             ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
   2517             return INVALID_OPERATION;
   2518         }
   2519     } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
   2520         if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
   2521             // input device to input mix connection
   2522             // only one sink supported when connecting an input device to a mix
   2523             if (patch->num_sinks > 1) {
   2524                 return INVALID_OPERATION;
   2525             }
   2526             sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
   2527             if (inputDesc == NULL) {
   2528                 return BAD_VALUE;
   2529             }
   2530             if (patchDesc != 0) {
   2531                 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
   2532                     return BAD_VALUE;
   2533                 }
   2534             }
   2535             sp<DeviceDescriptor> devDesc =
   2536                     mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
   2537             if (devDesc == 0) {
   2538                 return BAD_VALUE;
   2539             }
   2540 
   2541             if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
   2542                                                           devDesc->mAddress,
   2543                                                           patch->sinks[0].sample_rate,
   2544                                                           NULL, /*updatedSampleRate*/
   2545                                                           patch->sinks[0].format,
   2546                                                           NULL, /*updatedFormat*/
   2547                                                           patch->sinks[0].channel_mask,
   2548                                                           NULL, /*updatedChannelMask*/
   2549                                                           // FIXME for the parameter type,
   2550                                                           // and the NONE
   2551                                                           (audio_output_flags_t)
   2552                                                             AUDIO_INPUT_FLAG_NONE)) {
   2553                 return INVALID_OPERATION;
   2554             }
   2555             // TODO: reconfigure output format and channels here
   2556             ALOGV("createAudioPatch() setting device %08x on output %d",
   2557                                                   devDesc->type(), inputDesc->mIoHandle);
   2558             setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
   2559             index = mAudioPatches.indexOfKey(*handle);
   2560             if (index >= 0) {
   2561                 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
   2562                     ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
   2563                 }
   2564                 patchDesc = mAudioPatches.valueAt(index);
   2565                 patchDesc->mUid = uid;
   2566                 ALOGV("createAudioPatch() success");
   2567             } else {
   2568                 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
   2569                 return INVALID_OPERATION;
   2570             }
   2571         } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
   2572             // device to device connection
   2573             if (patchDesc != 0) {
   2574                 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
   2575                     return BAD_VALUE;
   2576                 }
   2577             }
   2578             sp<DeviceDescriptor> srcDeviceDesc =
   2579                     mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
   2580             if (srcDeviceDesc == 0) {
   2581                 return BAD_VALUE;
   2582             }
   2583 
   2584             //update source and sink with our own data as the data passed in the patch may
   2585             // be incomplete.
   2586             struct audio_patch newPatch = *patch;
   2587             srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
   2588 
   2589             for (size_t i = 0; i < patch->num_sinks; i++) {
   2590                 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
   2591                     ALOGV("createAudioPatch() source device but one sink is not a device");
   2592                     return INVALID_OPERATION;
   2593                 }
   2594 
   2595                 sp<DeviceDescriptor> sinkDeviceDesc =
   2596                         mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
   2597                 if (sinkDeviceDesc == 0) {
   2598                     return BAD_VALUE;
   2599                 }
   2600                 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
   2601 
   2602                 // create a software bridge in PatchPanel if:
   2603                 // - source and sink devices are on differnt HW modules OR
   2604                 // - audio HAL version is < 3.0
   2605                 if ((srcDeviceDesc->getModuleHandle() != sinkDeviceDesc->getModuleHandle()) ||
   2606                         (srcDeviceDesc->mModule->getHalVersion() < AUDIO_DEVICE_API_VERSION_3_0)) {
   2607                     // support only one sink device for now to simplify output selection logic
   2608                     if (patch->num_sinks > 1) {
   2609                         return INVALID_OPERATION;
   2610                     }
   2611                     SortedVector<audio_io_handle_t> outputs =
   2612                                             getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
   2613                     // if the sink device is reachable via an opened output stream, request to go via
   2614                     // this output stream by adding a second source to the patch description
   2615                     audio_io_handle_t output = selectOutput(outputs,
   2616                                                             AUDIO_OUTPUT_FLAG_NONE,
   2617                                                             AUDIO_FORMAT_INVALID);
   2618                     if (output != AUDIO_IO_HANDLE_NONE) {
   2619                         sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
   2620                         if (outputDesc->isDuplicated()) {
   2621                             return INVALID_OPERATION;
   2622                         }
   2623                         outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
   2624                         newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
   2625                         newPatch.num_sources = 2;
   2626                     }
   2627                 }
   2628             }
   2629             // TODO: check from routing capabilities in config file and other conflicting patches
   2630 
   2631             audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
   2632             if (index >= 0) {
   2633                 afPatchHandle = patchDesc->mAfPatchHandle;
   2634             }
   2635 
   2636             status_t status = mpClientInterface->createAudioPatch(&newPatch,
   2637                                                                   &afPatchHandle,
   2638                                                                   0);
   2639             ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
   2640                                                                   status, afPatchHandle);
   2641             if (status == NO_ERROR) {
   2642                 if (index < 0) {
   2643                     patchDesc = new AudioPatch(&newPatch, uid);
   2644                     addAudioPatch(patchDesc->mHandle, patchDesc);
   2645                 } else {
   2646                     patchDesc->mPatch = newPatch;
   2647                 }
   2648                 patchDesc->mAfPatchHandle = afPatchHandle;
   2649                 *handle = patchDesc->mHandle;
   2650                 nextAudioPortGeneration();
   2651                 mpClientInterface->onAudioPatchListUpdate();
   2652             } else {
   2653                 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
   2654                 status);
   2655                 return INVALID_OPERATION;
   2656             }
   2657         } else {
   2658             return BAD_VALUE;
   2659         }
   2660     } else {
   2661         return BAD_VALUE;
   2662     }
   2663     return NO_ERROR;
   2664 }
   2665 
   2666 status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
   2667                                                   uid_t uid)
   2668 {
   2669     ALOGV("releaseAudioPatch() patch %d", handle);
   2670 
   2671     ssize_t index = mAudioPatches.indexOfKey(handle);
   2672 
   2673     if (index < 0) {
   2674         return BAD_VALUE;
   2675     }
   2676     sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
   2677     ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
   2678           mUidCached, patchDesc->mUid, uid);
   2679     if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
   2680         return INVALID_OPERATION;
   2681     }
   2682 
   2683     struct audio_patch *patch = &patchDesc->mPatch;
   2684     patchDesc->mUid = mUidCached;
   2685     if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
   2686         sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
   2687         if (outputDesc == NULL) {
   2688             ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
   2689             return BAD_VALUE;
   2690         }
   2691 
   2692         setOutputDevice(outputDesc,
   2693                         getNewOutputDevice(outputDesc, true /*fromCache*/),
   2694                        true,
   2695                        0,
   2696                        NULL);
   2697     } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
   2698         if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
   2699             sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
   2700             if (inputDesc == NULL) {
   2701                 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
   2702                 return BAD_VALUE;
   2703             }
   2704             setInputDevice(inputDesc->mIoHandle,
   2705                            getNewInputDevice(inputDesc->mIoHandle),
   2706                            true,
   2707                            NULL);
   2708         } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
   2709             audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
   2710             status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
   2711             ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
   2712                                                               status, patchDesc->mAfPatchHandle);
   2713             removeAudioPatch(patchDesc->mHandle);
   2714             nextAudioPortGeneration();
   2715             mpClientInterface->onAudioPatchListUpdate();
   2716         } else {
   2717             return BAD_VALUE;
   2718         }
   2719     } else {
   2720         return BAD_VALUE;
   2721     }
   2722     return NO_ERROR;
   2723 }
   2724 
   2725 status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
   2726                                               struct audio_patch *patches,
   2727                                               unsigned int *generation)
   2728 {
   2729     if (generation == NULL) {
   2730         return BAD_VALUE;
   2731     }
   2732     *generation = curAudioPortGeneration();
   2733     return mAudioPatches.listAudioPatches(num_patches, patches);
   2734 }
   2735 
   2736 status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
   2737 {
   2738     ALOGV("setAudioPortConfig()");
   2739 
   2740     if (config == NULL) {
   2741         return BAD_VALUE;
   2742     }
   2743     ALOGV("setAudioPortConfig() on port handle %d", config->id);
   2744     // Only support gain configuration for now
   2745     if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
   2746         return INVALID_OPERATION;
   2747     }
   2748 
   2749     sp<AudioPortConfig> audioPortConfig;
   2750     if (config->type == AUDIO_PORT_TYPE_MIX) {
   2751         if (config->role == AUDIO_PORT_ROLE_SOURCE) {
   2752             sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
   2753             if (outputDesc == NULL) {
   2754                 return BAD_VALUE;
   2755             }
   2756             ALOG_ASSERT(!outputDesc->isDuplicated(),
   2757                         "setAudioPortConfig() called on duplicated output %d",
   2758                         outputDesc->mIoHandle);
   2759             audioPortConfig = outputDesc;
   2760         } else if (config->role == AUDIO_PORT_ROLE_SINK) {
   2761             sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
   2762             if (inputDesc == NULL) {
   2763                 return BAD_VALUE;
   2764             }
   2765             audioPortConfig = inputDesc;
   2766         } else {
   2767             return BAD_VALUE;
   2768         }
   2769     } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
   2770         sp<DeviceDescriptor> deviceDesc;
   2771         if (config->role == AUDIO_PORT_ROLE_SOURCE) {
   2772             deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
   2773         } else if (config->role == AUDIO_PORT_ROLE_SINK) {
   2774             deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
   2775         } else {
   2776             return BAD_VALUE;
   2777         }
   2778         if (deviceDesc == NULL) {
   2779             return BAD_VALUE;
   2780         }
   2781         audioPortConfig = deviceDesc;
   2782     } else {
   2783         return BAD_VALUE;
   2784     }
   2785 
   2786     struct audio_port_config backupConfig;
   2787     status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
   2788     if (status == NO_ERROR) {
   2789         struct audio_port_config newConfig;
   2790         audioPortConfig->toAudioPortConfig(&newConfig, config);
   2791         status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
   2792     }
   2793     if (status != NO_ERROR) {
   2794         audioPortConfig->applyAudioPortConfig(&backupConfig);
   2795     }
   2796 
   2797     return status;
   2798 }
   2799 
   2800 void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
   2801 {
   2802     clearAudioSources(uid);
   2803     clearAudioPatches(uid);
   2804     clearSessionRoutes(uid);
   2805 }
   2806 
   2807 void AudioPolicyManager::clearAudioPatches(uid_t uid)
   2808 {
   2809     for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--)  {
   2810         sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
   2811         if (patchDesc->mUid == uid) {
   2812             releaseAudioPatch(mAudioPatches.keyAt(i), uid);
   2813         }
   2814     }
   2815 }
   2816 
   2817 void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
   2818                                             audio_io_handle_t ouptutToSkip)
   2819 {
   2820     audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
   2821     SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
   2822     for (size_t j = 0; j < mOutputs.size(); j++) {
   2823         if (mOutputs.keyAt(j) == ouptutToSkip) {
   2824             continue;
   2825         }
   2826         sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
   2827         if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
   2828             continue;
   2829         }
   2830         // If the default device for this strategy is on another output mix,
   2831         // invalidate all tracks in this strategy to force re connection.
   2832         // Otherwise select new device on the output mix.
   2833         if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
   2834             for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
   2835                 if (getStrategy((audio_stream_type_t)stream) == strategy) {
   2836                     mpClientInterface->invalidateStream((audio_stream_type_t)stream);
   2837                 }
   2838             }
   2839         } else {
   2840             audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
   2841             setOutputDevice(outputDesc, newDevice, false);
   2842         }
   2843     }
   2844 }
   2845 
   2846 void AudioPolicyManager::clearSessionRoutes(uid_t uid)
   2847 {
   2848     // remove output routes associated with this uid
   2849     SortedVector<routing_strategy> affectedStrategies;
   2850     for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--)  {
   2851         sp<SessionRoute> route = mOutputRoutes.valueAt(i);
   2852         if (route->mUid == uid) {
   2853             mOutputRoutes.removeItemsAt(i);
   2854             if (route->mDeviceDescriptor != 0) {
   2855                 affectedStrategies.add(getStrategy(route->mStreamType));
   2856             }
   2857         }
   2858     }
   2859     // reroute outputs if necessary
   2860     for (size_t i = 0; i < affectedStrategies.size(); i++) {
   2861         checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
   2862     }
   2863 
   2864     // remove input routes associated with this uid
   2865     SortedVector<audio_source_t> affectedSources;
   2866     for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--)  {
   2867         sp<SessionRoute> route = mInputRoutes.valueAt(i);
   2868         if (route->mUid == uid) {
   2869             mInputRoutes.removeItemsAt(i);
   2870             if (route->mDeviceDescriptor != 0) {
   2871                 affectedSources.add(route->mSource);
   2872             }
   2873         }
   2874     }
   2875     // reroute inputs if necessary
   2876     SortedVector<audio_io_handle_t> inputsToClose;
   2877     for (size_t i = 0; i < mInputs.size(); i++) {
   2878         sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
   2879         if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
   2880             inputsToClose.add(inputDesc->mIoHandle);
   2881         }
   2882     }
   2883     for (size_t i = 0; i < inputsToClose.size(); i++) {
   2884         closeInput(inputsToClose[i]);
   2885     }
   2886 }
   2887 
   2888 void AudioPolicyManager::clearAudioSources(uid_t uid)
   2889 {
   2890     for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--)  {
   2891         sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
   2892         if (sourceDesc->mUid == uid) {
   2893             stopAudioSource(mAudioSources.keyAt(i));
   2894         }
   2895     }
   2896 }
   2897 
   2898 status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
   2899                                        audio_io_handle_t *ioHandle,
   2900                                        audio_devices_t *device)
   2901 {
   2902     *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
   2903     *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
   2904     *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
   2905 
   2906     return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
   2907 }
   2908 
   2909 status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
   2910                                   const audio_attributes_t *attributes,
   2911                                   audio_io_handle_t *handle,
   2912                                   uid_t uid)
   2913 {
   2914     ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
   2915     if (source == NULL || attributes == NULL || handle == NULL) {
   2916         return BAD_VALUE;
   2917     }
   2918 
   2919     *handle = AUDIO_IO_HANDLE_NONE;
   2920 
   2921     if (source->role != AUDIO_PORT_ROLE_SOURCE ||
   2922             source->type != AUDIO_PORT_TYPE_DEVICE) {
   2923         ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
   2924         return INVALID_OPERATION;
   2925     }
   2926 
   2927     sp<DeviceDescriptor> srcDeviceDesc =
   2928             mAvailableInputDevices.getDevice(source->ext.device.type,
   2929                                               String8(source->ext.device.address));
   2930     if (srcDeviceDesc == 0) {
   2931         ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
   2932         return BAD_VALUE;
   2933     }
   2934     sp<AudioSourceDescriptor> sourceDesc =
   2935             new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
   2936 
   2937     struct audio_patch dummyPatch;
   2938     sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
   2939     sourceDesc->mPatchDesc = patchDesc;
   2940 
   2941     status_t status = connectAudioSource(sourceDesc);
   2942     if (status == NO_ERROR) {
   2943         mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
   2944         *handle = sourceDesc->getHandle();
   2945     }
   2946     return status;
   2947 }
   2948 
   2949 status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
   2950 {
   2951     ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
   2952 
   2953     // make sure we only have one patch per source.
   2954     disconnectAudioSource(sourceDesc);
   2955 
   2956     routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
   2957     audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
   2958     sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
   2959 
   2960     audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
   2961     sp<DeviceDescriptor> sinkDeviceDesc =
   2962             mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
   2963 
   2964     audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
   2965     struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
   2966 
   2967     if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
   2968             sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
   2969             srcDeviceDesc->getAudioPort()->mModule->getHalVersion() >= AUDIO_DEVICE_API_VERSION_3_0 &&
   2970             srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
   2971         ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
   2972         //   create patch between src device and output device
   2973         //   create Hwoutput and add to mHwOutputs
   2974     } else {
   2975         SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
   2976         audio_io_handle_t output =
   2977                 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
   2978         if (output == AUDIO_IO_HANDLE_NONE) {
   2979             ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
   2980             return INVALID_OPERATION;
   2981         }
   2982         sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
   2983         if (outputDesc->isDuplicated()) {
   2984             ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
   2985             return INVALID_OPERATION;
   2986         }
   2987         // create a special patch with no sink and two sources:
   2988         // - the second source indicates to PatchPanel through which output mix this patch should
   2989         // be connected as well as the stream type for volume control
   2990         // - the sink is defined by whatever output device is currently selected for the output
   2991         // though which this patch is routed.
   2992         patch->num_sinks = 0;
   2993         patch->num_sources = 2;
   2994         srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
   2995         outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
   2996         patch->sources[1].ext.mix.usecase.stream = stream;
   2997         status_t status = mpClientInterface->createAudioPatch(patch,
   2998                                                               &afPatchHandle,
   2999                                                               0);
   3000         ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
   3001                                                               status, afPatchHandle);
   3002         if (status != NO_ERROR) {
   3003             ALOGW("%s patch panel could not connect device patch, error %d",
   3004                   __FUNCTION__, status);
   3005             return INVALID_OPERATION;
   3006         }
   3007         uint32_t delayMs = 0;
   3008         status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
   3009 
   3010         if (status != NO_ERROR) {
   3011             mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
   3012             return status;
   3013         }
   3014         sourceDesc->mSwOutput = outputDesc;
   3015         if (delayMs != 0) {
   3016             usleep(delayMs * 1000);
   3017         }
   3018     }
   3019 
   3020     sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
   3021     addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
   3022 
   3023     return NO_ERROR;
   3024 }
   3025 
   3026 status_t AudioPolicyManager::stopAudioSource(audio_io_handle_t handle __unused)
   3027 {
   3028     sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
   3029     ALOGV("%s handle %d", __FUNCTION__, handle);
   3030     if (sourceDesc == 0) {
   3031         ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
   3032         return BAD_VALUE;
   3033     }
   3034     status_t status = disconnectAudioSource(sourceDesc);
   3035 
   3036     mAudioSources.removeItem(handle);
   3037     return status;
   3038 }
   3039 
   3040 status_t AudioPolicyManager::setMasterMono(bool mono)
   3041 {
   3042     if (mMasterMono == mono) {
   3043         return NO_ERROR;
   3044     }
   3045     mMasterMono = mono;
   3046     // if enabling mono we close all offloaded devices, which will invalidate the
   3047     // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
   3048     // for recreating the new AudioTrack as non-offloaded PCM.
   3049     //
   3050     // If disabling mono, we leave all tracks as is: we don't know which clients
   3051     // and tracks are able to be recreated as offloaded. The next "song" should
   3052     // play back offloaded.
   3053     if (mMasterMono) {
   3054         Vector<audio_io_handle_t> offloaded;
   3055         for (size_t i = 0; i < mOutputs.size(); ++i) {
   3056             sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
   3057             if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
   3058                 offloaded.push(desc->mIoHandle);
   3059             }
   3060         }
   3061         for (size_t i = 0; i < offloaded.size(); ++i) {
   3062             closeOutput(offloaded[i]);
   3063         }
   3064     }
   3065     // update master mono for all remaining outputs
   3066     for (size_t i = 0; i < mOutputs.size(); ++i) {
   3067         updateMono(mOutputs.keyAt(i));
   3068     }
   3069     return NO_ERROR;
   3070 }
   3071 
   3072 status_t AudioPolicyManager::getMasterMono(bool *mono)
   3073 {
   3074     *mono = mMasterMono;
   3075     return NO_ERROR;
   3076 }
   3077 
   3078 status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
   3079 {
   3080     ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
   3081 
   3082     sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
   3083     if (patchDesc == 0) {
   3084         ALOGW("%s source has no patch with handle %d", __FUNCTION__,
   3085               sourceDesc->mPatchDesc->mHandle);
   3086         return BAD_VALUE;
   3087     }
   3088     removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
   3089 
   3090     audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
   3091     sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
   3092     if (swOutputDesc != 0) {
   3093         stopSource(swOutputDesc, stream, false);
   3094         mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
   3095     } else {
   3096         sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
   3097         if (hwOutputDesc != 0) {
   3098           //   release patch between src device and output device
   3099           //   close Hwoutput and remove from mHwOutputs
   3100         } else {
   3101             ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
   3102         }
   3103     }
   3104     return NO_ERROR;
   3105 }
   3106 
   3107 sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
   3108         audio_io_handle_t output, routing_strategy strategy)
   3109 {
   3110     sp<AudioSourceDescriptor> source;
   3111     for (size_t i = 0; i < mAudioSources.size(); i++)  {
   3112         sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
   3113         routing_strategy sourceStrategy =
   3114                 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
   3115         sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
   3116         if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
   3117             source = sourceDesc;
   3118             break;
   3119         }
   3120     }
   3121     return source;
   3122 }
   3123 
   3124 // ----------------------------------------------------------------------------
   3125 // AudioPolicyManager
   3126 // ----------------------------------------------------------------------------
   3127 uint32_t AudioPolicyManager::nextAudioPortGeneration()
   3128 {
   3129     return android_atomic_inc(&mAudioPortGeneration);
   3130 }
   3131 
   3132 AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
   3133     :
   3134 #ifdef AUDIO_POLICY_TEST
   3135     Thread(false),
   3136 #endif //AUDIO_POLICY_TEST
   3137     mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
   3138     mA2dpSuspended(false),
   3139     mAudioPortGeneration(1),
   3140     mBeaconMuteRefCount(0),
   3141     mBeaconPlayingRefCount(0),
   3142     mBeaconMuted(false),
   3143     mTtsOutputAvailable(false),
   3144     mMasterMono(false)
   3145 {
   3146     mUidCached = getuid();
   3147     mpClientInterface = clientInterface;
   3148 
   3149     // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
   3150     // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
   3151     // Note: remove also speaker_drc_enabled from global configuration of XML config file.
   3152     bool speakerDrcEnabled = false;
   3153 
   3154 #ifdef USE_XML_AUDIO_POLICY_CONF
   3155     mVolumeCurves = new VolumeCurvesCollection();
   3156     AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
   3157                              mDefaultOutputDevice, speakerDrcEnabled,
   3158                              static_cast<VolumeCurvesCollection *>(mVolumeCurves));
   3159     PolicySerializer serializer;
   3160     if (serializer.deserialize(AUDIO_POLICY_XML_CONFIG_FILE, config) != NO_ERROR) {
   3161 #else
   3162     mVolumeCurves = new StreamDescriptorCollection();
   3163     AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
   3164                              mDefaultOutputDevice, speakerDrcEnabled);
   3165     if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
   3166             (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
   3167 #endif
   3168         ALOGE("could not load audio policy configuration file, setting defaults");
   3169         config.setDefault();
   3170     }
   3171     // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
   3172     mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
   3173 
   3174     // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
   3175     audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
   3176     if (!engineInstance) {
   3177         ALOGE("%s:  Could not get an instance of policy engine", __FUNCTION__);
   3178         return;
   3179     }
   3180     // Retrieve the Policy Manager Interface
   3181     mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
   3182     if (mEngine == NULL) {
   3183         ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
   3184         return;
   3185     }
   3186     mEngine->setObserver(this);
   3187     status_t status = mEngine->initCheck();
   3188     ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
   3189 
   3190     // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
   3191     // open all output streams needed to access attached devices
   3192     audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
   3193     audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
   3194     for (size_t i = 0; i < mHwModules.size(); i++) {
   3195         mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
   3196         if (mHwModules[i]->mHandle == 0) {
   3197             ALOGW("could not open HW module %s", mHwModules[i]->getName());
   3198             continue;
   3199         }
   3200         // open all output streams needed to access attached devices
   3201         // except for direct output streams that are only opened when they are actually
   3202         // required by an app.
   3203         // This also validates mAvailableOutputDevices list
   3204         for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
   3205         {
   3206             const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
   3207 
   3208             if (!outProfile->hasSupportedDevices()) {
   3209                 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
   3210                 continue;
   3211             }
   3212             if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
   3213                 mTtsOutputAvailable = true;
   3214             }
   3215 
   3216             if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
   3217                 continue;
   3218             }
   3219             audio_devices_t profileType = outProfile->getSupportedDevicesType();
   3220             if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
   3221                 profileType = mDefaultOutputDevice->type();
   3222             } else {
   3223                 // chose first device present in profile's SupportedDevices also part of
   3224                 // outputDeviceTypes
   3225                 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
   3226             }
   3227             if ((profileType & outputDeviceTypes) == 0) {
   3228                 continue;
   3229             }
   3230             sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
   3231                                                                                  mpClientInterface);
   3232             const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
   3233             const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
   3234             String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
   3235                     : String8("");
   3236 
   3237             outputDesc->mDevice = profileType;
   3238             audio_config_t config = AUDIO_CONFIG_INITIALIZER;
   3239             config.sample_rate = outputDesc->mSamplingRate;
   3240             config.channel_mask = outputDesc->mChannelMask;
   3241             config.format = outputDesc->mFormat;
   3242             audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
   3243             status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
   3244                                                             &output,
   3245                                                             &config,
   3246                                                             &outputDesc->mDevice,
   3247                                                             address,
   3248                                                             &outputDesc->mLatency,
   3249                                                             outputDesc->mFlags);
   3250 
   3251             if (status != NO_ERROR) {
   3252                 ALOGW("Cannot open output stream for device %08x on hw module %s",
   3253                       outputDesc->mDevice,
   3254                       mHwModules[i]->getName());
   3255             } else {
   3256                 outputDesc->mSamplingRate = config.sample_rate;
   3257                 outputDesc->mChannelMask = config.channel_mask;
   3258                 outputDesc->mFormat = config.format;
   3259 
   3260                 for (size_t k = 0; k  < supportedDevices.size(); k++) {
   3261                     ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
   3262                     // give a valid ID to an attached device once confirmed it is reachable
   3263                     if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
   3264                         mAvailableOutputDevices[index]->attach(mHwModules[i]);
   3265                     }
   3266                 }
   3267                 if (mPrimaryOutput == 0 &&
   3268                         outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
   3269                     mPrimaryOutput = outputDesc;
   3270                 }
   3271                 addOutput(output, outputDesc);
   3272                 setOutputDevice(outputDesc,
   3273                                 outputDesc->mDevice,
   3274                                 true,
   3275                                 0,
   3276                                 NULL,
   3277                                 address.string());
   3278             }
   3279         }
   3280         // open input streams needed to access attached devices to validate
   3281         // mAvailableInputDevices list
   3282         for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
   3283         {
   3284             const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
   3285 
   3286             if (!inProfile->hasSupportedDevices()) {
   3287                 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
   3288                 continue;
   3289             }
   3290             // chose first device present in profile's SupportedDevices also part of
   3291             // inputDeviceTypes
   3292             audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
   3293 
   3294             if ((profileType & inputDeviceTypes) == 0) {
   3295                 continue;
   3296             }
   3297             sp<AudioInputDescriptor> inputDesc =
   3298                     new AudioInputDescriptor(inProfile);
   3299 
   3300             inputDesc->mDevice = profileType;
   3301 
   3302             // find the address
   3303             DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
   3304             //   the inputs vector must be of size 1, but we don't want to crash here
   3305             String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
   3306                     : String8("");
   3307             ALOGV("  for input device 0x%x using address %s", profileType, address.string());
   3308             ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
   3309 
   3310             audio_config_t config = AUDIO_CONFIG_INITIALIZER;
   3311             config.sample_rate = inputDesc->mSamplingRate;
   3312             config.channel_mask = inputDesc->mChannelMask;
   3313             config.format = inputDesc->mFormat;
   3314             audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
   3315             status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
   3316                                                            &input,
   3317                                                            &config,
   3318                                                            &inputDesc->mDevice,
   3319                                                            address,
   3320                                                            AUDIO_SOURCE_MIC,
   3321                                                            AUDIO_INPUT_FLAG_NONE);
   3322 
   3323             if (status == NO_ERROR) {
   3324                 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
   3325                 for (size_t k = 0; k  < supportedDevices.size(); k++) {
   3326                     ssize_t index =  mAvailableInputDevices.indexOf(supportedDevices[k]);
   3327                     // give a valid ID to an attached device once confirmed it is reachable
   3328                     if (index >= 0) {
   3329                         sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
   3330                         if (!devDesc->isAttached()) {
   3331                             devDesc->attach(mHwModules[i]);
   3332                             devDesc->importAudioPort(inProfile);
   3333                         }
   3334                     }
   3335                 }
   3336                 mpClientInterface->closeInput(input);
   3337             } else {
   3338                 ALOGW("Cannot open input stream for device %08x on hw module %s",
   3339                       inputDesc->mDevice,
   3340                       mHwModules[i]->getName());
   3341             }
   3342         }
   3343     }
   3344     // make sure all attached devices have been allocated a unique ID
   3345     for (size_t i = 0; i  < mAvailableOutputDevices.size();) {
   3346         if (!mAvailableOutputDevices[i]->isAttached()) {
   3347             ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
   3348             mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
   3349             continue;
   3350         }
   3351         // The device is now validated and can be appended to the available devices of the engine
   3352         mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
   3353                                           AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
   3354         i++;
   3355     }
   3356     for (size_t i = 0; i  < mAvailableInputDevices.size();) {
   3357         if (!mAvailableInputDevices[i]->isAttached()) {
   3358             ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
   3359             mAvailableInputDevices.remove(mAvailableInputDevices[i]);
   3360             continue;
   3361         }
   3362         // The device is now validated and can be appended to the available devices of the engine
   3363         mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
   3364                                           AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
   3365         i++;
   3366     }
   3367     // make sure default device is reachable
   3368     if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
   3369         ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
   3370     }
   3371 
   3372     ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
   3373 
   3374     updateDevicesAndOutputs();
   3375 
   3376 #ifdef AUDIO_POLICY_TEST
   3377     if (mPrimaryOutput != 0) {
   3378         AudioParameter outputCmd = AudioParameter();
   3379         outputCmd.addInt(String8("set_id"), 0);
   3380         mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
   3381 
   3382         mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
   3383         mTestSamplingRate = 44100;
   3384         mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
   3385         mTestChannels =  AUDIO_CHANNEL_OUT_STEREO;
   3386         mTestLatencyMs = 0;
   3387         mCurOutput = 0;
   3388         mDirectOutput = false;
   3389         for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
   3390             mTestOutputs[i] = 0;
   3391         }
   3392 
   3393         const size_t SIZE = 256;
   3394         char buffer[SIZE];
   3395         snprintf(buffer, SIZE, "AudioPolicyManagerTest");
   3396         run(buffer, ANDROID_PRIORITY_AUDIO);
   3397     }
   3398 #endif //AUDIO_POLICY_TEST
   3399 }
   3400 
   3401 AudioPolicyManager::~AudioPolicyManager()
   3402 {
   3403 #ifdef AUDIO_POLICY_TEST
   3404     exit();
   3405 #endif //AUDIO_POLICY_TEST
   3406    for (size_t i = 0; i < mOutputs.size(); i++) {
   3407         mpClientInterface->closeOutput(mOutputs.keyAt(i));
   3408    }
   3409    for (size_t i = 0; i < mInputs.size(); i++) {
   3410         mpClientInterface->closeInput(mInputs.keyAt(i));
   3411    }
   3412    mAvailableOutputDevices.clear();
   3413    mAvailableInputDevices.clear();
   3414    mOutputs.clear();
   3415    mInputs.clear();
   3416    mHwModules.clear();
   3417 }
   3418 
   3419 status_t AudioPolicyManager::initCheck()
   3420 {
   3421     return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
   3422 }
   3423 
   3424 #ifdef AUDIO_POLICY_TEST
   3425 bool AudioPolicyManager::threadLoop()
   3426 {
   3427     ALOGV("entering threadLoop()");
   3428     while (!exitPending())
   3429     {
   3430         String8 command;
   3431         int valueInt;
   3432         String8 value;
   3433 
   3434         Mutex::Autolock _l(mLock);
   3435         mWaitWorkCV.waitRelative(mLock, milliseconds(50));
   3436 
   3437         command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
   3438         AudioParameter param = AudioParameter(command);
   3439 
   3440         if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
   3441             valueInt != 0) {
   3442             ALOGV("Test command %s received", command.string());
   3443             String8 target;
   3444             if (param.get(String8("target"), target) != NO_ERROR) {
   3445                 target = "Manager";
   3446             }
   3447             if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
   3448                 param.remove(String8("test_cmd_policy_output"));
   3449                 mCurOutput = valueInt;
   3450             }
   3451             if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
   3452                 param.remove(String8("test_cmd_policy_direct"));
   3453                 if (value == "false") {
   3454                     mDirectOutput = false;
   3455                 } else if (value == "true") {
   3456                     mDirectOutput = true;
   3457                 }
   3458             }
   3459             if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
   3460                 param.remove(String8("test_cmd_policy_input"));
   3461                 mTestInput = valueInt;
   3462             }
   3463 
   3464             if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
   3465                 param.remove(String8("test_cmd_policy_format"));
   3466                 int format = AUDIO_FORMAT_INVALID;
   3467                 if (value == "PCM 16 bits") {
   3468                     format = AUDIO_FORMAT_PCM_16_BIT;
   3469                 } else if (value == "PCM 8 bits") {
   3470                     format = AUDIO_FORMAT_PCM_8_BIT;
   3471                 } else if (value == "Compressed MP3") {
   3472                     format = AUDIO_FORMAT_MP3;
   3473                 }
   3474                 if (format != AUDIO_FORMAT_INVALID) {
   3475                     if (target == "Manager") {
   3476                         mTestFormat = format;
   3477                     } else if (mTestOutputs[mCurOutput] != 0) {
   3478                         AudioParameter outputParam = AudioParameter();
   3479                         outputParam.addInt(String8("format"), format);
   3480                         mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
   3481                     }
   3482                 }
   3483             }
   3484             if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
   3485                 param.remove(String8("test_cmd_policy_channels"));
   3486                 int channels = 0;
   3487 
   3488                 if (value == "Channels Stereo") {
   3489                     channels =  AUDIO_CHANNEL_OUT_STEREO;
   3490                 } else if (value == "Channels Mono") {
   3491                     channels =  AUDIO_CHANNEL_OUT_MONO;
   3492                 }
   3493                 if (channels != 0) {
   3494                     if (target == "Manager") {
   3495                         mTestChannels = channels;
   3496                     } else if (mTestOutputs[mCurOutput] != 0) {
   3497                         AudioParameter outputParam = AudioParameter();
   3498                         outputParam.addInt(String8("channels"), channels);
   3499                         mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
   3500                     }
   3501                 }
   3502             }
   3503             if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
   3504                 param.remove(String8("test_cmd_policy_sampleRate"));
   3505                 if (valueInt >= 0 && valueInt <= 96000) {
   3506                     int samplingRate = valueInt;
   3507                     if (target == "Manager") {
   3508                         mTestSamplingRate = samplingRate;
   3509                     } else if (mTestOutputs[mCurOutput] != 0) {
   3510                         AudioParameter outputParam = AudioParameter();
   3511                         outputParam.addInt(String8("sampling_rate"), samplingRate);
   3512                         mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
   3513                     }
   3514                 }
   3515             }
   3516 
   3517             if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
   3518                 param.remove(String8("test_cmd_policy_reopen"));
   3519 
   3520                 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
   3521 
   3522                 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
   3523 
   3524                 removeOutput(mPrimaryOutput->mIoHandle);
   3525                 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
   3526                                                                                mpClientInterface);
   3527                 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
   3528                 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
   3529                 config.sample_rate = outputDesc->mSamplingRate;
   3530                 config.channel_mask = outputDesc->mChannelMask;
   3531                 config.format = outputDesc->mFormat;
   3532                 audio_io_handle_t handle;
   3533                 status_t status = mpClientInterface->openOutput(moduleHandle,
   3534                                                                 &handle,
   3535                                                                 &config,
   3536                                                                 &outputDesc->mDevice,
   3537                                                                 String8(""),
   3538                                                                 &outputDesc->mLatency,
   3539                                                                 outputDesc->mFlags);
   3540                 if (status != NO_ERROR) {
   3541                     ALOGE("Failed to reopen hardware output stream, "
   3542                         "samplingRate: %d, format %d, channels %d",
   3543                         outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
   3544                 } else {
   3545                     outputDesc->mSamplingRate = config.sample_rate;
   3546                     outputDesc->mChannelMask = config.channel_mask;
   3547                     outputDesc->mFormat = config.format;
   3548                     mPrimaryOutput = outputDesc;
   3549                     AudioParameter outputCmd = AudioParameter();
   3550                     outputCmd.addInt(String8("set_id"), 0);
   3551                     mpClientInterface->setParameters(handle, outputCmd.toString());
   3552                     addOutput(handle, outputDesc);
   3553                 }
   3554             }
   3555 
   3556 
   3557             mpClientInterface->setParameters(0, String8("test_cmd_policy="));
   3558         }
   3559     }
   3560     return false;
   3561 }
   3562 
   3563 void AudioPolicyManager::exit()
   3564 {
   3565     {
   3566         AutoMutex _l(mLock);
   3567         requestExit();
   3568         mWaitWorkCV.signal();
   3569     }
   3570     requestExitAndWait();
   3571 }
   3572 
   3573 int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
   3574 {
   3575     for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
   3576         if (output == mTestOutputs[i]) return i;
   3577     }
   3578     return 0;
   3579 }
   3580 #endif //AUDIO_POLICY_TEST
   3581 
   3582 // ---
   3583 
   3584 void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<SwAudioOutputDescriptor> outputDesc)
   3585 {
   3586     outputDesc->setIoHandle(output);
   3587     mOutputs.add(output, outputDesc);
   3588     updateMono(output); // update mono status when adding to output list
   3589     nextAudioPortGeneration();
   3590 }
   3591 
   3592 void AudioPolicyManager::removeOutput(audio_io_handle_t output)
   3593 {
   3594     mOutputs.removeItem(output);
   3595 }
   3596 
   3597 void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
   3598 {
   3599     inputDesc->setIoHandle(input);
   3600     mInputs.add(input, inputDesc);
   3601     nextAudioPortGeneration();
   3602 }
   3603 
   3604 void AudioPolicyManager::findIoHandlesByAddress(sp<SwAudioOutputDescriptor> desc /*in*/,
   3605         const audio_devices_t device /*in*/,
   3606         const String8 address /*in*/,
   3607         SortedVector<audio_io_handle_t>& outputs /*out*/) {
   3608     sp<DeviceDescriptor> devDesc =
   3609         desc->mProfile->getSupportedDeviceByAddress(device, address);
   3610     if (devDesc != 0) {
   3611         ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
   3612               desc->mIoHandle, address.string());
   3613         outputs.add(desc->mIoHandle);
   3614     }
   3615 }
   3616 
   3617 status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
   3618                                                    audio_policy_dev_state_t state,
   3619                                                    SortedVector<audio_io_handle_t>& outputs,
   3620                                                    const String8 address)
   3621 {
   3622     audio_devices_t device = devDesc->type();
   3623     sp<SwAudioOutputDescriptor> desc;
   3624 
   3625     if (audio_device_is_digital(device)) {
   3626         // erase all current sample rates, formats and channel masks
   3627         devDesc->clearAudioProfiles();
   3628     }
   3629 
   3630     if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
   3631         // first list already open outputs that can be routed to this device
   3632         for (size_t i = 0; i < mOutputs.size(); i++) {
   3633             desc = mOutputs.valueAt(i);
   3634             if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
   3635                 if (!device_distinguishes_on_address(device)) {
   3636                     ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
   3637                     outputs.add(mOutputs.keyAt(i));
   3638                 } else {
   3639                     ALOGV("  checking address match due to device 0x%x", device);
   3640                     findIoHandlesByAddress(desc, device, address, outputs);
   3641                 }
   3642             }
   3643         }
   3644         // then look for output profiles that can be routed to this device
   3645         SortedVector< sp<IOProfile> > profiles;
   3646         for (size_t i = 0; i < mHwModules.size(); i++)
   3647         {
   3648             if (mHwModules[i]->mHandle == 0) {
   3649                 continue;
   3650             }
   3651             for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
   3652             {
   3653                 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
   3654                 if (profile->supportDevice(device)) {
   3655                     if (!device_distinguishes_on_address(device) ||
   3656                             profile->supportDeviceAddress(address)) {
   3657                         profiles.add(profile);
   3658                         ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
   3659                     }
   3660                 }
   3661             }
   3662         }
   3663 
   3664         ALOGV("  found %zu profiles, %zu outputs", profiles.size(), outputs.size());
   3665 
   3666         if (profiles.isEmpty() && outputs.isEmpty()) {
   3667             ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
   3668             return BAD_VALUE;
   3669         }
   3670 
   3671         // open outputs for matching profiles if needed. Direct outputs are also opened to
   3672         // query for dynamic parameters and will be closed later by setDeviceConnectionState()
   3673         for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
   3674             sp<IOProfile> profile = profiles[profile_index];
   3675 
   3676             // nothing to do if one output is already opened for this profile
   3677             size_t j;
   3678             for (j = 0; j < outputs.size(); j++) {
   3679                 desc = mOutputs.valueFor(outputs.itemAt(j));
   3680                 if (!desc->isDuplicated() && desc->mProfile == profile) {
   3681                     // matching profile: save the sample rates, format and channel masks supported
   3682                     // by the profile in our device descriptor
   3683                     if (audio_device_is_digital(device)) {
   3684                         devDesc->importAudioPort(profile);
   3685                     }
   3686                     break;
   3687                 }
   3688             }
   3689             if (j != outputs.size()) {
   3690                 continue;
   3691             }
   3692 
   3693             ALOGV("opening output for device %08x with params %s profile %p",
   3694                                                       device, address.string(), profile.get());
   3695             desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
   3696             desc->mDevice = device;
   3697             audio_config_t config = AUDIO_CONFIG_INITIALIZER;
   3698             config.sample_rate = desc->mSamplingRate;
   3699             config.channel_mask = desc->mChannelMask;
   3700             config.format = desc->mFormat;
   3701             config.offload_info.sample_rate = desc->mSamplingRate;
   3702             config.offload_info.channel_mask = desc->mChannelMask;
   3703             config.offload_info.format = desc->mFormat;
   3704             audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
   3705             status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
   3706                                                             &output,
   3707                                                             &config,
   3708                                                             &desc->mDevice,
   3709                                                             address,
   3710                                                             &desc->mLatency,
   3711                                                             desc->mFlags);
   3712             if (status == NO_ERROR) {
   3713                 desc->mSamplingRate = config.sample_rate;
   3714                 desc->mChannelMask = config.channel_mask;
   3715                 desc->mFormat = config.format;
   3716 
   3717                 // Here is where the out_set_parameters() for card & device gets called
   3718                 if (!address.isEmpty()) {
   3719                     char *param = audio_device_address_to_parameter(device, address);
   3720                     mpClientInterface->setParameters(output, String8(param));
   3721                     free(param);
   3722                 }
   3723                 updateAudioProfiles(device, output, profile->getAudioProfiles());
   3724                 if (!profile->hasValidAudioProfile()) {
   3725                     ALOGW("checkOutputsForDevice() missing param");
   3726                     mpClientInterface->closeOutput(output);
   3727                     output = AUDIO_IO_HANDLE_NONE;
   3728                 } else if (profile->hasDynamicAudioProfile()) {
   3729                     mpClientInterface->closeOutput(output);
   3730                     output = AUDIO_IO_HANDLE_NONE;
   3731                     profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format);
   3732                     config.offload_info.sample_rate = config.sample_rate;
   3733                     config.offload_info.channel_mask = config.channel_mask;
   3734                     config.offload_info.format = config.format;
   3735                     status = mpClientInterface->openOutput(profile->getModuleHandle(),
   3736                                                            &output,
   3737                                                            &config,
   3738                                                            &desc->mDevice,
   3739                                                            address,
   3740                                                            &desc->mLatency,
   3741                                                            desc->mFlags);
   3742                     if (status == NO_ERROR) {
   3743                         desc->mSamplingRate = config.sample_rate;
   3744                         desc->mChannelMask = config.channel_mask;
   3745                         desc->mFormat = config.format;
   3746                     } else {
   3747                         output = AUDIO_IO_HANDLE_NONE;
   3748                     }
   3749                 }
   3750 
   3751                 if (output != AUDIO_IO_HANDLE_NONE) {
   3752                     addOutput(output, desc);
   3753                     if (device_distinguishes_on_address(device) && address != "0") {
   3754                         sp<AudioPolicyMix> policyMix;
   3755                         if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
   3756                             ALOGE("checkOutputsForDevice() cannot find policy for address %s",
   3757                                   address.string());
   3758                         }
   3759                         policyMix->setOutput(desc);
   3760                         desc->mPolicyMix = policyMix->getMix();
   3761 
   3762                     } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
   3763                                     hasPrimaryOutput()) {
   3764                         // no duplicated output for direct outputs and
   3765                         // outputs used by dynamic policy mixes
   3766                         audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
   3767 
   3768                         // set initial stream volume for device
   3769                         applyStreamVolumes(desc, device, 0, true);
   3770 
   3771                         //TODO: configure audio effect output stage here
   3772 
   3773                         // open a duplicating output thread for the new output and the primary output
   3774                         duplicatedOutput =
   3775                                 mpClientInterface->openDuplicateOutput(output,
   3776                                                                        mPrimaryOutput->mIoHandle);
   3777                         if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
   3778                             // add duplicated output descriptor
   3779                             sp<SwAudioOutputDescriptor> dupOutputDesc =
   3780                                     new SwAudioOutputDescriptor(NULL, mpClientInterface);
   3781                             dupOutputDesc->mOutput1 = mPrimaryOutput;
   3782                             dupOutputDesc->mOutput2 = desc;
   3783                             dupOutputDesc->mSamplingRate = desc->mSamplingRate;
   3784                             dupOutputDesc->mFormat = desc->mFormat;
   3785                             dupOutputDesc->mChannelMask = desc->mChannelMask;
   3786                             dupOutputDesc->mLatency = desc->mLatency;
   3787                             addOutput(duplicatedOutput, dupOutputDesc);
   3788                             applyStreamVolumes(dupOutputDesc, device, 0, true);
   3789                         } else {
   3790                             ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
   3791                                     mPrimaryOutput->mIoHandle, output);
   3792                             mpClientInterface->closeOutput(output);
   3793                             removeOutput(output);
   3794                             nextAudioPortGeneration();
   3795                             output = AUDIO_IO_HANDLE_NONE;
   3796                         }
   3797                     }
   3798                 }
   3799             } else {
   3800                 output = AUDIO_IO_HANDLE_NONE;
   3801             }
   3802             if (output == AUDIO_IO_HANDLE_NONE) {
   3803                 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
   3804                 profiles.removeAt(profile_index);
   3805                 profile_index--;
   3806             } else {
   3807                 outputs.add(output);
   3808                 // Load digital format info only for digital devices
   3809                 if (audio_device_is_digital(device)) {
   3810                     devDesc->importAudioPort(profile);
   3811                 }
   3812 
   3813                 if (device_distinguishes_on_address(device)) {
   3814                     ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
   3815                             device, address.string());
   3816                     setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
   3817                             NULL/*patch handle*/, address.string());
   3818                 }
   3819                 ALOGV("checkOutputsForDevice(): adding output %d", output);
   3820             }
   3821         }
   3822 
   3823         if (profiles.isEmpty()) {
   3824             ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
   3825             return BAD_VALUE;
   3826         }
   3827     } else { // Disconnect
   3828         // check if one opened output is not needed any more after disconnecting one device
   3829         for (size_t i = 0; i < mOutputs.size(); i++) {
   3830             desc = mOutputs.valueAt(i);
   3831             if (!desc->isDuplicated()) {
   3832                 // exact match on device
   3833                 if (device_distinguishes_on_address(device) &&
   3834                         (desc->supportedDevices() == device)) {
   3835                     findIoHandlesByAddress(desc, device, address, outputs);
   3836                 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
   3837                     ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
   3838                             mOutputs.keyAt(i));
   3839                     outputs.add(mOutputs.keyAt(i));
   3840                 }
   3841             }
   3842         }
   3843         // Clear any profiles associated with the disconnected device.
   3844         for (size_t i = 0; i < mHwModules.size(); i++)
   3845         {
   3846             if (mHwModules[i]->mHandle == 0) {
   3847                 continue;
   3848             }
   3849             for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
   3850             {
   3851                 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
   3852                 if (profile->supportDevice(device)) {
   3853                     ALOGV("checkOutputsForDevice(): "
   3854                             "clearing direct output profile %zu on module %zu", j, i);
   3855                     profile->clearAudioProfiles();
   3856                 }
   3857             }
   3858         }
   3859     }
   3860     return NO_ERROR;
   3861 }
   3862 
   3863 status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor> devDesc,
   3864                                                   audio_policy_dev_state_t state,
   3865                                                   SortedVector<audio_io_handle_t>& inputs,
   3866                                                   const String8 address)
   3867 {
   3868     audio_devices_t device = devDesc->type();
   3869     sp<AudioInputDescriptor> desc;
   3870 
   3871     if (audio_device_is_digital(device)) {
   3872         // erase all current sample rates, formats and channel masks
   3873         devDesc->clearAudioProfiles();
   3874     }
   3875 
   3876     if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
   3877         // first list already open inputs that can be routed to this device
   3878         for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
   3879             desc = mInputs.valueAt(input_index);
   3880             if (desc->mProfile->supportDevice(device)) {
   3881                 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
   3882                inputs.add(mInputs.keyAt(input_index));
   3883             }
   3884         }
   3885 
   3886         // then look for input profiles that can be routed to this device
   3887         SortedVector< sp<IOProfile> > profiles;
   3888         for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
   3889         {
   3890             if (mHwModules[module_idx]->mHandle == 0) {
   3891                 continue;
   3892             }
   3893             for (size_t profile_index = 0;
   3894                  profile_index < mHwModules[module_idx]->mInputProfiles.size();
   3895                  profile_index++)
   3896             {
   3897                 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
   3898 
   3899                 if (profile->supportDevice(device)) {
   3900                     if (!device_distinguishes_on_address(device) ||
   3901                             profile->supportDeviceAddress(address)) {
   3902                         profiles.add(profile);
   3903                         ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
   3904                               profile_index, module_idx);
   3905                     }
   3906                 }
   3907             }
   3908         }
   3909 
   3910         if (profiles.isEmpty() && inputs.isEmpty()) {
   3911             ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
   3912             return BAD_VALUE;
   3913         }
   3914 
   3915         // open inputs for matching profiles if needed. Direct inputs are also opened to
   3916         // query for dynamic parameters and will be closed later by setDeviceConnectionState()
   3917         for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
   3918 
   3919             sp<IOProfile> profile = profiles[profile_index];
   3920             // nothing to do if one input is already opened for this profile
   3921             size_t input_index;
   3922             for (input_index = 0; input_index < mInputs.size(); input_index++) {
   3923                 desc = mInputs.valueAt(input_index);
   3924                 if (desc->mProfile == profile) {
   3925                     if (audio_device_is_digital(device)) {
   3926                         devDesc->importAudioPort(profile);
   3927                     }
   3928                     break;
   3929                 }
   3930             }
   3931             if (input_index != mInputs.size()) {
   3932                 continue;
   3933             }
   3934 
   3935             ALOGV("opening input for device 0x%X with params %s", device, address.string());
   3936             desc = new AudioInputDescriptor(profile);
   3937             desc->mDevice = device;
   3938             audio_config_t config = AUDIO_CONFIG_INITIALIZER;
   3939             config.sample_rate = desc->mSamplingRate;
   3940             config.channel_mask = desc->mChannelMask;
   3941             config.format = desc->mFormat;
   3942             audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
   3943             status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
   3944                                                            &input,
   3945                                                            &config,
   3946                                                            &desc->mDevice,
   3947                                                            address,
   3948                                                            AUDIO_SOURCE_MIC,
   3949                                                            AUDIO_INPUT_FLAG_NONE /*FIXME*/);
   3950 
   3951             if (status == NO_ERROR) {
   3952                 desc->mSamplingRate = config.sample_rate;
   3953                 desc->mChannelMask = config.channel_mask;
   3954                 desc->mFormat = config.format;
   3955 
   3956                 if (!address.isEmpty()) {
   3957                     char *param = audio_device_address_to_parameter(device, address);
   3958                     mpClientInterface->setParameters(input, String8(param));
   3959                     free(param);
   3960                 }
   3961                 updateAudioProfiles(device, input, profile->getAudioProfiles());
   3962                 if (!profile->hasValidAudioProfile()) {
   3963                     ALOGW("checkInputsForDevice() direct input missing param");
   3964                     mpClientInterface->closeInput(input);
   3965                     input = AUDIO_IO_HANDLE_NONE;
   3966                 }
   3967 
   3968                 if (input != 0) {
   3969                     addInput(input, desc);
   3970                 }
   3971             } // endif input != 0
   3972 
   3973             if (input == AUDIO_IO_HANDLE_NONE) {
   3974                 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
   3975                 profiles.removeAt(profile_index);
   3976                 profile_index--;
   3977             } else {
   3978                 inputs.add(input);
   3979                 if (audio_device_is_digital(device)) {
   3980                     devDesc->importAudioPort(profile);
   3981                 }
   3982                 ALOGV("checkInputsForDevice(): adding input %d", input);
   3983             }
   3984         } // end scan profiles
   3985 
   3986         if (profiles.isEmpty()) {
   3987             ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
   3988             return BAD_VALUE;
   3989         }
   3990     } else {
   3991         // Disconnect
   3992         // check if one opened input is not needed any more after disconnecting one device
   3993         for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
   3994             desc = mInputs.valueAt(input_index);
   3995             if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
   3996                 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
   3997                       mInputs.keyAt(input_index));
   3998                 inputs.add(mInputs.keyAt(input_index));
   3999             }
   4000         }
   4001         // Clear any profiles associated with the disconnected device.
   4002         for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
   4003             if (mHwModules[module_index]->mHandle == 0) {
   4004                 continue;
   4005             }
   4006             for (size_t profile_index = 0;
   4007                  profile_index < mHwModules[module_index]->mInputProfiles.size();
   4008                  profile_index++) {
   4009                 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
   4010                 if (profile->supportDevice(device)) {
   4011                     ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
   4012                           profile_index, module_index);
   4013                     profile->clearAudioProfiles();
   4014                 }
   4015             }
   4016         }
   4017     } // end disconnect
   4018 
   4019     return NO_ERROR;
   4020 }
   4021 
   4022 
   4023 void AudioPolicyManager::closeOutput(audio_io_handle_t output)
   4024 {
   4025     ALOGV("closeOutput(%d)", output);
   4026 
   4027     sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
   4028     if (outputDesc == NULL) {
   4029         ALOGW("closeOutput() unknown output %d", output);
   4030         return;
   4031     }
   4032     mPolicyMixes.closeOutput(outputDesc);
   4033 
   4034     // look for duplicated outputs connected to the output being removed.
   4035     for (size_t i = 0; i < mOutputs.size(); i++) {
   4036         sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
   4037         if (dupOutputDesc->isDuplicated() &&
   4038                 (dupOutputDesc->mOutput1 == outputDesc ||
   4039                 dupOutputDesc->mOutput2 == outputDesc)) {
   4040             sp<AudioOutputDescriptor> outputDesc2;
   4041             if (dupOutputDesc->mOutput1 == outputDesc) {
   4042                 outputDesc2 = dupOutputDesc->mOutput2;
   4043             } else {
   4044                 outputDesc2 = dupOutputDesc->mOutput1;
   4045             }
   4046             // As all active tracks on duplicated output will be deleted,
   4047             // and as they were also referenced on the other output, the reference
   4048             // count for their stream type must be adjusted accordingly on
   4049             // the other output.
   4050             for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
   4051                 int refCount = dupOutputDesc->mRefCount[j];
   4052                 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
   4053             }
   4054             audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
   4055             ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
   4056 
   4057             mpClientInterface->closeOutput(duplicatedOutput);
   4058             removeOutput(duplicatedOutput);
   4059         }
   4060     }
   4061 
   4062     nextAudioPortGeneration();
   4063 
   4064     ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
   4065     if (index >= 0) {
   4066         sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
   4067         status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
   4068         mAudioPatches.removeItemsAt(index);
   4069         mpClientInterface->onAudioPatchListUpdate();
   4070     }
   4071 
   4072     AudioParameter param;
   4073     param.add(String8("closing"), String8("true"));
   4074     mpClientInterface->setParameters(output, param.toString());
   4075 
   4076     mpClientInterface->closeOutput(output);
   4077     removeOutput(output);
   4078     mPreviousOutputs = mOutputs;
   4079 }
   4080 
   4081 void AudioPolicyManager::closeInput(audio_io_handle_t input)
   4082 {
   4083     ALOGV("closeInput(%d)", input);
   4084 
   4085     sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
   4086     if (inputDesc == NULL) {
   4087         ALOGW("closeInput() unknown input %d", input);
   4088         return;
   4089     }
   4090 
   4091     nextAudioPortGeneration();
   4092 
   4093     ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
   4094     if (index >= 0) {
   4095         sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
   4096         status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
   4097         mAudioPatches.removeItemsAt(index);
   4098         mpClientInterface->onAudioPatchListUpdate();
   4099     }
   4100 
   4101     mpClientInterface->closeInput(input);
   4102     mInputs.removeItem(input);
   4103 }
   4104 
   4105 SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
   4106                                                                 audio_devices_t device,
   4107                                                                 SwAudioOutputCollection openOutputs)
   4108 {
   4109     SortedVector<audio_io_handle_t> outputs;
   4110 
   4111     ALOGVV("getOutputsForDevice() device %04x", device);
   4112     for (size_t i = 0; i < openOutputs.size(); i++) {
   4113         ALOGVV("output %d isDuplicated=%d device=%04x",
   4114                 i, openOutputs.valueAt(i)->isDuplicated(),
   4115                 openOutputs.valueAt(i)->supportedDevices());
   4116         if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
   4117             ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
   4118             outputs.add(openOutputs.keyAt(i));
   4119         }
   4120     }
   4121     return outputs;
   4122 }
   4123 
   4124 bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
   4125                                       SortedVector<audio_io_handle_t>& outputs2)
   4126 {
   4127     if (outputs1.size() != outputs2.size()) {
   4128         return false;
   4129     }
   4130     for (size_t i = 0; i < outputs1.size(); i++) {
   4131         if (outputs1[i] != outputs2[i]) {
   4132             return false;
   4133         }
   4134     }
   4135     return true;
   4136 }
   4137 
   4138 void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
   4139 {
   4140     audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
   4141     audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
   4142     SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
   4143     SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
   4144 
   4145     // also take into account external policy-related changes: add all outputs which are
   4146     // associated with policies in the "before" and "after" output vectors
   4147     ALOGVV("checkOutputForStrategy(): policy related outputs");
   4148     for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
   4149         const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
   4150         if (desc != 0 && desc->mPolicyMix != NULL) {
   4151             srcOutputs.add(desc->mIoHandle);
   4152             ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
   4153         }
   4154     }
   4155     for (size_t i = 0 ; i < mOutputs.size() ; i++) {
   4156         const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
   4157         if (desc != 0 && desc->mPolicyMix != NULL) {
   4158             dstOutputs.add(desc->mIoHandle);
   4159             ALOGVV(" new outputs: adding %d", desc->mIoHandle);
   4160         }
   4161     }
   4162 
   4163     if (!vectorsEqual(srcOutputs,dstOutputs)) {
   4164         ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
   4165               strategy, srcOutputs[0], dstOutputs[0]);
   4166         // mute strategy while moving tracks from one output to another
   4167         for (size_t i = 0; i < srcOutputs.size(); i++) {
   4168             sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
   4169             if (isStrategyActive(desc, strategy)) {
   4170                 setStrategyMute(strategy, true, desc);
   4171                 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
   4172             }
   4173             sp<AudioSourceDescriptor> source =
   4174                     getSourceForStrategyOnOutput(srcOutputs[i], strategy);
   4175             if (source != 0){
   4176                 connectAudioSource(source);
   4177             }
   4178         }
   4179 
   4180         // Move effects associated to this strategy from previous output to new output
   4181         if (strategy == STRATEGY_MEDIA) {
   4182             audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
   4183             SortedVector<audio_io_handle_t> moved;
   4184             for (size_t i = 0; i < mEffects.size(); i++) {
   4185                 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
   4186                 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
   4187                         effectDesc->mIo != fxOutput) {
   4188                     if (moved.indexOf(effectDesc->mIo) < 0) {
   4189                         ALOGV("checkOutputForStrategy() moving effect %d to output %d",
   4190                               mEffects.keyAt(i), fxOutput);
   4191                         mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
   4192                                                        fxOutput);
   4193                         moved.add(effectDesc->mIo);
   4194                     }
   4195                     effectDesc->mIo = fxOutput;
   4196                 }
   4197             }
   4198         }
   4199         // Move tracks associated to this strategy from previous output to new output
   4200         for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
   4201             if (getStrategy((audio_stream_type_t)i) == strategy) {
   4202                 mpClientInterface->invalidateStream((audio_stream_type_t)i);
   4203             }
   4204         }
   4205     }
   4206 }
   4207 
   4208 void AudioPolicyManager::checkOutputForAllStrategies()
   4209 {
   4210     if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
   4211         checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
   4212     checkOutputForStrategy(STRATEGY_PHONE);
   4213     if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
   4214         checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
   4215     checkOutputForStrategy(STRATEGY_SONIFICATION);
   4216     checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
   4217     checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
   4218     checkOutputForStrategy(STRATEGY_MEDIA);
   4219     checkOutputForStrategy(STRATEGY_DTMF);
   4220     checkOutputForStrategy(STRATEGY_REROUTING);
   4221 }
   4222 
   4223 void AudioPolicyManager::checkA2dpSuspend()
   4224 {
   4225     audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
   4226     if (a2dpOutput == 0) {
   4227         mA2dpSuspended = false;
   4228         return;
   4229     }
   4230 
   4231     bool isScoConnected =
   4232             ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
   4233                     ~AUDIO_DEVICE_BIT_IN) != 0) ||
   4234             ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
   4235     // suspend A2DP output if:
   4236     //      (NOT already suspended) &&
   4237     //      ((SCO device is connected &&
   4238     //       (forced usage for communication || for record is SCO))) ||
   4239     //      (phone state is ringing || in call)
   4240     //
   4241     // restore A2DP output if:
   4242     //      (Already suspended) &&
   4243     //      ((SCO device is NOT connected ||
   4244     //       (forced usage NOT for communication && NOT for record is SCO))) &&
   4245     //      (phone state is NOT ringing && NOT in call)
   4246     //
   4247     if (mA2dpSuspended) {
   4248         if ((!isScoConnected ||
   4249              ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) != AUDIO_POLICY_FORCE_BT_SCO) &&
   4250               (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) != AUDIO_POLICY_FORCE_BT_SCO))) &&
   4251              ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
   4252               (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
   4253 
   4254             mpClientInterface->restoreOutput(a2dpOutput);
   4255             mA2dpSuspended = false;
   4256         }
   4257     } else {
   4258         if ((isScoConnected &&
   4259              ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) == AUDIO_POLICY_FORCE_BT_SCO) ||
   4260               (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) == AUDIO_POLICY_FORCE_BT_SCO))) ||
   4261              ((mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
   4262               (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
   4263 
   4264             mpClientInterface->suspendOutput(a2dpOutput);
   4265             mA2dpSuspended = true;
   4266         }
   4267     }
   4268 }
   4269 
   4270 audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
   4271                                                        bool fromCache)
   4272 {
   4273     audio_devices_t device = AUDIO_DEVICE_NONE;
   4274 
   4275     ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
   4276     if (index >= 0) {
   4277         sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
   4278         if (patchDesc->mUid != mUidCached) {
   4279             ALOGV("getNewOutputDevice() device %08x forced by patch %d",
   4280                   outputDesc->device(), outputDesc->getPatchHandle());
   4281             return outputDesc->device();
   4282         }
   4283     }
   4284 
   4285     // check the following by order of priority to request a routing change if necessary:
   4286     // 1: the strategy enforced audible is active and enforced on the output:
   4287     //      use device for strategy enforced audible
   4288     // 2: we are in call or the strategy phone is active on the output:
   4289     //      use device for strategy phone
   4290     // 3: the strategy for enforced audible is active but not enforced on the output:
   4291     //      use the device for strategy enforced audible
   4292     // 4: the strategy sonification is active on the output:
   4293     //      use device for strategy sonification
   4294     // 5: the strategy accessibility is active on the output:
   4295     //      use device for strategy accessibility
   4296     // 6: the strategy "respectful" sonification is active on the output:
   4297     //      use device for strategy "respectful" sonification
   4298     // 7: the strategy media is active on the output:
   4299     //      use device for strategy media
   4300     // 8: the strategy DTMF is active on the output:
   4301     //      use device for strategy DTMF
   4302     // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
   4303     //      use device for strategy t-t-s
   4304     if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
   4305         mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
   4306         device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
   4307     } else if (isInCall() ||
   4308                     isStrategyActive(outputDesc, STRATEGY_PHONE)) {
   4309         device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
   4310     } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
   4311         device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
   4312     } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
   4313         device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
   4314     } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
   4315         device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
   4316     } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
   4317         device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
   4318     } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
   4319         device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
   4320     } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
   4321         device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
   4322     } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
   4323         device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
   4324     } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
   4325         device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
   4326     }
   4327 
   4328     ALOGV("getNewOutputDevice() selected device %x", device);
   4329     return device;
   4330 }
   4331 
   4332 audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
   4333 {
   4334     sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
   4335 
   4336     ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
   4337     if (index >= 0) {
   4338         sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
   4339         if (patchDesc->mUid != mUidCached) {
   4340             ALOGV("getNewInputDevice() device %08x forced by patch %d",
   4341                   inputDesc->mDevice, inputDesc->getPatchHandle());
   4342             return inputDesc->mDevice;
   4343         }
   4344     }
   4345 
   4346     audio_devices_t device = getDeviceAndMixForInputSource(inputDesc->inputSource());
   4347 
   4348     return device;
   4349 }
   4350 
   4351 bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
   4352                                                audio_stream_type_t stream2) {
   4353     return ((stream1 == stream2) ||
   4354             ((stream1 == AUDIO_STREAM_ACCESSIBILITY) && (stream2 == AUDIO_STREAM_MUSIC)) ||
   4355             ((stream1 == AUDIO_STREAM_MUSIC) && (stream2 == AUDIO_STREAM_ACCESSIBILITY)));
   4356 }
   4357 
   4358 uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
   4359     return (uint32_t)getStrategy(stream);
   4360 }
   4361 
   4362 audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
   4363     // By checking the range of stream before calling getStrategy, we avoid
   4364     // getStrategy's behavior for invalid streams.  getStrategy would do a ALOGE
   4365     // and then return STRATEGY_MEDIA, but we want to return the empty set.
   4366     if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
   4367         return AUDIO_DEVICE_NONE;
   4368     }
   4369     audio_devices_t devices = AUDIO_DEVICE_NONE;
   4370     for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
   4371         if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
   4372             continue;
   4373         }
   4374         routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
   4375         audio_devices_t curDevices =
   4376                 getDeviceForStrategy((routing_strategy)curStrategy, true /*fromCache*/);
   4377         SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(curDevices, mOutputs);
   4378         for (size_t i = 0; i < outputs.size(); i++) {
   4379             sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
   4380             if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
   4381                 curDevices |= outputDesc->device();
   4382             }
   4383         }
   4384         devices |= curDevices;
   4385     }
   4386 
   4387     /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
   4388       and doesn't really need to.*/
   4389     if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
   4390         devices |= AUDIO_DEVICE_OUT_SPEAKER;
   4391         devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
   4392     }
   4393     return devices;
   4394 }
   4395 
   4396 routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
   4397 {
   4398     ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
   4399     return mEngine->getStrategyForStream(stream);
   4400 }
   4401 
   4402 uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
   4403     // flags to strategy mapping
   4404     if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
   4405         return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
   4406     }
   4407     if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
   4408         return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
   4409     }
   4410     // usage to strategy mapping
   4411     return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
   4412 }
   4413 
   4414 void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
   4415     switch(stream) {
   4416     case AUDIO_STREAM_MUSIC:
   4417         checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
   4418         updateDevicesAndOutputs();
   4419         break;
   4420     default:
   4421         break;
   4422     }
   4423 }
   4424 
   4425 uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
   4426 
   4427     // skip beacon mute management if a dedicated TTS output is available
   4428     if (mTtsOutputAvailable) {
   4429         return 0;
   4430     }
   4431 
   4432     switch(event) {
   4433     case STARTING_OUTPUT:
   4434         mBeaconMuteRefCount++;
   4435         break;
   4436     case STOPPING_OUTPUT:
   4437         if (mBeaconMuteRefCount > 0) {
   4438             mBeaconMuteRefCount--;
   4439         }
   4440         break;
   4441     case STARTING_BEACON:
   4442         mBeaconPlayingRefCount++;
   4443         break;
   4444     case STOPPING_BEACON:
   4445         if (mBeaconPlayingRefCount > 0) {
   4446             mBeaconPlayingRefCount--;
   4447         }
   4448         break;
   4449     }
   4450 
   4451     if (mBeaconMuteRefCount > 0) {
   4452         // any playback causes beacon to be muted
   4453         return setBeaconMute(true);
   4454     } else {
   4455         // no other playback: unmute when beacon starts playing, mute when it stops
   4456         return setBeaconMute(mBeaconPlayingRefCount == 0);
   4457     }
   4458 }
   4459 
   4460 uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
   4461     ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
   4462             mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
   4463     // keep track of muted state to avoid repeating mute/unmute operations
   4464     if (mBeaconMuted != mute) {
   4465         // mute/unmute AUDIO_STREAM_TTS on all outputs
   4466         ALOGV("\t muting %d", mute);
   4467         uint32_t maxLatency = 0;
   4468         for (size_t i = 0; i < mOutputs.size(); i++) {
   4469             sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
   4470             setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
   4471                     desc,
   4472                     0 /*delay*/, AUDIO_DEVICE_NONE);
   4473             const uint32_t latency = desc->latency() * 2;
   4474             if (latency > maxLatency) {
   4475                 maxLatency = latency;
   4476             }
   4477         }
   4478         mBeaconMuted = mute;
   4479         return maxLatency;
   4480     }
   4481     return 0;
   4482 }
   4483 
   4484 audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
   4485                                                          bool fromCache)
   4486 {
   4487     // Routing
   4488     // see if we have an explicit route
   4489     // scan the whole RouteMap, for each entry, convert the stream type to a strategy
   4490     // (getStrategy(stream)).
   4491     // if the strategy from the stream type in the RouteMap is the same as the argument above,
   4492     // and activity count is non-zero
   4493     // the device = the device from the descriptor in the RouteMap, and exit.
   4494     for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
   4495         sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
   4496         routing_strategy routeStrategy = getStrategy(route->mStreamType);
   4497         if ((routeStrategy == strategy) && route->isActive()) {
   4498             return route->mDeviceDescriptor->type();
   4499         }
   4500     }
   4501 
   4502     if (fromCache) {
   4503         ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
   4504               strategy, mDeviceForStrategy[strategy]);
   4505         return mDeviceForStrategy[strategy];
   4506     }
   4507     return mEngine->getDeviceForStrategy(strategy);
   4508 }
   4509 
   4510 void AudioPolicyManager::updateDevicesAndOutputs()
   4511 {
   4512     for (int i = 0; i < NUM_STRATEGIES; i++) {
   4513         mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
   4514     }
   4515     mPreviousOutputs = mOutputs;
   4516 }
   4517 
   4518 uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
   4519                                                        audio_devices_t prevDevice,
   4520                                                        uint32_t delayMs)
   4521 {
   4522     // mute/unmute strategies using an incompatible device combination
   4523     // if muting, wait for the audio in pcm buffer to be drained before proceeding
   4524     // if unmuting, unmute only after the specified delay
   4525     if (outputDesc->isDuplicated()) {
   4526         return 0;
   4527     }
   4528 
   4529     uint32_t muteWaitMs = 0;
   4530     audio_devices_t device = outputDesc->device();
   4531     bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
   4532 
   4533     for (size_t i = 0; i < NUM_STRATEGIES; i++) {
   4534         audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
   4535         curDevice = curDevice & outputDesc->supportedDevices();
   4536         bool mute = shouldMute && (curDevice & device) && (curDevice != device);
   4537         bool doMute = false;
   4538 
   4539         if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
   4540             doMute = true;
   4541             outputDesc->mStrategyMutedByDevice[i] = true;
   4542         } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
   4543             doMute = true;
   4544             outputDesc->mStrategyMutedByDevice[i] = false;
   4545         }
   4546         if (doMute) {
   4547             for (size_t j = 0; j < mOutputs.size(); j++) {
   4548                 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
   4549                 // skip output if it does not share any device with current output
   4550                 if ((desc->supportedDevices() & outputDesc->supportedDevices())
   4551                         == AUDIO_DEVICE_NONE) {
   4552                     continue;
   4553                 }
   4554                 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x)",
   4555                       mute ? "muting" : "unmuting", i, curDevice);
   4556                 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
   4557                 if (isStrategyActive(desc, (routing_strategy)i)) {
   4558                     if (mute) {
   4559                         // FIXME: should not need to double latency if volume could be applied
   4560                         // immediately by the audioflinger mixer. We must account for the delay
   4561                         // between now and the next time the audioflinger thread for this output
   4562                         // will process a buffer (which corresponds to one buffer size,
   4563                         // usually 1/2 or 1/4 of the latency).
   4564                         if (muteWaitMs < desc->latency() * 2) {
   4565                             muteWaitMs = desc->latency() * 2;
   4566                         }
   4567                     }
   4568                 }
   4569             }
   4570         }
   4571     }
   4572 
   4573     // temporary mute output if device selection changes to avoid volume bursts due to
   4574     // different per device volumes
   4575     if (outputDesc->isActive() && (device != prevDevice)) {
   4576         if (muteWaitMs < outputDesc->latency() * 2) {
   4577             muteWaitMs = outputDesc->latency() * 2;
   4578         }
   4579         for (size_t i = 0; i < NUM_STRATEGIES; i++) {
   4580             if (isStrategyActive(outputDesc, (routing_strategy)i)) {
   4581                 setStrategyMute((routing_strategy)i, true, outputDesc);
   4582                 // do tempMute unmute after twice the mute wait time
   4583                 setStrategyMute((routing_strategy)i, false, outputDesc,
   4584                                 muteWaitMs *2, device);
   4585             }
   4586         }
   4587     }
   4588 
   4589     // wait for the PCM output buffers to empty before proceeding with the rest of the command
   4590     if (muteWaitMs > delayMs) {
   4591         muteWaitMs -= delayMs;
   4592         usleep(muteWaitMs * 1000);
   4593         return muteWaitMs;
   4594     }
   4595     return 0;
   4596 }
   4597 
   4598 uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
   4599                                              audio_devices_t device,
   4600                                              bool force,
   4601                                              int delayMs,
   4602                                              audio_patch_handle_t *patchHandle,
   4603                                              const char* address)
   4604 {
   4605     ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
   4606     AudioParameter param;
   4607     uint32_t muteWaitMs;
   4608 
   4609     if (outputDesc->isDuplicated()) {
   4610         muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
   4611         muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
   4612         return muteWaitMs;
   4613     }
   4614     // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
   4615     // output profile
   4616     if ((device != AUDIO_DEVICE_NONE) &&
   4617             ((device & outputDesc->supportedDevices()) == 0)) {
   4618         return 0;
   4619     }
   4620 
   4621     // filter devices according to output selected
   4622     device = (audio_devices_t)(device & outputDesc->supportedDevices());
   4623 
   4624     audio_devices_t prevDevice = outputDesc->mDevice;
   4625 
   4626     ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
   4627 
   4628     if (device != AUDIO_DEVICE_NONE) {
   4629         outputDesc->mDevice = device;
   4630     }
   4631     muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
   4632 
   4633     // Do not change the routing if:
   4634     //      the requested device is AUDIO_DEVICE_NONE
   4635     //      OR the requested device is the same as current device
   4636     //  AND force is not specified
   4637     //  AND the output is connected by a valid audio patch.
   4638     // Doing this check here allows the caller to call setOutputDevice() without conditions
   4639     if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
   4640         !force &&
   4641         outputDesc->getPatchHandle() != 0) {
   4642         ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
   4643         return muteWaitMs;
   4644     }
   4645 
   4646     ALOGV("setOutputDevice() changing device");
   4647 
   4648     // do the routing
   4649     if (device == AUDIO_DEVICE_NONE) {
   4650         resetOutputDevice(outputDesc, delayMs, NULL);
   4651     } else {
   4652         DeviceVector deviceList;
   4653         if ((address == NULL) || (strlen(address) == 0)) {
   4654             deviceList = mAvailableOutputDevices.getDevicesFromType(device);
   4655         } else {
   4656             deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
   4657         }
   4658 
   4659         if (!deviceList.isEmpty()) {
   4660             struct audio_patch patch;
   4661             outputDesc->toAudioPortConfig(&patch.sources[0]);
   4662             patch.num_sources = 1;
   4663             patch.num_sinks = 0;
   4664             for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
   4665                 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
   4666                 patch.num_sinks++;
   4667             }
   4668             ssize_t index;
   4669             if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
   4670                 index = mAudioPatches.indexOfKey(*patchHandle);
   4671             } else {
   4672                 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
   4673             }
   4674             sp< AudioPatch> patchDesc;
   4675             audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
   4676             if (index >= 0) {
   4677                 patchDesc = mAudioPatches.valueAt(index);
   4678                 afPatchHandle = patchDesc->mAfPatchHandle;
   4679             }
   4680 
   4681             status_t status = mpClientInterface->createAudioPatch(&patch,
   4682                                                                    &afPatchHandle,
   4683                                                                    delayMs);
   4684             ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
   4685                     "num_sources %d num_sinks %d",
   4686                                        status, afPatchHandle, patch.num_sources, patch.num_sinks);
   4687             if (status == NO_ERROR) {
   4688                 if (index < 0) {
   4689                     patchDesc = new AudioPatch(&patch, mUidCached);
   4690                     addAudioPatch(patchDesc->mHandle, patchDesc);
   4691                 } else {
   4692                     patchDesc->mPatch = patch;
   4693                 }
   4694                 patchDesc->mAfPatchHandle = afPatchHandle;
   4695                 if (patchHandle) {
   4696                     *patchHandle = patchDesc->mHandle;
   4697                 }
   4698                 outputDesc->setPatchHandle(patchDesc->mHandle);
   4699                 nextAudioPortGeneration();
   4700                 mpClientInterface->onAudioPatchListUpdate();
   4701             }
   4702         }
   4703 
   4704         // inform all input as well
   4705         for (size_t i = 0; i < mInputs.size(); i++) {
   4706             const sp<AudioInputDescriptor>  inputDescriptor = mInputs.valueAt(i);
   4707             if (!is_virtual_input_device(inputDescriptor->mDevice)) {
   4708                 AudioParameter inputCmd = AudioParameter();
   4709                 ALOGV("%s: inform input %d of device:%d", __func__,
   4710                       inputDescriptor->mIoHandle, device);
   4711                 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
   4712                 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
   4713                                                  inputCmd.toString(),
   4714                                                  delayMs);
   4715             }
   4716         }
   4717     }
   4718 
   4719     // update stream volumes according to new device
   4720     applyStreamVolumes(outputDesc, device, delayMs);
   4721 
   4722     return muteWaitMs;
   4723 }
   4724 
   4725 status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
   4726                                                int delayMs,
   4727                                                audio_patch_handle_t *patchHandle)
   4728 {
   4729     ssize_t index;
   4730     if (patchHandle) {
   4731         index = mAudioPatches.indexOfKey(*patchHandle);
   4732     } else {
   4733         index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
   4734     }
   4735     if (index < 0) {
   4736         return INVALID_OPERATION;
   4737     }
   4738     sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
   4739     status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
   4740     ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
   4741     outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
   4742     removeAudioPatch(patchDesc->mHandle);
   4743     nextAudioPortGeneration();
   4744     mpClientInterface->onAudioPatchListUpdate();
   4745     return status;
   4746 }
   4747 
   4748 status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
   4749                                             audio_devices_t device,
   4750                                             bool force,
   4751                                             audio_patch_handle_t *patchHandle)
   4752 {
   4753     status_t status = NO_ERROR;
   4754 
   4755     sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
   4756     if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
   4757         inputDesc->mDevice = device;
   4758 
   4759         DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
   4760         if (!deviceList.isEmpty()) {
   4761             struct audio_patch patch;
   4762             inputDesc->toAudioPortConfig(&patch.sinks[0]);
   4763             // AUDIO_SOURCE_HOTWORD is for internal use only:
   4764             // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
   4765             if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
   4766                     !inputDesc->isSoundTrigger()) {
   4767                 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
   4768             }
   4769             patch.num_sinks = 1;
   4770             //only one input device for now
   4771             deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
   4772             patch.num_sources = 1;
   4773             ssize_t index;
   4774             if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
   4775                 index = mAudioPatches.indexOfKey(*patchHandle);
   4776             } else {
   4777                 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
   4778             }
   4779             sp< AudioPatch> patchDesc;
   4780             audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
   4781             if (index >= 0) {
   4782                 patchDesc = mAudioPatches.valueAt(index);
   4783                 afPatchHandle = patchDesc->mAfPatchHandle;
   4784             }
   4785 
   4786             status_t status = mpClientInterface->createAudioPatch(&patch,
   4787                                                                   &afPatchHandle,
   4788                                                                   0);
   4789             ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
   4790                                                                           status, afPatchHandle);
   4791             if (status == NO_ERROR) {
   4792                 if (index < 0) {
   4793                     patchDesc = new AudioPatch(&patch, mUidCached);
   4794                     addAudioPatch(patchDesc->mHandle, patchDesc);
   4795                 } else {
   4796                     patchDesc->mPatch = patch;
   4797                 }
   4798                 patchDesc->mAfPatchHandle = afPatchHandle;
   4799                 if (patchHandle) {
   4800                     *patchHandle = patchDesc->mHandle;
   4801                 }
   4802                 inputDesc->setPatchHandle(patchDesc->mHandle);
   4803                 nextAudioPortGeneration();
   4804                 mpClientInterface->onAudioPatchListUpdate();
   4805             }
   4806         }
   4807     }
   4808     return status;
   4809 }
   4810 
   4811 status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
   4812                                               audio_patch_handle_t *patchHandle)
   4813 {
   4814     sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
   4815     ssize_t index;
   4816     if (patchHandle) {
   4817         index = mAudioPatches.indexOfKey(*patchHandle);
   4818     } else {
   4819         index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
   4820     }
   4821     if (index < 0) {
   4822         return INVALID_OPERATION;
   4823     }
   4824     sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
   4825     status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
   4826     ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
   4827     inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
   4828     removeAudioPatch(patchDesc->mHandle);
   4829     nextAudioPortGeneration();
   4830     mpClientInterface->onAudioPatchListUpdate();
   4831     return status;
   4832 }
   4833 
   4834 sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
   4835                                                   String8 address,
   4836                                                   uint32_t& samplingRate,
   4837                                                   audio_format_t& format,
   4838                                                   audio_channel_mask_t& channelMask,
   4839                                                   audio_input_flags_t flags)
   4840 {
   4841     // Choose an input profile based on the requested capture parameters: select the first available
   4842     // profile supporting all requested parameters.
   4843     //
   4844     // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
   4845     // the best matching profile, not the first one.
   4846 
   4847     for (size_t i = 0; i < mHwModules.size(); i++)
   4848     {
   4849         if (mHwModules[i]->mHandle == 0) {
   4850             continue;
   4851         }
   4852         for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
   4853         {
   4854             sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
   4855             // profile->log();
   4856             if (profile->isCompatibleProfile(device, address, samplingRate,
   4857                                              &samplingRate /*updatedSamplingRate*/,
   4858                                              format,
   4859                                              &format /*updatedFormat*/,
   4860                                              channelMask,
   4861                                              &channelMask /*updatedChannelMask*/,
   4862                                              (audio_output_flags_t) flags)) {
   4863 
   4864                 return profile;
   4865             }
   4866         }
   4867     }
   4868     return NULL;
   4869 }
   4870 
   4871 
   4872 audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
   4873                                                                   AudioMix **policyMix)
   4874 {
   4875     audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
   4876     audio_devices_t selectedDeviceFromMix =
   4877            mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
   4878 
   4879     if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
   4880         return selectedDeviceFromMix;
   4881     }
   4882     return getDeviceForInputSource(inputSource);
   4883 }
   4884 
   4885 audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
   4886 {
   4887     for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
   4888          sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
   4889          if (inputSource == route->mSource && route->isActive()) {
   4890              return route->mDeviceDescriptor->type();
   4891          }
   4892      }
   4893 
   4894      return mEngine->getDeviceForInputSource(inputSource);
   4895 }
   4896 
   4897 float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
   4898                                         int index,
   4899                                         audio_devices_t device)
   4900 {
   4901     float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
   4902     // if a headset is connected, apply the following rules to ring tones and notifications
   4903     // to avoid sound level bursts in user's ears:
   4904     // - always attenuate notifications volume by 6dB
   4905     // - attenuate ring tones volume by 6dB unless music is not playing and
   4906     // speaker is part of the select devices
   4907     // - if music is playing, always limit the volume to current music volume,
   4908     // with a minimum threshold at -36dB so that notification is always perceived.
   4909     const routing_strategy stream_strategy = getStrategy(stream);
   4910     if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
   4911             AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
   4912             AUDIO_DEVICE_OUT_WIRED_HEADSET |
   4913             AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
   4914         ((stream_strategy == STRATEGY_SONIFICATION)
   4915                 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
   4916                 || (stream == AUDIO_STREAM_SYSTEM)
   4917                 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
   4918                     (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
   4919             mVolumeCurves->canBeMuted(stream)) {
   4920         // when the phone is ringing we must consider that music could have been paused just before
   4921         // by the music application and behave as if music was active if the last music track was
   4922         // just stopped
   4923         if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
   4924                 mLimitRingtoneVolume) {
   4925             volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
   4926             audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
   4927             float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
   4928                                              mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
   4929                                                                               musicDevice),
   4930                                              musicDevice);
   4931             float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
   4932                     musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
   4933             if (volumeDB > minVolDB) {
   4934                 volumeDB = minVolDB;
   4935                 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
   4936             }
   4937             if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
   4938                     AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
   4939                 // on A2DP, also ensure notification volume is not too low compared to media when
   4940                 // intended to be played
   4941                 if ((volumeDB > -96.0f) &&
   4942                         (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
   4943                     ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
   4944                             stream, device,
   4945                             volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
   4946                     volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
   4947                 }
   4948             }
   4949         } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
   4950                 stream_strategy != STRATEGY_SONIFICATION) {
   4951             volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
   4952         }
   4953     }
   4954 
   4955     return volumeDB;
   4956 }
   4957 
   4958 status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
   4959                                                    int index,
   4960                                                    const sp<AudioOutputDescriptor>& outputDesc,
   4961                                                    audio_devices_t device,
   4962                                                    int delayMs,
   4963                                                    bool force)
   4964 {
   4965     // do not change actual stream volume if the stream is muted
   4966     if (outputDesc->mMuteCount[stream] != 0) {
   4967         ALOGVV("checkAndSetVolume() stream %d muted count %d",
   4968               stream, outputDesc->mMuteCount[stream]);
   4969         return NO_ERROR;
   4970     }
   4971     audio_policy_forced_cfg_t forceUseForComm =
   4972             mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
   4973     // do not change in call volume if bluetooth is connected and vice versa
   4974     if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
   4975         (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
   4976         ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
   4977              stream, forceUseForComm);
   4978         return INVALID_OPERATION;
   4979     }
   4980 
   4981     if (device == AUDIO_DEVICE_NONE) {
   4982         device = outputDesc->device();
   4983     }
   4984 
   4985     float volumeDb = computeVolume(stream, index, device);
   4986     if (outputDesc->isFixedVolume(device)) {
   4987         volumeDb = 0.0f;
   4988     }
   4989 
   4990     outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
   4991 
   4992     if (stream == AUDIO_STREAM_VOICE_CALL ||
   4993         stream == AUDIO_STREAM_BLUETOOTH_SCO) {
   4994         float voiceVolume;
   4995         // Force voice volume to max for bluetooth SCO as volume is managed by the headset
   4996         if (stream == AUDIO_STREAM_VOICE_CALL) {
   4997             voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
   4998         } else {
   4999             voiceVolume = 1.0;
   5000         }
   5001 
   5002         if (voiceVolume != mLastVoiceVolume) {
   5003             mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
   5004             mLastVoiceVolume = voiceVolume;
   5005         }
   5006     }
   5007 
   5008     return NO_ERROR;
   5009 }
   5010 
   5011 void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
   5012                                                 audio_devices_t device,
   5013                                                 int delayMs,
   5014                                                 bool force)
   5015 {
   5016     ALOGVV("applyStreamVolumes() for device %08x", device);
   5017 
   5018     for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
   5019         checkAndSetVolume((audio_stream_type_t)stream,
   5020                           mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
   5021                           outputDesc,
   5022                           device,
   5023                           delayMs,
   5024                           force);
   5025     }
   5026 }
   5027 
   5028 void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
   5029                                              bool on,
   5030                                              const sp<AudioOutputDescriptor>& outputDesc,
   5031                                              int delayMs,
   5032                                              audio_devices_t device)
   5033 {
   5034     ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
   5035            strategy, on, outputDesc->getId());
   5036     for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
   5037         if (getStrategy((audio_stream_type_t)stream) == strategy) {
   5038             setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
   5039         }
   5040     }
   5041 }
   5042 
   5043 void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
   5044                                            bool on,
   5045                                            const sp<AudioOutputDescriptor>& outputDesc,
   5046                                            int delayMs,
   5047                                            audio_devices_t device)
   5048 {
   5049     if (device == AUDIO_DEVICE_NONE) {
   5050         device = outputDesc->device();
   5051     }
   5052 
   5053     ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
   5054           stream, on, outputDesc->mMuteCount[stream], device);
   5055 
   5056     if (on) {
   5057         if (outputDesc->mMuteCount[stream] == 0) {
   5058             if (mVolumeCurves->canBeMuted(stream) &&
   5059                     ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
   5060                      (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
   5061                 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
   5062             }
   5063         }
   5064         // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
   5065         outputDesc->mMuteCount[stream]++;
   5066     } else {
   5067         if (outputDesc->mMuteCount[stream] == 0) {
   5068             ALOGV("setStreamMute() unmuting non muted stream!");
   5069             return;
   5070         }
   5071         if (--outputDesc->mMuteCount[stream] == 0) {
   5072             checkAndSetVolume(stream,
   5073                               mVolumeCurves->getVolumeIndex(stream, device),
   5074                               outputDesc,
   5075                               device,
   5076                               delayMs);
   5077         }
   5078     }
   5079 }
   5080 
   5081 void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
   5082                                                       bool starting, bool stateChange)
   5083 {
   5084     if(!hasPrimaryOutput()) {
   5085         return;
   5086     }
   5087 
   5088     // if the stream pertains to sonification strategy and we are in call we must
   5089     // mute the stream if it is low visibility. If it is high visibility, we must play a tone
   5090     // in the device used for phone strategy and play the tone if the selected device does not
   5091     // interfere with the device used for phone strategy
   5092     // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
   5093     // many times as there are active tracks on the output
   5094     const routing_strategy stream_strategy = getStrategy(stream);
   5095     if ((stream_strategy == STRATEGY_SONIFICATION) ||
   5096             ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
   5097         sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
   5098         ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
   5099                 stream, starting, outputDesc->mDevice, stateChange);
   5100         if (outputDesc->mRefCount[stream]) {
   5101             int muteCount = 1;
   5102             if (stateChange) {
   5103                 muteCount = outputDesc->mRefCount[stream];
   5104             }
   5105             if (audio_is_low_visibility(stream)) {
   5106                 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
   5107                 for (int i = 0; i < muteCount; i++) {
   5108                     setStreamMute(stream, starting, mPrimaryOutput);
   5109                 }
   5110             } else {
   5111                 ALOGV("handleIncallSonification() high visibility");
   5112                 if (outputDesc->device() &
   5113                         getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
   5114                     ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
   5115                     for (int i = 0; i < muteCount; i++) {
   5116                         setStreamMute(stream, starting, mPrimaryOutput);
   5117                     }
   5118                 }
   5119                 if (starting) {
   5120                     mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
   5121                                                  AUDIO_STREAM_VOICE_CALL);
   5122                 } else {
   5123                     mpClientInterface->stopTone();
   5124                 }
   5125             }
   5126         }
   5127     }
   5128 }
   5129 
   5130 audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
   5131 {
   5132     // flags to stream type mapping
   5133     if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
   5134         return AUDIO_STREAM_ENFORCED_AUDIBLE;
   5135     }
   5136     if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
   5137         return AUDIO_STREAM_BLUETOOTH_SCO;
   5138     }
   5139     if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
   5140         return AUDIO_STREAM_TTS;
   5141     }
   5142 
   5143     // usage to stream type mapping
   5144     switch (attr->usage) {
   5145     case AUDIO_USAGE_MEDIA:
   5146     case AUDIO_USAGE_GAME:
   5147     case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
   5148         return AUDIO_STREAM_MUSIC;
   5149     case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
   5150         return AUDIO_STREAM_ACCESSIBILITY;
   5151     case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
   5152         return AUDIO_STREAM_SYSTEM;
   5153     case AUDIO_USAGE_VOICE_COMMUNICATION:
   5154         return AUDIO_STREAM_VOICE_CALL;
   5155 
   5156     case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
   5157         return AUDIO_STREAM_DTMF;
   5158 
   5159     case AUDIO_USAGE_ALARM:
   5160         return AUDIO_STREAM_ALARM;
   5161     case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
   5162         return AUDIO_STREAM_RING;
   5163 
   5164     case AUDIO_USAGE_NOTIFICATION:
   5165     case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
   5166     case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
   5167     case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
   5168     case AUDIO_USAGE_NOTIFICATION_EVENT:
   5169         return AUDIO_STREAM_NOTIFICATION;
   5170 
   5171     case AUDIO_USAGE_UNKNOWN:
   5172     default:
   5173         return AUDIO_STREAM_MUSIC;
   5174     }
   5175 }
   5176 
   5177 bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
   5178 {
   5179     // has flags that map to a strategy?
   5180     if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
   5181         return true;
   5182     }
   5183 
   5184     // has known usage?
   5185     switch (paa->usage) {
   5186     case AUDIO_USAGE_UNKNOWN:
   5187     case AUDIO_USAGE_MEDIA:
   5188     case AUDIO_USAGE_VOICE_COMMUNICATION:
   5189     case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
   5190     case AUDIO_USAGE_ALARM:
   5191     case AUDIO_USAGE_NOTIFICATION:
   5192     case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
   5193     case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
   5194     case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
   5195     case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
   5196     case AUDIO_USAGE_NOTIFICATION_EVENT:
   5197     case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
   5198     case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
   5199     case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
   5200     case AUDIO_USAGE_GAME:
   5201     case AUDIO_USAGE_VIRTUAL_SOURCE:
   5202         break;
   5203     default:
   5204         return false;
   5205     }
   5206     return true;
   5207 }
   5208 
   5209 bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor> outputDesc,
   5210                                           routing_strategy strategy, uint32_t inPastMs,
   5211                                           nsecs_t sysTime) const
   5212 {
   5213     if ((sysTime == 0) && (inPastMs != 0)) {
   5214         sysTime = systemTime();
   5215     }
   5216     for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
   5217         if (((getStrategy((audio_stream_type_t)i) == strategy) ||
   5218                 (NUM_STRATEGIES == strategy)) &&
   5219                 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
   5220             return true;
   5221         }
   5222     }
   5223     return false;
   5224 }
   5225 
   5226 audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
   5227 {
   5228     return mEngine->getForceUse(usage);
   5229 }
   5230 
   5231 bool AudioPolicyManager::isInCall()
   5232 {
   5233     return isStateInCall(mEngine->getPhoneState());
   5234 }
   5235 
   5236 bool AudioPolicyManager::isStateInCall(int state)
   5237 {
   5238     return is_state_in_call(state);
   5239 }
   5240 
   5241 void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
   5242 {
   5243     for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--)  {
   5244         sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
   5245         if (sourceDesc->mDevice->equals(deviceDesc)) {
   5246             ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
   5247             stopAudioSource(sourceDesc->getHandle());
   5248         }
   5249     }
   5250 
   5251     for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--)  {
   5252         sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
   5253         bool release = false;
   5254         for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++)  {
   5255             const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
   5256             if (source->type == AUDIO_PORT_TYPE_DEVICE &&
   5257                     source->ext.device.type == deviceDesc->type()) {
   5258                 release = true;
   5259             }
   5260         }
   5261         for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++)  {
   5262             const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
   5263             if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
   5264                     sink->ext.device.type == deviceDesc->type()) {
   5265                 release = true;
   5266             }
   5267         }
   5268         if (release) {
   5269             ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
   5270             releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
   5271         }
   5272     }
   5273 }
   5274 
   5275 // Modify the list of surround sound formats supported.
   5276 void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
   5277     FormatVector &formats = *formatsPtr;
   5278     // TODO Set this based on Config properties.
   5279     const bool alwaysForceAC3 = true;
   5280 
   5281     audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
   5282             AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
   5283     ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
   5284 
   5285     // Analyze original support for various formats.
   5286     bool supportsAC3 = false;
   5287     bool supportsOtherSurround = false;
   5288     bool supportsIEC61937 = false;
   5289     for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
   5290         audio_format_t format = formats[formatIndex];
   5291         switch (format) {
   5292             case AUDIO_FORMAT_AC3:
   5293                 supportsAC3 = true;
   5294                 break;
   5295             case AUDIO_FORMAT_E_AC3:
   5296             case AUDIO_FORMAT_DTS:
   5297             case AUDIO_FORMAT_DTS_HD:
   5298                 supportsOtherSurround = true;
   5299                 break;
   5300             case AUDIO_FORMAT_IEC61937:
   5301                 supportsIEC61937 = true;
   5302                 break;
   5303             default:
   5304                 break;
   5305         }
   5306     }
   5307 
   5308     // Modify formats based on surround preferences.
   5309     // If NEVER, remove support for surround formats.
   5310     if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
   5311         if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
   5312             // Remove surround sound related formats.
   5313             for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
   5314                 audio_format_t format = formats[formatIndex];
   5315                 switch(format) {
   5316                     case AUDIO_FORMAT_AC3:
   5317                     case AUDIO_FORMAT_E_AC3:
   5318                     case AUDIO_FORMAT_DTS:
   5319                     case AUDIO_FORMAT_DTS_HD:
   5320                     case AUDIO_FORMAT_IEC61937:
   5321                         formats.removeAt(formatIndex);
   5322                         break;
   5323                     default:
   5324                         formatIndex++; // keep it
   5325                         break;
   5326                 }
   5327             }
   5328             supportsAC3 = false;
   5329             supportsOtherSurround = false;
   5330             supportsIEC61937 = false;
   5331         }
   5332     } else { // AUTO or ALWAYS
   5333         // Most TVs support AC3 even if they do not report it in the EDID.
   5334         if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
   5335                 && !supportsAC3) {
   5336             formats.add(AUDIO_FORMAT_AC3);
   5337             supportsAC3 = true;
   5338         }
   5339 
   5340         // If ALWAYS, add support for raw surround formats if all are missing.
   5341         // This assumes that if any of these formats are reported by the HAL
   5342         // then the report is valid and should not be modified.
   5343         if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS)
   5344                 && !supportsOtherSurround) {
   5345             formats.add(AUDIO_FORMAT_E_AC3);
   5346             formats.add(AUDIO_FORMAT_DTS);
   5347             formats.add(AUDIO_FORMAT_DTS_HD);
   5348             supportsOtherSurround = true;
   5349         }
   5350 
   5351         // Add support for IEC61937 if any raw surround supported.
   5352         // The HAL could do this but add it here, just in case.
   5353         if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
   5354             formats.add(AUDIO_FORMAT_IEC61937);
   5355             supportsIEC61937 = true;
   5356         }
   5357     }
   5358 }
   5359 
   5360 // Modify the list of channel masks supported.
   5361 void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
   5362     ChannelsVector &channelMasks = *channelMasksPtr;
   5363     audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
   5364             AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
   5365 
   5366     // If NEVER, then remove support for channelMasks > stereo.
   5367     if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
   5368         for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
   5369             audio_channel_mask_t channelMask = channelMasks[maskIndex];
   5370             if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
   5371                 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
   5372                 channelMasks.removeAt(maskIndex);
   5373             } else {
   5374                 maskIndex++;
   5375             }
   5376         }
   5377     // If ALWAYS, then make sure we at least support 5.1
   5378     } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
   5379         bool supports5dot1 = false;
   5380         // Are there any channel masks that can be considered "surround"?
   5381         for (size_t maskIndex = 0; maskIndex < channelMasks.size(); maskIndex++) {
   5382             audio_channel_mask_t channelMask = channelMasks[maskIndex];
   5383             if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
   5384                 supports5dot1 = true;
   5385                 break;
   5386             }
   5387         }
   5388         // If not then add 5.1 support.
   5389         if (!supports5dot1) {
   5390             channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
   5391             ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
   5392         }
   5393     }
   5394 }
   5395 
   5396 void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
   5397                                              audio_io_handle_t ioHandle,
   5398                                              AudioProfileVector &profiles)
   5399 {
   5400     String8 reply;
   5401     char *value;
   5402 
   5403     // Format MUST be checked first to update the list of AudioProfile
   5404     if (profiles.hasDynamicFormat()) {
   5405         reply = mpClientInterface->getParameters(ioHandle,
   5406                                                  String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
   5407         ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
   5408         AudioParameter repliedParameters(reply);
   5409         if (repliedParameters.get(
   5410                 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS), reply) != NO_ERROR) {
   5411             ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
   5412             return;
   5413         }
   5414         FormatVector formats = formatsFromString(reply.string());
   5415         if (device == AUDIO_DEVICE_OUT_HDMI) {
   5416             filterSurroundFormats(&formats);
   5417         }
   5418         profiles.setFormats(formats);
   5419     }
   5420     const FormatVector &supportedFormats = profiles.getSupportedFormats();
   5421 
   5422     for (size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
   5423         audio_format_t format = supportedFormats[formatIndex];
   5424         ChannelsVector channelMasks;
   5425         SampleRateVector samplingRates;
   5426         AudioParameter requestedParameters;
   5427         requestedParameters.addInt(String8(AUDIO_PARAMETER_STREAM_FORMAT), format);
   5428 
   5429         if (profiles.hasDynamicRateFor(format)) {
   5430             reply = mpClientInterface->getParameters(ioHandle,
   5431                                                      requestedParameters.toString() + ";" +
   5432                                                      AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES);
   5433             ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
   5434             AudioParameter repliedParameters(reply);
   5435             if (repliedParameters.get(
   5436                     String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES), reply) == NO_ERROR) {
   5437                 samplingRates = samplingRatesFromString(reply.string());
   5438             }
   5439         }
   5440         if (profiles.hasDynamicChannelsFor(format)) {
   5441             reply = mpClientInterface->getParameters(ioHandle,
   5442                                                      requestedParameters.toString() + ";" +
   5443                                                      AUDIO_PARAMETER_STREAM_SUP_CHANNELS);
   5444             ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
   5445             AudioParameter repliedParameters(reply);
   5446             if (repliedParameters.get(
   5447                     String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS), reply) == NO_ERROR) {
   5448                 channelMasks = channelMasksFromString(reply.string());
   5449                 if (device == AUDIO_DEVICE_OUT_HDMI) {
   5450                     filterSurroundChannelMasks(&channelMasks);
   5451                 }
   5452             }
   5453         }
   5454         profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
   5455     }
   5456 }
   5457 
   5458 }; // namespace android
   5459