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