blob: 7d69e4f04e5aacc0cfe3fc19a509e9a923d61978 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
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
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#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
François Gaffief4ad6e52015-11-19 16:59:57 +010027#define AUDIO_POLICY_XML_CONFIG_FILE "/system/etc/audio_policy_configuration.xml"
28
Eric Laurentd4692962014-05-05 18:13:44 -070029#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070030#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070031
François Gaffie2110e042015-03-24 08:41:51 +010032#include <AudioPolicyManagerInterface.h>
33#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070034#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070035#include <utils/Log.h>
36#include <hardware/audio.h>
37#include <hardware/audio_effect.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070038#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080039#include <media/AudioPolicyHelper.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070040#include <soundtrigger/SoundTrigger.h>
Eric Laurentd4692962014-05-05 18:13:44 -070041#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010042#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010043#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010044#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010045#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010046#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010047#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010048#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070049
Eric Laurent3b73df72014-03-11 09:06:29 -070050namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070051
Eric Laurentdc462862016-07-19 12:29:53 -070052//FIXME: workaround for truncated touch sounds
53// to be removed when the problem is handled by system UI
54#define TOUCH_SOUND_FIXED_DELAY_MS 100
Eric Laurente552edb2014-03-10 17:42:56 -070055// ----------------------------------------------------------------------------
56// AudioPolicyInterface implementation
57// ----------------------------------------------------------------------------
58
Eric Laurente0720872014-03-11 09:30:41 -070059status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080060 audio_policy_dev_state_t state,
61 const char *device_address,
62 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070063{
Paul McLeane743a472015-01-28 11:07:31 -080064 return setDeviceConnectionStateInt(device, state, device_address, device_name);
Eric Laurentc73ca6e2014-12-12 14:34:22 -080065}
66
François Gaffie44481e72016-04-20 07:49:57 +020067void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
68 audio_policy_dev_state_t state,
69 const String8 &device_address)
70{
71 AudioParameter param(device_address);
72 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
73 AUDIO_PARAMETER_DEVICE_CONNECT : AUDIO_PARAMETER_DEVICE_DISCONNECT);
74 param.addInt(key, device);
75 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
76}
77
Eric Laurentc73ca6e2014-12-12 14:34:22 -080078status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -080079 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -080080 const char *device_address,
81 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -080082{
Paul McLeane743a472015-01-28 11:07:31 -080083 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
84- device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -070085
86 // connect/disconnect only 1 device at a time
87 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
88
François Gaffie53615e22015-03-19 09:24:12 +010089 sp<DeviceDescriptor> devDesc =
90 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -080091
Eric Laurente552edb2014-03-10 17:42:56 -070092 // handle output devices
93 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -070094 SortedVector <audio_io_handle_t> outputs;
95
Eric Laurent3a4311c2014-03-17 12:00:47 -070096 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
97
Eric Laurente552edb2014-03-10 17:42:56 -070098 // save a copy of the opened output descriptors before any output is opened or closed
99 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
100 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700101 switch (state)
102 {
103 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800104 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700105 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700106 ALOGW("setDeviceConnectionState() device already connected: %x", device);
107 return INVALID_OPERATION;
108 }
109 ALOGV("setDeviceConnectionState() connecting device %x", device);
110
Eric Laurente552edb2014-03-10 17:42:56 -0700111 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700112 index = mAvailableOutputDevices.add(devDesc);
113 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100114 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700115 if (module == 0) {
116 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
117 device);
118 mAvailableOutputDevices.remove(devDesc);
119 return INVALID_OPERATION;
120 }
Paul McLeane743a472015-01-28 11:07:31 -0800121 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700122 } else {
123 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700124 }
125
François Gaffie44481e72016-04-20 07:49:57 +0200126 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
127 // parameters on newly connected devices (instead of opening the outputs...)
128 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
129
Eric Laurenta1d525f2015-01-29 13:36:45 -0800130 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700131 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200132
133 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
134 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700135 return INVALID_OPERATION;
136 }
François Gaffie2110e042015-03-24 08:41:51 +0100137 // Propagate device availability to Engine
138 mEngine->setDeviceConnectionState(devDesc, state);
139
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700140 // outputs should never be empty here
141 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
142 "checkOutputsForDevice() returned no outputs but status OK");
143 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
144 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800145
Eric Laurent3ae5f312015-02-03 17:12:08 -0800146 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700147 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700148 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700149 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700150 ALOGW("setDeviceConnectionState() device not connected: %x", device);
151 return INVALID_OPERATION;
152 }
153
Paul McLean5c477aa2014-08-20 16:47:57 -0700154 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
155
Paul McLeane743a472015-01-28 11:07:31 -0800156 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200157 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700158
Eric Laurente552edb2014-03-10 17:42:56 -0700159 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700160 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700161
Eric Laurenta1d525f2015-01-29 13:36:45 -0800162 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100163
164 // Propagate device availability to Engine
165 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700166 } break;
167
168 default:
169 ALOGE("setDeviceConnectionState() invalid state: %x", state);
170 return BAD_VALUE;
171 }
172
Eric Laurent3a4311c2014-03-17 12:00:47 -0700173 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
174 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700175 checkA2dpSuspend();
176 checkOutputForAllStrategies();
177 // outputs must be closed after checkOutputForAllStrategies() is executed
178 if (!outputs.isEmpty()) {
179 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700180 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700181 // close unused outputs after device disconnection or direct outputs that have been
182 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700183 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700184 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
185 (desc->mDirectOpenCount == 0))) {
186 closeOutput(outputs[i]);
187 }
188 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700189 // check again after closing A2DP output to reset mA2dpSuspended if needed
190 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700191 }
192
193 updateDevicesAndOutputs();
Eric Laurent87ffa392015-05-22 10:32:38 -0700194 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700195 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
196 updateCallRouting(newDevice);
197 }
Eric Laurente552edb2014-03-10 17:42:56 -0700198 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700199 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
200 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
201 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700202 // do not force device change on duplicated output because if device is 0, it will
203 // also force a device 0 for the two outputs it is duplicated to which may override
204 // a valid device selection on those outputs.
Eric Laurentc75307b2015-03-17 15:29:32 -0700205 bool force = !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100206 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700207 // always force when disconnecting (a non-duplicated device)
208 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700209 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700210 }
Eric Laurente552edb2014-03-10 17:42:56 -0700211 }
212
Eric Laurentd60560a2015-04-10 11:31:20 -0700213 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
214 cleanUpForDevice(devDesc);
215 }
216
Eric Laurent72aa32f2014-05-30 18:51:48 -0700217 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700218 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700219 } // end if is output device
220
Eric Laurente552edb2014-03-10 17:42:56 -0700221 // handle input devices
222 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700223 SortedVector <audio_io_handle_t> inputs;
224
Eric Laurent3a4311c2014-03-17 12:00:47 -0700225 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700226 switch (state)
227 {
228 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700229 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700230 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700231 ALOGW("setDeviceConnectionState() device already connected: %d", device);
232 return INVALID_OPERATION;
233 }
François Gaffie53615e22015-03-19 09:24:12 +0100234 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700235 if (module == NULL) {
236 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
237 device);
238 return INVALID_OPERATION;
239 }
François Gaffie44481e72016-04-20 07:49:57 +0200240
241 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
242 // parameters on newly connected devices (instead of opening the inputs...)
243 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
244
Paul McLean9080a4c2015-06-18 08:24:02 -0700245 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200246 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
247 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700248 return INVALID_OPERATION;
249 }
250
Eric Laurent3a4311c2014-03-17 12:00:47 -0700251 index = mAvailableInputDevices.add(devDesc);
252 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800253 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700254 } else {
255 return NO_MEMORY;
256 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800257
François Gaffie2110e042015-03-24 08:41:51 +0100258 // Propagate device availability to Engine
259 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700260 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700261
262 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700263 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700264 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700265 ALOGW("setDeviceConnectionState() device not connected: %d", device);
266 return INVALID_OPERATION;
267 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700268
269 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
270
271 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200272 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700273
Paul McLean9080a4c2015-06-18 08:24:02 -0700274 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700275 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700276
François Gaffie2110e042015-03-24 08:41:51 +0100277 // Propagate device availability to Engine
278 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700279 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700280
281 default:
282 ALOGE("setDeviceConnectionState() invalid state: %x", state);
283 return BAD_VALUE;
284 }
285
Eric Laurentd4692962014-05-05 18:13:44 -0700286 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700287
Eric Laurent87ffa392015-05-22 10:32:38 -0700288 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700289 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
290 updateCallRouting(newDevice);
291 }
292
Eric Laurentd60560a2015-04-10 11:31:20 -0700293 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
294 cleanUpForDevice(devDesc);
295 }
296
Eric Laurentb52c1522014-05-20 11:27:36 -0700297 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700298 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700299 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700300
301 ALOGW("setDeviceConnectionState() invalid device: %x", device);
302 return BAD_VALUE;
303}
304
Eric Laurente0720872014-03-11 09:30:41 -0700305audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100306 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700307{
Eric Laurent634b7142016-04-20 13:48:02 -0700308 sp<DeviceDescriptor> devDesc =
309 mHwModules.getDeviceDescriptor(device, device_address, "",
310 (strlen(device_address) != 0)/*matchAddress*/);
311
312 if (devDesc == 0) {
313 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
314 device, device_address);
315 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
316 }
François Gaffie53615e22015-03-19 09:24:12 +0100317
Eric Laurent3a4311c2014-03-17 12:00:47 -0700318 DeviceVector *deviceVector;
319
Eric Laurente552edb2014-03-10 17:42:56 -0700320 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700321 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700322 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700323 deviceVector = &mAvailableInputDevices;
324 } else {
325 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
326 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700327 }
Eric Laurent634b7142016-04-20 13:48:02 -0700328
329 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
330 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800331}
332
Eric Laurentdc462862016-07-19 12:29:53 -0700333uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700334{
335 bool createTxPatch = false;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700336 status_t status;
337 audio_patch_handle_t afPatchHandle;
338 DeviceVector deviceList;
Eric Laurentdc462862016-07-19 12:29:53 -0700339 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700340
Eric Laurent87ffa392015-05-22 10:32:38 -0700341 if(!hasPrimaryOutput()) {
Eric Laurentdc462862016-07-19 12:29:53 -0700342 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700343 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800344 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700345 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
346
347 // release existing RX patch if any
348 if (mCallRxPatch != 0) {
349 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
350 mCallRxPatch.clear();
351 }
352 // release TX patch if any
353 if (mCallTxPatch != 0) {
354 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
355 mCallTxPatch.clear();
356 }
357
358 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
359 // via setOutputDevice() on primary output.
360 // Otherwise, create two audio patches for TX and RX path.
361 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700362 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700363 // If the TX device is also on the primary HW module, setOutputDevice() will take care
364 // of it due to legacy implementation. If not, create a patch.
365 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
366 == AUDIO_DEVICE_NONE) {
367 createTxPatch = true;
368 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700369 } else { // create RX path audio patch
370 struct audio_patch patch;
371
372 patch.num_sources = 1;
373 patch.num_sinks = 1;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700374 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
375 ALOG_ASSERT(!deviceList.isEmpty(),
376 "updateCallRouting() selected device not in output device list");
377 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
378 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
379 ALOG_ASSERT(!deviceList.isEmpty(),
380 "updateCallRouting() no telephony RX device");
381 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
382
383 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
384 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
385
386 // request to reuse existing output stream if one is already opened to reach the RX device
387 SortedVector<audio_io_handle_t> outputs =
388 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700389 audio_io_handle_t output = selectOutput(outputs,
390 AUDIO_OUTPUT_FLAG_NONE,
391 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700392 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700393 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700394 ALOG_ASSERT(!outputDesc->isDuplicated(),
395 "updateCallRouting() RX device output is duplicated");
396 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700397 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700398 patch.num_sources = 2;
399 }
400
401 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700402 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700403 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
404 status);
405 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100406 mCallRxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700407 mCallRxPatch->mAfPatchHandle = afPatchHandle;
408 mCallRxPatch->mUid = mUidCached;
409 }
410 createTxPatch = true;
411 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700412 if (createTxPatch) { // create TX path audio patch
Eric Laurentc2730ba2014-07-20 15:47:07 -0700413 struct audio_patch patch;
Eric Laurent8ae73122016-04-12 10:13:29 -0700414
Eric Laurentc2730ba2014-07-20 15:47:07 -0700415 patch.num_sources = 1;
416 patch.num_sinks = 1;
417 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
418 ALOG_ASSERT(!deviceList.isEmpty(),
419 "updateCallRouting() selected device not in input device list");
420 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
421 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
422 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
423 ALOG_ASSERT(!deviceList.isEmpty(),
424 "updateCallRouting() no telephony TX device");
425 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
426 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
427
428 SortedVector<audio_io_handle_t> outputs =
429 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700430 audio_io_handle_t output = selectOutput(outputs,
431 AUDIO_OUTPUT_FLAG_NONE,
432 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700433 // request to reuse existing output stream if one is already opened to reach the TX
434 // path output device
435 if (output != AUDIO_IO_HANDLE_NONE) {
436 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
437 ALOG_ASSERT(!outputDesc->isDuplicated(),
438 "updateCallRouting() RX device output is duplicated");
439 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700440 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700441 patch.num_sources = 2;
442 }
443
Eric Laurentc0a889f2015-10-14 14:36:34 -0700444 // terminate active capture if on the same HW module as the call TX source device
445 // FIXME: would be better to refine to only inputs whose profile connects to the
446 // call TX device but this information is not in the audio patch and logic here must be
447 // symmetric to the one in startInput()
Eric Laurentfb66dd92016-01-28 18:32:03 -0800448 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
449 for (size_t i = 0; i < activeInputs.size(); i++) {
450 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
451 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
452 AudioSessionCollection activeSessions =
453 activeDesc->getAudioSessions(true /*activeOnly*/);
454 for (size_t j = 0; j < activeSessions.size(); j++) {
455 audio_session_t activeSession = activeSessions.keyAt(j);
456 stopInput(activeDesc->mIoHandle, activeSession);
457 releaseInput(activeDesc->mIoHandle, activeSession);
458 }
Eric Laurentc0a889f2015-10-14 14:36:34 -0700459 }
460 }
461
Eric Laurentc2730ba2014-07-20 15:47:07 -0700462 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700463 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700464 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
465 status);
466 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100467 mCallTxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700468 mCallTxPatch->mAfPatchHandle = afPatchHandle;
469 mCallTxPatch->mUid = mUidCached;
470 }
471 }
Eric Laurentdc462862016-07-19 12:29:53 -0700472
473 return muteWaitMs;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700474}
475
Eric Laurente0720872014-03-11 09:30:41 -0700476void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700477{
478 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100479 // store previous phone state for management of sonification strategy below
480 int oldState = mEngine->getPhoneState();
481
482 if (mEngine->setPhoneState(state) != NO_ERROR) {
483 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700484 return;
485 }
François Gaffie2110e042015-03-24 08:41:51 +0100486 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700487 // if leaving call state, handle special case of active streams
488 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700489 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700490 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800491 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700492 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700493 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800494
Eric Laurent63dea1d2015-07-02 17:10:28 -0700495 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800496 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700497 }
498
François Gaffie2110e042015-03-24 08:41:51 +0100499 /**
500 * Switching to or from incall state or switching between telephony and VoIP lead to force
501 * routing command.
502 */
503 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
504 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700505
506 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700507 checkA2dpSuspend();
508 checkOutputForAllStrategies();
509 updateDevicesAndOutputs();
510
Eric Laurente552edb2014-03-10 17:42:56 -0700511 int delayMs = 0;
512 if (isStateInCall(state)) {
513 nsecs_t sysTime = systemTime();
514 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700515 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700516 // mute media and sonification strategies and delay device switch by the largest
517 // latency of any output where either strategy is active.
518 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100519 if ((isStrategyActive(desc, STRATEGY_MEDIA,
520 SONIFICATION_HEADSET_MUSIC_DELAY,
521 sysTime) ||
522 isStrategyActive(desc, STRATEGY_SONIFICATION,
523 SONIFICATION_HEADSET_MUSIC_DELAY,
524 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700525 (delayMs < (int)desc->latency()*2)) {
526 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700527 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700528 setStrategyMute(STRATEGY_MEDIA, true, desc);
529 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700530 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700531 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
532 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700533 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
534 }
535 }
536
Eric Laurent87ffa392015-05-22 10:32:38 -0700537 if (hasPrimaryOutput()) {
538 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
539 // the device returned is not necessarily reachable via this output
540 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
541 // force routing command to audio hardware when ending call
542 // even if no device change is needed
543 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
544 rxDevice = mPrimaryOutput->device();
545 }
Eric Laurente552edb2014-03-10 17:42:56 -0700546
Eric Laurent87ffa392015-05-22 10:32:38 -0700547 if (state == AUDIO_MODE_IN_CALL) {
548 updateCallRouting(rxDevice, delayMs);
549 } else if (oldState == AUDIO_MODE_IN_CALL) {
550 if (mCallRxPatch != 0) {
551 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
552 mCallRxPatch.clear();
553 }
554 if (mCallTxPatch != 0) {
555 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
556 mCallTxPatch.clear();
557 }
558 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
559 } else {
560 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700561 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700562 }
Eric Laurente552edb2014-03-10 17:42:56 -0700563 // if entering in call state, handle special case of active streams
564 // pertaining to sonification strategy see handleIncallSonification()
565 if (isStateInCall(state)) {
566 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800567 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700568 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700569 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700570
571 // force reevaluating accessibility routing when call starts
572 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700573 }
574
575 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700576 if (state == AUDIO_MODE_RINGTONE &&
577 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700578 mLimitRingtoneVolume = true;
579 } else {
580 mLimitRingtoneVolume = false;
581 }
582}
583
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700584audio_mode_t AudioPolicyManager::getPhoneState() {
585 return mEngine->getPhoneState();
586}
587
Eric Laurente0720872014-03-11 09:30:41 -0700588void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700589 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700590{
François Gaffie2110e042015-03-24 08:41:51 +0100591 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -0700592
François Gaffie2110e042015-03-24 08:41:51 +0100593 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
594 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
595 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700596 }
François Gaffie2110e042015-03-24 08:41:51 +0100597 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
598 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
599 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700600
601 // check for device and output changes triggered by new force usage
602 checkA2dpSuspend();
603 checkOutputForAllStrategies();
604 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800605
Eric Laurentdc462862016-07-19 12:29:53 -0700606 //FIXME: workaround for truncated touch sounds
607 // to be removed when the problem is handled by system UI
608 uint32_t delayMs = 0;
609 uint32_t waitMs = 0;
610 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
611 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
612 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700613 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700614 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700615 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700616 }
Eric Laurente552edb2014-03-10 17:42:56 -0700617 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700618 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
619 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
620 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700621 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
622 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700623 }
Eric Laurente552edb2014-03-10 17:42:56 -0700624 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700625 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700626 }
627 }
628
Eric Laurentfb66dd92016-01-28 18:32:03 -0800629 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
630 for (size_t i = 0; i < activeInputs.size(); i++) {
631 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
632 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700633 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800634 if (activeDesc->mProfile->getSupportedDevices().types() &
635 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
636 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700637 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800638 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700639 }
Eric Laurente552edb2014-03-10 17:42:56 -0700640 }
Eric Laurente552edb2014-03-10 17:42:56 -0700641}
642
Eric Laurente0720872014-03-11 09:30:41 -0700643void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700644{
645 ALOGV("setSystemProperty() property %s, value %s", property, value);
646}
647
648// Find a direct output profile compatible with the parameters passed, even if the input flags do
649// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800650sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700651 audio_devices_t device,
652 uint32_t samplingRate,
653 audio_format_t format,
654 audio_channel_mask_t channelMask,
655 audio_output_flags_t flags)
656{
Eric Laurent861a6282015-05-18 15:40:16 -0700657 // only retain flags that will drive the direct output profile selection
658 // if explicitly requested
659 static const uint32_t kRelevantFlags =
660 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
661 flags =
662 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
663
664 sp<IOProfile> profile;
665
Eric Laurente552edb2014-03-10 17:42:56 -0700666 for (size_t i = 0; i < mHwModules.size(); i++) {
667 if (mHwModules[i]->mHandle == 0) {
668 continue;
669 }
670 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent861a6282015-05-18 15:40:16 -0700671 sp<IOProfile> curProfile = mHwModules[i]->mOutputProfiles[j];
672 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700673 samplingRate, NULL /*updatedSamplingRate*/,
674 format, NULL /*updatedFormat*/,
675 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700676 flags)) {
677 continue;
678 }
679 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100680 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700681 continue;
682 }
683 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100684 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700685 continue;
686 }
687 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100688 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700689 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700690 }
Eric Laurente552edb2014-03-10 17:42:56 -0700691 }
692 }
Eric Laurent861a6282015-05-18 15:40:16 -0700693 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700694}
695
Eric Laurente0720872014-03-11 09:30:41 -0700696audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +0100697 uint32_t samplingRate,
698 audio_format_t format,
699 audio_channel_mask_t channelMask,
700 audio_output_flags_t flags,
701 const audio_offload_info_t *offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -0700702{
Eric Laurent3b73df72014-03-11 09:06:29 -0700703 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700704 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
705 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
706 device, stream, samplingRate, format, channelMask, flags);
707
Eric Laurente83b55d2014-11-14 10:06:21 -0800708 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
709 stream, samplingRate,format, channelMask,
710 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700711}
712
Eric Laurente83b55d2014-11-14 10:06:21 -0800713status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
714 audio_io_handle_t *output,
715 audio_session_t session,
716 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700717 uid_t uid,
Eric Laurente83b55d2014-11-14 10:06:21 -0800718 uint32_t samplingRate,
719 audio_format_t format,
720 audio_channel_mask_t channelMask,
721 audio_output_flags_t flags,
Paul McLeanaa981192015-03-21 09:55:15 -0700722 audio_port_handle_t selectedDeviceId,
Eric Laurente83b55d2014-11-14 10:06:21 -0800723 const audio_offload_info_t *offloadInfo)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700724{
Eric Laurente83b55d2014-11-14 10:06:21 -0800725 audio_attributes_t attributes;
726 if (attr != NULL) {
727 if (!isValidAttributes(attr)) {
728 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
729 attr->usage, attr->content_type, attr->flags,
730 attr->tags);
731 return BAD_VALUE;
732 }
733 attributes = *attr;
734 } else {
735 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
736 ALOGE("getOutputForAttr(): invalid stream type");
737 return BAD_VALUE;
738 }
739 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700740 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700741 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800742 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100743 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Phil Burkfdb3c072016-02-09 10:47:02 -0800744 if (!audio_has_proportional_frames(format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100745 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800746 }
François Gaffie036e1e92015-03-19 10:16:24 +0100747 *stream = streamTypefromAttributesInt(&attributes);
748 *output = desc->mIoHandle;
749 ALOGV("getOutputForAttr() returns output %d", *output);
750 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800751 }
752 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
753 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
754 return BAD_VALUE;
755 }
756
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700757 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
758 " session %d selectedDeviceId %d",
759 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
760 session, selectedDeviceId);
761
762 *stream = streamTypefromAttributesInt(&attributes);
763
764 // Explicit routing?
765 sp<DeviceDescriptor> deviceDesc;
766 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
767 if (mAvailableOutputDevices[i]->getId() == selectedDeviceId) {
768 deviceDesc = mAvailableOutputDevices[i];
769 break;
770 }
771 }
772 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700773
Eric Laurente83b55d2014-11-14 10:06:21 -0800774 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700775 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700776
Eric Laurente83b55d2014-11-14 10:06:21 -0800777 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700778 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
779 }
780
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700781 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700782 device, samplingRate, format, channelMask, flags);
783
Eric Laurente83b55d2014-11-14 10:06:21 -0800784 *output = getOutputForDevice(device, session, *stream,
785 samplingRate, format, channelMask,
786 flags, offloadInfo);
787 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700788 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800789 return INVALID_OPERATION;
790 }
Paul McLeanaa981192015-03-21 09:55:15 -0700791
Eric Laurente83b55d2014-11-14 10:06:21 -0800792 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700793}
794
795audio_io_handle_t AudioPolicyManager::getOutputForDevice(
796 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800797 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700798 audio_stream_type_t stream,
799 uint32_t samplingRate,
800 audio_format_t format,
801 audio_channel_mask_t channelMask,
802 audio_output_flags_t flags,
803 const audio_offload_info_t *offloadInfo)
804{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700805 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700806 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700807
Eric Laurente552edb2014-03-10 17:42:56 -0700808#ifdef AUDIO_POLICY_TEST
809 if (mCurOutput != 0) {
810 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
811 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
812
813 if (mTestOutputs[mCurOutput] == 0) {
814 ALOGV("getOutput() opening test output");
Eric Laurentc75307b2015-03-17 15:29:32 -0700815 sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
816 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700817 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700818 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700819 outputDesc->mFlags =
820 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700821 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700822 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
823 config.sample_rate = mTestSamplingRate;
824 config.channel_mask = mTestChannels;
825 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700826 if (offloadInfo != NULL) {
827 config.offload_info = *offloadInfo;
828 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700829 status = mpClientInterface->openOutput(0,
830 &mTestOutputs[mCurOutput],
831 &config,
832 &outputDesc->mDevice,
833 String8(""),
834 &outputDesc->mLatency,
835 outputDesc->mFlags);
836 if (status == NO_ERROR) {
837 outputDesc->mSamplingRate = config.sample_rate;
838 outputDesc->mFormat = config.format;
839 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700840 AudioParameter outputCmd = AudioParameter();
841 outputCmd.addInt(String8("set_id"),mCurOutput);
842 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
843 addOutput(mTestOutputs[mCurOutput], outputDesc);
844 }
845 }
846 return mTestOutputs[mCurOutput];
847 }
848#endif //AUDIO_POLICY_TEST
849
850 // open a direct output if required by specified parameters
851 //force direct flag if offload flag is set: offloading implies a direct output stream
852 // and all common behaviors are driven by checking only the direct flag
853 // this should normally be set appropriately in the policy configuration file
854 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700855 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700856 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700857 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
858 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
859 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800860 // only allow deep buffering for music stream type
861 if (stream != AUDIO_STREAM_MUSIC) {
862 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700863 } else if (/* stream == AUDIO_STREAM_MUSIC && */
864 flags == AUDIO_OUTPUT_FLAG_NONE &&
865 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
866 // use DEEP_BUFFER as default output for music stream type
867 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800868 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700869 if (stream == AUDIO_STREAM_TTS) {
870 flags = AUDIO_OUTPUT_FLAG_TTS;
871 }
Eric Laurente552edb2014-03-10 17:42:56 -0700872
Eric Laurentb732cf52014-09-24 19:08:21 -0700873 sp<IOProfile> profile;
874
875 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700876 // and not explicitly requested
877 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Glenn Kasten05ddca52016-02-11 08:17:12 -0800878 audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700879 audio_channel_count_from_out_mask(channelMask) <= 2) {
880 goto non_direct_output;
881 }
882
Andy Hung2ddee192015-12-18 17:34:44 -0800883 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
884 // This prevents creating an offloaded track and tearing it down immediately after start
885 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700886 // FIXME: We should check the audio session here but we do not have it in this context.
887 // This may prevent offloading in rare situations where effects are left active by apps
888 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700889
Eric Laurente552edb2014-03-10 17:42:56 -0700890 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800891 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700892 profile = getProfileForDirectOutput(device,
893 samplingRate,
894 format,
895 channelMask,
896 (audio_output_flags_t)flags);
897 }
898
Eric Laurent1c333e22014-05-20 10:48:17 -0700899 if (profile != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700900 sp<SwAudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700901
902 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700903 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700904 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
905 outputDesc = desc;
906 // reuse direct output if currently open and configured with same parameters
907 if ((samplingRate == outputDesc->mSamplingRate) &&
Eric Laurente6930022016-02-11 10:20:40 -0800908 audio_formats_match(format, outputDesc->mFormat) &&
Eric Laurente552edb2014-03-10 17:42:56 -0700909 (channelMask == outputDesc->mChannelMask)) {
910 outputDesc->mDirectOpenCount++;
911 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
912 return mOutputs.keyAt(i);
913 }
914 }
915 }
916 // close direct output if currently open and configured with different parameters
917 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700918 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700919 }
Eric Laurent861a6282015-05-18 15:40:16 -0700920
921 // if the selected profile is offloaded and no offload info was specified,
922 // create a default one
923 audio_offload_info_t defaultOffloadInfo = AUDIO_INFO_INITIALIZER;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100924 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) && !offloadInfo) {
Eric Laurent861a6282015-05-18 15:40:16 -0700925 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
926 defaultOffloadInfo.sample_rate = samplingRate;
927 defaultOffloadInfo.channel_mask = channelMask;
928 defaultOffloadInfo.format = format;
929 defaultOffloadInfo.stream_type = stream;
930 defaultOffloadInfo.bit_rate = 0;
931 defaultOffloadInfo.duration_us = -1;
932 defaultOffloadInfo.has_video = true; // conservative
933 defaultOffloadInfo.is_streaming = true; // likely
934 offloadInfo = &defaultOffloadInfo;
935 }
936
Eric Laurentc75307b2015-03-17 15:29:32 -0700937 outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700938 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700939 outputDesc->mLatency = 0;
Eric Laurent861a6282015-05-18 15:40:16 -0700940 outputDesc->mFlags = (audio_output_flags_t)(outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700941 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
942 config.sample_rate = samplingRate;
943 config.channel_mask = channelMask;
944 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700945 if (offloadInfo != NULL) {
946 config.offload_info = *offloadInfo;
947 }
Eric Laurent322b4d22015-04-03 15:57:54 -0700948 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -0700949 &output,
950 &config,
951 &outputDesc->mDevice,
952 String8(""),
953 &outputDesc->mLatency,
954 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700955
956 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700957 if (status != NO_ERROR ||
958 (samplingRate != 0 && samplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -0800959 (format != AUDIO_FORMAT_DEFAULT && !audio_formats_match(format, config.format)) ||
Eric Laurentcf2c0212014-07-25 16:20:43 -0700960 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700961 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
962 "format %d %d, channelMask %04x %04x", output, samplingRate,
963 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
964 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700965 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700966 mpClientInterface->closeOutput(output);
967 }
Eric Laurenta82797f2015-01-30 11:49:43 -0800968 // fall back to mixer output if possible when the direct output could not be open
Glenn Kasten05ddca52016-02-11 08:17:12 -0800969 if (audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -0800970 goto non_direct_output;
971 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700972 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700973 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700974 outputDesc->mSamplingRate = config.sample_rate;
975 outputDesc->mChannelMask = config.channel_mask;
976 outputDesc->mFormat = config.format;
977 outputDesc->mRefCount[stream] = 0;
978 outputDesc->mStopTime[stream] = 0;
979 outputDesc->mDirectOpenCount = 1;
980
Eric Laurente552edb2014-03-10 17:42:56 -0700981 audio_io_handle_t srcOutput = getOutputForEffect();
982 addOutput(output, outputDesc);
983 audio_io_handle_t dstOutput = getOutputForEffect();
984 if (dstOutput == output) {
985 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
986 }
987 mPreviousOutputs = mOutputs;
988 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700989 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700990 return output;
991 }
992
Eric Laurentb732cf52014-09-24 19:08:21 -0700993non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -0700994
995 // A request for HW A/V sync cannot fallback to a mixed output because time
996 // stamps are embedded in audio data
997 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
998 return AUDIO_IO_HANDLE_NONE;
999 }
1000
Eric Laurente552edb2014-03-10 17:42:56 -07001001 // ignoring channel mask due to downmix capability in mixer
1002
1003 // open a non direct output
1004
1005 // for non direct outputs, only PCM is supported
1006 if (audio_is_linear_pcm(format)) {
1007 // get which output is suitable for the specified stream. The actual
1008 // routing change will happen when startOutput() will be called
1009 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1010
Eric Laurent8838a382014-09-08 16:44:28 -07001011 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1012 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1013 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001014 }
1015 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1016 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1017
Paul McLeanaa981192015-03-21 09:55:15 -07001018 ALOGV(" getOutputForDevice() returns output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07001019
1020 return output;
1021}
1022
Eric Laurente0720872014-03-11 09:30:41 -07001023audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001024 audio_output_flags_t flags,
1025 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001026{
1027 // select one output among several that provide a path to a particular device or set of
1028 // devices (the list was previously build by getOutputsForDevice()).
1029 // The priority is as follows:
1030 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001031 // 2: the output with the bit depth the closest to the requested one
1032 // 3: the primary output
1033 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001034
1035 if (outputs.size() == 0) {
1036 return 0;
1037 }
1038 if (outputs.size() == 1) {
1039 return outputs[0];
1040 }
1041
1042 int maxCommonFlags = 0;
Eric Laurente6930022016-02-11 10:20:40 -08001043 audio_io_handle_t outputForFlags = 0;
1044 audio_io_handle_t outputForPrimary = 0;
1045 audio_io_handle_t outputForFormat = 0;
1046 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1047 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001048
1049 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001050 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001051 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001052 // if a valid format is specified, skip output if not compatible
1053 if (format != AUDIO_FORMAT_INVALID) {
1054 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente6930022016-02-11 10:20:40 -08001055 if (!audio_formats_match(format, outputDesc->mFormat)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001056 continue;
1057 }
1058 } else if (!audio_is_linear_pcm(format)) {
1059 continue;
1060 }
Eric Laurente6930022016-02-11 10:20:40 -08001061 if (AudioPort::isBetterFormatMatch(
1062 outputDesc->mFormat, bestFormat, format)) {
1063 outputForFormat = outputs[i];
1064 bestFormat = outputDesc->mFormat;
1065 }
Eric Laurent8838a382014-09-08 16:44:28 -07001066 }
1067
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001068 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001069 if (commonFlags >= maxCommonFlags) {
1070 if (commonFlags == maxCommonFlags) {
1071 if (AudioPort::isBetterFormatMatch(
1072 outputDesc->mFormat, bestFormatForFlags, format)) {
1073 outputForFlags = outputs[i];
1074 bestFormatForFlags = outputDesc->mFormat;
1075 }
1076 } else {
1077 outputForFlags = outputs[i];
1078 maxCommonFlags = commonFlags;
1079 bestFormatForFlags = outputDesc->mFormat;
1080 }
Eric Laurente552edb2014-03-10 17:42:56 -07001081 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1082 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001083 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurente6930022016-02-11 10:20:40 -08001084 outputForPrimary = outputs[i];
Eric Laurente552edb2014-03-10 17:42:56 -07001085 }
1086 }
1087 }
1088
Eric Laurente6930022016-02-11 10:20:40 -08001089 if (outputForFlags != 0) {
1090 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001091 }
Eric Laurente6930022016-02-11 10:20:40 -08001092 if (outputForFormat != 0) {
1093 return outputForFormat;
1094 }
1095 if (outputForPrimary != 0) {
1096 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001097 }
1098
1099 return outputs[0];
1100}
1101
Eric Laurente0720872014-03-11 09:30:41 -07001102status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001103 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001104 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001105{
Paul McLeanaa981192015-03-21 09:55:15 -07001106 ALOGV("startOutput() output %d, stream %d, session %d",
1107 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001108 ssize_t index = mOutputs.indexOfKey(output);
1109 if (index < 0) {
1110 ALOGW("startOutput() unknown output %d", output);
1111 return BAD_VALUE;
1112 }
1113
Eric Laurentc75307b2015-03-17 15:29:32 -07001114 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1115
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001116 // Routing?
1117 mOutputRoutes.incRouteActivity(session);
1118
Eric Laurentc75307b2015-03-17 15:29:32 -07001119 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001120 AudioMix *policyMix = NULL;
1121 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001122 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001123 policyMix = outputDesc->mPolicyMix;
1124 address = policyMix->mDeviceAddress.string();
1125 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1126 newDevice = policyMix->mDeviceType;
1127 } else {
1128 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1129 }
Eric Laurent493404d2015-04-21 15:07:36 -07001130 } else if (mOutputRoutes.hasRouteChanged(session)) {
1131 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001132 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001133 } else {
1134 newDevice = AUDIO_DEVICE_NONE;
1135 }
1136
1137 uint32_t delayMs = 0;
1138
Eric Laurentc40d9692016-04-13 19:14:13 -07001139 status_t status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001140
1141 if (status != NO_ERROR) {
1142 mOutputRoutes.decRouteActivity(session);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001143 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001144 }
1145 // Automatically enable the remote submix input when output is started on a re routing mix
1146 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001147 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1148 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001149 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1150 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001151 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001152 "remote-submix");
1153 }
1154
1155 if (delayMs != 0) {
1156 usleep(delayMs * 1000);
1157 }
1158
1159 return status;
1160}
1161
1162status_t AudioPolicyManager::startSource(sp<AudioOutputDescriptor> outputDesc,
1163 audio_stream_type_t stream,
1164 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001165 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001166 uint32_t *delayMs)
1167{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001168 // cannot start playback of STREAM_TTS if any other output is being used
1169 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001170
1171 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001172 if (stream == AUDIO_STREAM_TTS) {
1173 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001174 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001175 return INVALID_OPERATION;
1176 } else {
1177 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1178 }
1179 } else {
1180 // some playback other than beacon starts
1181 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1182 }
1183
Eric Laurent77305a62016-07-25 16:39:22 -07001184 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001185 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001186 bool force = !outputDesc->isActive() &&
1187 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001188
Eric Laurente552edb2014-03-10 17:42:56 -07001189 // increment usage count for this stream on the requested output:
1190 // NOTE that the usage count is the same for duplicated output and hardware output which is
1191 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1192 outputDesc->changeRefCount(stream, 1);
1193
Eric Laurent493404d2015-04-21 15:07:36 -07001194 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001195 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001196 if (device == AUDIO_DEVICE_NONE) {
1197 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001198 }
Eric Laurente552edb2014-03-10 17:42:56 -07001199 routing_strategy strategy = getStrategy(stream);
1200 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001201 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1202 (beaconMuteLatency > 0);
1203 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001204 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001205 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001206 if (desc != outputDesc) {
Eric Laurent77305a62016-07-25 16:39:22 -07001207 // force a device change if any other output is:
1208 // - managed by the same hw module
1209 // - has a current device selection that differs from selected device.
1210 // - supports currently selected device
1211 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001212 // In this case, the audio HAL must receive the new device selection so that it can
1213 // change the device currently selected by the other active output.
1214 if (outputDesc->sharesHwModuleWith(desc) &&
Eric Laurent77305a62016-07-25 16:39:22 -07001215 desc->device() != device &&
1216 desc->supportedDevices() & device &&
1217 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001218 force = true;
1219 }
1220 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001221 // a notification so that audio focus effect can propagate, or that a mute/unmute
1222 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001223 uint32_t latency = desc->latency();
1224 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1225 waitMs = latency;
1226 }
1227 }
1228 }
Eric Laurentdc462862016-07-19 12:29:53 -07001229 uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force, 0, NULL, address);
Eric Laurente552edb2014-03-10 17:42:56 -07001230
1231 // handle special case for sonification while in call
1232 if (isInCall()) {
1233 handleIncallSonification(stream, true, false);
1234 }
1235
1236 // apply volume rules for current stream and device if necessary
1237 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01001238 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07001239 outputDesc,
1240 device);
Eric Laurente552edb2014-03-10 17:42:56 -07001241
1242 // update the outputs if starting an output with a stream that can affect notification
1243 // routing
1244 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001245
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001246 // force reevaluating accessibility routing when ringtone or alarm starts
1247 if (strategy == STRATEGY_SONIFICATION) {
1248 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1249 }
Eric Laurentdc462862016-07-19 12:29:53 -07001250
1251 if (waitMs > muteWaitMs) {
1252 *delayMs = waitMs - muteWaitMs;
1253 }
Eric Laurente552edb2014-03-10 17:42:56 -07001254 }
Eric Laurentdc462862016-07-19 12:29:53 -07001255
Eric Laurente552edb2014-03-10 17:42:56 -07001256 return NO_ERROR;
1257}
1258
1259
Eric Laurente0720872014-03-11 09:30:41 -07001260status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001261 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001262 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001263{
1264 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1265 ssize_t index = mOutputs.indexOfKey(output);
1266 if (index < 0) {
1267 ALOGW("stopOutput() unknown output %d", output);
1268 return BAD_VALUE;
1269 }
1270
Eric Laurentc75307b2015-03-17 15:29:32 -07001271 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001272
Eric Laurentc75307b2015-03-17 15:29:32 -07001273 if (outputDesc->mRefCount[stream] == 1) {
1274 // Automatically disable the remote submix input when output is stopped on a
1275 // re routing mix of type MIX_TYPE_RECORDERS
1276 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1277 outputDesc->mPolicyMix != NULL &&
1278 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1279 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1280 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001281 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001282 "remote-submix");
1283 }
1284 }
1285
1286 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001287 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001288 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001289 int activityCount = mOutputRoutes.decRouteActivity(session);
1290 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1291
1292 if (forceDeviceUpdate) {
1293 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1294 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001295 }
1296
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001297 return stopSource(outputDesc, stream, forceDeviceUpdate);
Eric Laurentc75307b2015-03-17 15:29:32 -07001298}
1299
1300status_t AudioPolicyManager::stopSource(sp<AudioOutputDescriptor> outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001301 audio_stream_type_t stream,
1302 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001303{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001304 // always handle stream stop, check which stream type is stopping
1305 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1306
Eric Laurente552edb2014-03-10 17:42:56 -07001307 // handle special case for sonification while in call
1308 if (isInCall()) {
1309 handleIncallSonification(stream, false, false);
1310 }
1311
1312 if (outputDesc->mRefCount[stream] > 0) {
1313 // decrement usage count of this stream on the output
1314 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001315
Eric Laurente552edb2014-03-10 17:42:56 -07001316 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001317 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001318 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001319 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001320 // delay the device switch by twice the latency because stopOutput() is executed when
1321 // the track stop() command is received and at that time the audio track buffer can
1322 // still contain data that needs to be drained. The latency only covers the audio HAL
1323 // and kernel buffers. Also the latency does not always include additional delay in the
1324 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001325 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001326
1327 // force restoring the device selection on other active outputs if it differs from the
1328 // one being selected for this output
1329 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001330 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001331 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001332 desc->isActive() &&
1333 outputDesc->sharesHwModuleWith(desc) &&
1334 (newDevice != desc->device())) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001335 setOutputDevice(desc,
1336 getNewOutputDevice(desc, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001337 true,
Eric Laurentc75307b2015-03-17 15:29:32 -07001338 outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001339 }
1340 }
1341 // update the outputs if stopping one with a stream that can affect notification routing
1342 handleNotificationRoutingForStream(stream);
1343 }
1344 return NO_ERROR;
1345 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001346 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001347 return INVALID_OPERATION;
1348 }
1349}
1350
Eric Laurente83b55d2014-11-14 10:06:21 -08001351void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001352 audio_stream_type_t stream __unused,
1353 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001354{
1355 ALOGV("releaseOutput() %d", output);
1356 ssize_t index = mOutputs.indexOfKey(output);
1357 if (index < 0) {
1358 ALOGW("releaseOutput() releasing unknown output %d", output);
1359 return;
1360 }
1361
1362#ifdef AUDIO_POLICY_TEST
1363 int testIndex = testOutputIndex(output);
1364 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001365 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001366 if (outputDesc->isActive()) {
1367 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01001368 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001369 mTestOutputs[testIndex] = 0;
1370 }
1371 return;
1372 }
1373#endif //AUDIO_POLICY_TEST
1374
Paul McLeanaa981192015-03-21 09:55:15 -07001375 // Routing
1376 mOutputRoutes.removeRoute(session);
1377
Eric Laurentc75307b2015-03-17 15:29:32 -07001378 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001379 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001380 if (desc->mDirectOpenCount <= 0) {
1381 ALOGW("releaseOutput() invalid open count %d for output %d",
1382 desc->mDirectOpenCount, output);
1383 return;
1384 }
1385 if (--desc->mDirectOpenCount == 0) {
1386 closeOutput(output);
1387 // If effects where present on the output, audioflinger moved them to the primary
1388 // output by default: move them back to the appropriate output.
1389 audio_io_handle_t dstOutput = getOutputForEffect();
Eric Laurent87ffa392015-05-22 10:32:38 -07001390 if (hasPrimaryOutput() && dstOutput != mPrimaryOutput->mIoHandle) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001391 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX,
1392 mPrimaryOutput->mIoHandle, dstOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07001393 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001394 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001395 }
1396 }
1397}
1398
1399
Eric Laurentcaf7f482014-11-25 17:50:47 -08001400status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1401 audio_io_handle_t *input,
1402 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001403 uid_t uid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001404 uint32_t samplingRate,
1405 audio_format_t format,
1406 audio_channel_mask_t channelMask,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001407 audio_input_flags_t flags,
Paul McLean466dc8e2015-04-17 13:15:36 -06001408 audio_port_handle_t selectedDeviceId,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001409 input_type_t *inputType)
Eric Laurente552edb2014-03-10 17:42:56 -07001410{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001411 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1412 "session %d, flags %#x",
1413 attr->source, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001414
Eric Laurentcaf7f482014-11-25 17:50:47 -08001415 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001416 *inputType = API_INPUT_INVALID;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001417
Eric Laurent275e8e92014-11-30 15:14:47 -08001418 audio_devices_t device;
1419 // handle legacy remote submix case where the address was not always specified
1420 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001421 audio_source_t inputSource = attr->source;
1422 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001423 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001424
Eric Laurentc447ded2015-01-06 08:47:05 -08001425 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1426 inputSource = AUDIO_SOURCE_MIC;
1427 }
1428 halInputSource = inputSource;
1429
Paul McLean466dc8e2015-04-17 13:15:36 -06001430 // Explicit routing?
1431 sp<DeviceDescriptor> deviceDesc;
1432 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1433 if (mAvailableInputDevices[i]->getId() == selectedDeviceId) {
1434 deviceDesc = mAvailableInputDevices[i];
1435 break;
1436 }
1437 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001438 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001439
Eric Laurentc447ded2015-01-06 08:47:05 -08001440 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001441 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07001442 status_t ret = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
François Gaffie036e1e92015-03-19 10:16:24 +01001443 if (ret != NO_ERROR) {
1444 return ret;
1445 }
1446 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001447 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1448 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001449 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001450 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001451 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001452 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001453 return BAD_VALUE;
1454 }
Eric Laurentc722f302014-12-10 11:21:49 -08001455 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001456 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001457 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1458 // there is an external policy, but this input is attached to a mix of recorders,
1459 // meaning it receives audio injected into the framework, so the recorder doesn't
1460 // know about it and is therefore considered "legacy"
1461 *inputType = API_INPUT_LEGACY;
1462 } else {
1463 // recording a mix of players defined by an external policy, we're rerouting for
1464 // an external policy
1465 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1466 }
Eric Laurentc722f302014-12-10 11:21:49 -08001467 } else if (audio_is_remote_submix_device(device)) {
1468 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001469 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001470 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1471 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001472 } else {
1473 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001474 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001475
Eric Laurent599c7582015-12-07 18:05:55 -08001476 }
1477
1478 *input = getInputForDevice(device, address, session, uid, inputSource,
1479 samplingRate, format, channelMask, flags,
1480 policyMix);
1481 if (*input == AUDIO_IO_HANDLE_NONE) {
1482 mInputRoutes.removeRoute(session);
1483 return INVALID_OPERATION;
1484 }
1485 ALOGV("getInputForAttr() returns input type = %d", *inputType);
1486 return NO_ERROR;
1487}
1488
1489
1490audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1491 String8 address,
1492 audio_session_t session,
1493 uid_t uid,
1494 audio_source_t inputSource,
1495 uint32_t samplingRate,
1496 audio_format_t format,
1497 audio_channel_mask_t channelMask,
1498 audio_input_flags_t flags,
1499 AudioMix *policyMix)
1500{
1501 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1502 audio_source_t halInputSource = inputSource;
1503 bool isSoundTrigger = false;
1504
1505 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1506 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1507 if (index >= 0) {
1508 input = mSoundTriggerSessions.valueFor(session);
1509 isSoundTrigger = true;
1510 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1511 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1512 } else {
1513 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001514 }
1515 }
1516
Andy Hungf129b032015-04-07 13:45:50 -07001517 // find a compatible input profile (not necessarily identical in parameters)
1518 sp<IOProfile> profile;
1519 // samplingRate and flags may be updated by getInputProfile
Glenn Kasten05ddca52016-02-11 08:17:12 -08001520 uint32_t profileSamplingRate = (samplingRate == 0) ? SAMPLE_RATE_HZ_DEFAULT : samplingRate;
Andy Hungf129b032015-04-07 13:45:50 -07001521 audio_format_t profileFormat = format;
1522 audio_channel_mask_t profileChannelMask = channelMask;
1523 audio_input_flags_t profileFlags = flags;
1524 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001525 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001526 profileSamplingRate, profileFormat, profileChannelMask,
1527 profileFlags);
1528 if (profile != 0) {
1529 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001530 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1531 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001532 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1533 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1534 } else { // fail
Eric Laurent599c7582015-12-07 18:05:55 -08001535 ALOGW("getInputForDevice() could not find profile for device 0x%X,"
1536 "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
Andy Hungf129b032015-04-07 13:45:50 -07001537 device, samplingRate, format, channelMask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001538 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001539 }
Eric Laurente552edb2014-03-10 17:42:56 -07001540 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001541 // Pick input sampling rate if not specified by client
1542 if (samplingRate == 0) {
1543 samplingRate = profileSamplingRate;
1544 }
Eric Laurente552edb2014-03-10 17:42:56 -07001545
Eric Laurent322b4d22015-04-03 15:57:54 -07001546 if (profile->getModuleHandle() == 0) {
1547 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001548 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001549 }
1550
Eric Laurent599c7582015-12-07 18:05:55 -08001551 sp<AudioSession> audioSession = new AudioSession(session,
1552 inputSource,
1553 format,
1554 samplingRate,
1555 channelMask,
1556 flags,
1557 uid,
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001558 isSoundTrigger,
1559 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001560
Eric Laurentfb66dd92016-01-28 18:32:03 -08001561
Eric Laurent599c7582015-12-07 18:05:55 -08001562 // reuse an open input if possible
1563 for (size_t i = 0; i < mInputs.size(); i++) {
1564 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001565 // reuse input if:
1566 // - it shares the same profile
1567 // AND
1568 // - it is not a reroute submix input
1569 // AND
1570 // - it is: not used for sound trigger
1571 // OR
1572 // used for sound trigger and all clients use the same session ID
1573 //
1574 if ((profile == desc->mProfile) &&
1575 (isSoundTrigger == desc->isSoundTrigger()) &&
1576 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001577
1578 sp<AudioSession> as = desc->getAudioSession(session);
1579 if (as != 0) {
1580 // do not allow unmatching properties on same session
1581 if (as->matches(audioSession)) {
1582 as->changeOpenCount(1);
1583 } else {
1584 ALOGW("getInputForDevice() record with different attributes"
1585 " exists for session %d", session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001586 break;
Eric Laurent599c7582015-12-07 18:05:55 -08001587 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001588 } else if (isSoundTrigger) {
1589 break;
1590 }
1591 // force close input if current source is now the highest priority request on this input
1592 // and current input properties are not exactly as requested.
1593 if ((desc->mSamplingRate != samplingRate ||
1594 desc->mChannelMask != channelMask ||
Eric Laurente6930022016-02-11 10:20:40 -08001595 !audio_formats_match(desc->mFormat, format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001596 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
1597 source_priority(inputSource))) {
1598 ALOGV("%s: ", __FUNCTION__);
1599 AudioSessionCollection sessions = desc->getAudioSessions(false /*activeOnly*/);
1600 for (size_t j = 0; j < sessions.size(); j++) {
1601 audio_session_t currentSession = sessions.keyAt(j);
1602 stopInput(desc->mIoHandle, currentSession);
1603 releaseInput(desc->mIoHandle, currentSession);
1604 }
1605 break;
Eric Laurent599c7582015-12-07 18:05:55 -08001606 } else {
1607 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001608 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1609 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001610 }
Eric Laurent599c7582015-12-07 18:05:55 -08001611 }
1612 }
Eric Laurent599c7582015-12-07 18:05:55 -08001613
Eric Laurentcf2c0212014-07-25 16:20:43 -07001614 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Andy Hungf129b032015-04-07 13:45:50 -07001615 config.sample_rate = profileSamplingRate;
1616 config.channel_mask = profileChannelMask;
1617 config.format = profileFormat;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001618
Eric Laurent322b4d22015-04-03 15:57:54 -07001619 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurent599c7582015-12-07 18:05:55 -08001620 &input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001621 &config,
1622 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001623 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001624 halInputSource,
Andy Hungf129b032015-04-07 13:45:50 -07001625 profileFlags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001626
1627 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001628 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Andy Hungf129b032015-04-07 13:45:50 -07001629 (profileSamplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001630 !audio_formats_match(profileFormat, config.format) ||
Andy Hungf129b032015-04-07 13:45:50 -07001631 (profileChannelMask != config.channel_mask)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001632 ALOGW("getInputForAttr() failed opening input: samplingRate %d"
1633 ", format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001634 samplingRate, format, channelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001635 if (input != AUDIO_IO_HANDLE_NONE) {
1636 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001637 }
Eric Laurent599c7582015-12-07 18:05:55 -08001638 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001639 }
1640
Eric Laurent1f2f2232014-06-02 12:01:23 -07001641 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Andy Hungf129b032015-04-07 13:45:50 -07001642 inputDesc->mSamplingRate = profileSamplingRate;
1643 inputDesc->mFormat = profileFormat;
1644 inputDesc->mChannelMask = profileChannelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001645 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001646 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001647 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001648
Eric Laurent599c7582015-12-07 18:05:55 -08001649 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001650 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001651
Eric Laurent599c7582015-12-07 18:05:55 -08001652 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001653}
1654
Eric Laurentfb66dd92016-01-28 18:32:03 -08001655bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1656 const sp<AudioSession>& audioSession)
1657{
1658 // Do not allow capture if an active voice call is using a software patch and
1659 // the call TX source device is on the same HW module.
1660 // FIXME: would be better to refine to only inputs whose profile connects to the
1661 // call TX device but this information is not in the audio patch
1662 if (mCallTxPatch != 0 &&
1663 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1664 return false;
1665 }
1666
1667 // starting concurrent capture is enabled if:
1668 // 1) capturing for re-routing
1669 // 2) capturing for HOTWORD source
1670 // 3) capturing for FM TUNER source
1671 // 3) All other active captures are either for re-routing or HOTWORD
1672
1673 if (is_virtual_input_device(inputDesc->mDevice) ||
1674 audioSession->inputSource() == AUDIO_SOURCE_HOTWORD ||
1675 audioSession->inputSource() == AUDIO_SOURCE_FM_TUNER) {
1676 return true;
1677 }
1678
1679 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1680 for (size_t i = 0; i < activeInputs.size(); i++) {
1681 sp<AudioInputDescriptor> activeInput = activeInputs[i];
1682 if ((activeInput->inputSource() != AUDIO_SOURCE_HOTWORD) &&
1683 (activeInput->inputSource() != AUDIO_SOURCE_FM_TUNER) &&
1684 !is_virtual_input_device(activeInput->mDevice)) {
1685 return false;
1686 }
1687 }
1688
1689 return true;
1690}
1691
1692
Eric Laurent4dc68062014-07-28 17:26:49 -07001693status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001694 audio_session_t session,
1695 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001696{
1697 ALOGV("startInput() input %d", input);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001698 *concurrency = API_INPUT_CONCURRENCY_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001699 ssize_t index = mInputs.indexOfKey(input);
1700 if (index < 0) {
1701 ALOGW("startInput() unknown input %d", input);
1702 return BAD_VALUE;
1703 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001704 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001705
Eric Laurent599c7582015-12-07 18:05:55 -08001706 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1707 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001708 ALOGW("startInput() unknown session %d on input %d", session, input);
1709 return BAD_VALUE;
1710 }
1711
Eric Laurentfb66dd92016-01-28 18:32:03 -08001712 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1713 ALOGW("startInput(%d) failed: other input already started", input);
1714 return INVALID_OPERATION;
1715 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001716
Eric Laurentfb66dd92016-01-28 18:32:03 -08001717 if (isInCall()) {
1718 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1719 }
1720 if (mInputs.activeInputsCount() != 0) {
1721 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001722 }
1723
Eric Laurent313d1e72016-01-29 09:56:57 -08001724 // increment activity count before calling getNewInputDevice() below as only active sessions
1725 // are considered for device selection
1726 audioSession->changeActiveCount(1);
1727
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001728 // Routing?
1729 mInputRoutes.incRouteActivity(session);
1730
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001731 if (audioSession->activeCount() == 1 || mInputRoutes.hasRouteChanged(session)) {
Jean-Michel Trivi2b0c1fc2015-04-15 17:29:28 -07001732
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001733 setInputDevice(input, getNewInputDevice(inputDesc), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001734
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001735 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
1736 // if input maps to a dynamic policy with an activity listener, notify of state change
1737 if ((inputDesc->mPolicyMix != NULL)
1738 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1739 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
1740 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08001741 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001742
1743 if (mInputs.activeInputsCount() == 0) {
1744 SoundTrigger::setCaptureState(true);
1745 }
1746
1747 // automatically enable the remote submix output when input is started if not
1748 // used by a policy mix of type MIX_TYPE_RECORDERS
1749 // For remote submix (a virtual device), we open only one input per capture request.
1750 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1751 String8 address = String8("");
1752 if (inputDesc->mPolicyMix == NULL) {
1753 address = String8("0");
1754 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1755 address = inputDesc->mPolicyMix->mDeviceAddress;
1756 }
1757 if (address != "") {
1758 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1759 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1760 address, "remote-submix");
1761 }
Eric Laurentc722f302014-12-10 11:21:49 -08001762 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001763 }
Eric Laurente552edb2014-03-10 17:42:56 -07001764 }
1765
Eric Laurent599c7582015-12-07 18:05:55 -08001766 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07001767
Eric Laurente552edb2014-03-10 17:42:56 -07001768 return NO_ERROR;
1769}
1770
Eric Laurent4dc68062014-07-28 17:26:49 -07001771status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1772 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001773{
1774 ALOGV("stopInput() input %d", input);
1775 ssize_t index = mInputs.indexOfKey(input);
1776 if (index < 0) {
1777 ALOGW("stopInput() unknown input %d", input);
1778 return BAD_VALUE;
1779 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001780 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001781
Eric Laurent599c7582015-12-07 18:05:55 -08001782 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001783 if (index < 0) {
1784 ALOGW("stopInput() unknown session %d on input %d", session, input);
1785 return BAD_VALUE;
1786 }
1787
Eric Laurent599c7582015-12-07 18:05:55 -08001788 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001789 ALOGW("stopInput() input %d already stopped", input);
1790 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001791 }
1792
Eric Laurent599c7582015-12-07 18:05:55 -08001793 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06001794
1795 // Routing?
1796 mInputRoutes.decRouteActivity(session);
1797
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001798 if (audioSession->activeCount() == 0) {
Eric Laurent84332aa2016-01-28 22:19:18 +00001799
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001800 if (inputDesc->isActive()) {
1801 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
1802 } else {
1803 // if input maps to a dynamic policy with an activity listener, notify of state change
1804 if ((inputDesc->mPolicyMix != NULL)
1805 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1806 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
1807 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00001808 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001809
1810 // automatically disable the remote submix output when input is stopped if not
1811 // used by a policy mix of type MIX_TYPE_RECORDERS
1812 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1813 String8 address = String8("");
1814 if (inputDesc->mPolicyMix == NULL) {
1815 address = String8("0");
1816 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1817 address = inputDesc->mPolicyMix->mDeviceAddress;
1818 }
1819 if (address != "") {
1820 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1821 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1822 address, "remote-submix");
1823 }
Eric Laurent84332aa2016-01-28 22:19:18 +00001824 }
Eric Laurent84332aa2016-01-28 22:19:18 +00001825
Eric Laurentfb66dd92016-01-28 18:32:03 -08001826 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00001827
Eric Laurentfb66dd92016-01-28 18:32:03 -08001828 if (mInputs.activeInputsCount() == 0) {
1829 SoundTrigger::setCaptureState(false);
1830 }
1831 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00001832 }
Eric Laurente552edb2014-03-10 17:42:56 -07001833 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001834 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001835}
1836
Eric Laurent4dc68062014-07-28 17:26:49 -07001837void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1838 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001839{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001840
Eric Laurente552edb2014-03-10 17:42:56 -07001841 ALOGV("releaseInput() %d", input);
1842 ssize_t index = mInputs.indexOfKey(input);
1843 if (index < 0) {
1844 ALOGW("releaseInput() releasing unknown input %d", input);
1845 return;
1846 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001847
1848 // Routing
1849 mInputRoutes.removeRoute(session);
1850
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001851 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1852 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001853
Eric Laurent599c7582015-12-07 18:05:55 -08001854 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001855 if (index < 0) {
1856 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1857 return;
1858 }
Eric Laurent599c7582015-12-07 18:05:55 -08001859
1860 if (audioSession->openCount() == 0) {
1861 ALOGW("releaseInput() invalid open count %d on session %d",
1862 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001863 return;
1864 }
Eric Laurent599c7582015-12-07 18:05:55 -08001865
1866 if (audioSession->changeOpenCount(-1) == 0) {
1867 inputDesc->removeAudioSession(session);
1868 }
1869
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08001870 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001871 ALOGV("releaseInput() exit > 0");
1872 return;
1873 }
1874
Eric Laurent05b90f82014-08-27 15:32:29 -07001875 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001876 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001877 ALOGV("releaseInput() exit");
1878}
1879
Eric Laurentd4692962014-05-05 18:13:44 -07001880void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001881 bool patchRemoved = false;
1882
Eric Laurentd4692962014-05-05 18:13:44 -07001883 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001884 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08001885 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07001886 if (patch_index >= 0) {
1887 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07001888 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07001889 mAudioPatches.removeItemsAt(patch_index);
1890 patchRemoved = true;
1891 }
Eric Laurentd4692962014-05-05 18:13:44 -07001892 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1893 }
1894 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08001895 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07001896 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001897
1898 if (patchRemoved) {
1899 mpClientInterface->onAudioPatchListUpdate();
1900 }
Eric Laurentd4692962014-05-05 18:13:44 -07001901}
1902
Eric Laurente0720872014-03-11 09:30:41 -07001903void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001904 int indexMin,
1905 int indexMax)
1906{
1907 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01001908 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08001909
1910 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08001911 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1912 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001913 continue;
1914 }
1915 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001916 }
Eric Laurente552edb2014-03-10 17:42:56 -07001917}
1918
Eric Laurente0720872014-03-11 09:30:41 -07001919status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01001920 int index,
1921 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07001922{
1923
François Gaffied1ab2bd2015-12-02 18:20:06 +01001924 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
1925 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07001926 return BAD_VALUE;
1927 }
1928 if (!audio_is_output_device(device)) {
1929 return BAD_VALUE;
1930 }
1931
1932 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01001933 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07001934
Eric Laurent1fd372e2016-04-06 14:23:53 -07001935 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07001936 stream, device, index);
1937
Eric Laurent28d09f02016-03-08 10:43:05 -08001938 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08001939 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1940 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001941 continue;
1942 }
1943 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
1944 }
Eric Laurente552edb2014-03-10 17:42:56 -07001945
Eric Laurent1fd372e2016-04-06 14:23:53 -07001946 // update volume on all outputs and streams matching the following:
1947 // - The requested stream (or a stream matching for volume control) is active on the output
1948 // - The device (or devices) selected by the strategy corresponding to this stream includes
1949 // the requested device
1950 // - For non default requested device, currently selected device on the output is either the
1951 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07001952 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
1953 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07001954 status_t status = NO_ERROR;
1955 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001956 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1957 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08001958 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1959 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001960 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07001961 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07001962 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
1963 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07001964 continue;
1965 }
Eric Laurent794fde22016-03-11 09:50:45 -08001966 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08001967 audio_devices_t curStreamDevice = getDeviceForStrategy(curStrategy, true /*fromCache*/);
Eric Laurent1fd372e2016-04-06 14:23:53 -07001968 if ((curStreamDevice & device) == 0) {
1969 continue;
1970 }
1971 bool applyDefault = false;
Eric Laurent5a2b6292016-04-14 18:05:57 -07001972 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07001973 curStreamDevice |= device;
1974 } else if (!mVolumeCurves->hasVolumeIndexForDevice(
1975 stream, Volume::getDeviceForVolume(curStreamDevice))) {
1976 applyDefault = true;
1977 }
Eric Laurent28d09f02016-03-08 10:43:05 -08001978
Eric Laurent1fd372e2016-04-06 14:23:53 -07001979 if (applyDefault || ((curDevice & curStreamDevice) != 0)) {
Eric Laurentdc462862016-07-19 12:29:53 -07001980 //FIXME: workaround for truncated touch sounds
1981 // delayed volume change for system stream to be removed when the problem is
1982 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08001983 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07001984 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
1985 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08001986 if (volStatus != NO_ERROR) {
1987 status = volStatus;
1988 }
1989 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001990 }
Eric Laurente552edb2014-03-10 17:42:56 -07001991 }
1992 return status;
1993}
1994
Eric Laurente0720872014-03-11 09:30:41 -07001995status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001996 int *index,
1997 audio_devices_t device)
1998{
1999 if (index == NULL) {
2000 return BAD_VALUE;
2001 }
2002 if (!audio_is_output_device(device)) {
2003 return BAD_VALUE;
2004 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002005 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002006 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002007 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002008 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2009 }
François Gaffiedfd74092015-03-19 12:10:59 +01002010 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002011
François Gaffied1ab2bd2015-12-02 18:20:06 +01002012 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002013 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2014 return NO_ERROR;
2015}
2016
Eric Laurente0720872014-03-11 09:30:41 -07002017audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07002018 const SortedVector<audio_io_handle_t>& outputs)
2019{
2020 // select one output among several suitable for global effects.
2021 // The priority is as follows:
2022 // 1: An offloaded output. If the effect ends up not being offloadable,
2023 // AudioFlinger will invalidate the track and the offloaded output
2024 // will be closed causing the effect to be moved to a PCM output.
2025 // 2: A deep buffer output
2026 // 3: the first output in the list
2027
2028 if (outputs.size() == 0) {
2029 return 0;
2030 }
2031
2032 audio_io_handle_t outputOffloaded = 0;
2033 audio_io_handle_t outputDeepBuffer = 0;
2034
2035 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002036 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07002037 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07002038 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2039 outputOffloaded = outputs[i];
2040 }
2041 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
2042 outputDeepBuffer = outputs[i];
2043 }
2044 }
2045
2046 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
2047 outputOffloaded, outputDeepBuffer);
2048 if (outputOffloaded != 0) {
2049 return outputOffloaded;
2050 }
2051 if (outputDeepBuffer != 0) {
2052 return outputDeepBuffer;
2053 }
2054
2055 return outputs[0];
2056}
2057
Eric Laurente0720872014-03-11 09:30:41 -07002058audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07002059{
2060 // apply simple rule where global effects are attached to the same output as MUSIC streams
2061
Eric Laurent3b73df72014-03-11 09:06:29 -07002062 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002063 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2064 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
2065
2066 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
2067 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
2068 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
2069
2070 return output;
2071}
2072
Eric Laurente0720872014-03-11 09:30:41 -07002073status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002074 audio_io_handle_t io,
2075 uint32_t strategy,
2076 int session,
2077 int id)
2078{
2079 ssize_t index = mOutputs.indexOfKey(io);
2080 if (index < 0) {
2081 index = mInputs.indexOfKey(io);
2082 if (index < 0) {
2083 ALOGW("registerEffect() unknown io %d", io);
2084 return INVALID_OPERATION;
2085 }
2086 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002087 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002088}
2089
Eric Laurentc75307b2015-03-17 15:29:32 -07002090bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2091{
Eric Laurent28d09f02016-03-08 10:43:05 -08002092 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002093 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2094 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002095 continue;
2096 }
2097 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2098 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002099 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002100}
2101
2102bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2103{
2104 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2105}
2106
Eric Laurente0720872014-03-11 09:30:41 -07002107bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002108{
2109 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002110 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002111 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002112 return true;
2113 }
2114 }
2115 return false;
2116}
2117
Eric Laurent275e8e92014-11-30 15:14:47 -08002118// Register a list of custom mixes with their attributes and format.
2119// When a mix is registered, corresponding input and output profiles are
2120// added to the remote submix hw module. The profile contains only the
2121// parameters (sampling rate, format...) specified by the mix.
2122// The corresponding input remote submix device is also connected.
2123//
2124// When a remote submix device is connected, the address is checked to select the
2125// appropriate profile and the corresponding input or output stream is opened.
2126//
2127// When capture starts, getInputForAttr() will:
2128// - 1 look for a mix matching the address passed in attribtutes tags if any
2129// - 2 if none found, getDeviceForInputSource() will:
2130// - 2.1 look for a mix matching the attributes source
2131// - 2.2 if none found, default to device selection by policy rules
2132// At this time, the corresponding output remote submix device is also connected
2133// and active playback use cases can be transferred to this mix if needed when reconnecting
2134// after AudioTracks are invalidated
2135//
2136// When playback starts, getOutputForAttr() will:
2137// - 1 look for a mix matching the address passed in attribtutes tags if any
2138// - 2 if none found, look for a mix matching the attributes usage
2139// - 3 if none found, default to device and output selection by policy rules.
2140
2141status_t AudioPolicyManager::registerPolicyMixes(Vector<AudioMix> mixes)
2142{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002143 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2144 status_t res = NO_ERROR;
2145
2146 sp<HwModule> rSubmixModule;
2147 // examine each mix's route type
2148 for (size_t i = 0; i < mixes.size(); i++) {
2149 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2150 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2151 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002152 break;
2153 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002154 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2155 // Loop back through "remote submix"
2156 if (rSubmixModule == 0) {
2157 for (size_t j = 0; i < mHwModules.size(); j++) {
2158 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2159 && mHwModules[j]->mHandle != 0) {
2160 rSubmixModule = mHwModules[j];
2161 break;
2162 }
2163 }
2164 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002165
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002166 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002167
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002168 if (rSubmixModule == 0) {
2169 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration", i);
2170 res = INVALID_OPERATION;
2171 break;
2172 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002173
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002174 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002175
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002176 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002177 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002178 res = INVALID_OPERATION;
2179 break;
2180 }
2181 audio_config_t outputConfig = mixes[i].mFormat;
2182 audio_config_t inputConfig = mixes[i].mFormat;
2183 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2184 // stereo and let audio flinger do the channel conversion if needed.
2185 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2186 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2187 rSubmixModule->addOutputProfile(address, &outputConfig,
2188 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2189 rSubmixModule->addInputProfile(address, &inputConfig,
2190 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002191
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002192 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2193 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2194 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2195 address.string(), "remote-submix");
2196 } else {
2197 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2198 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2199 address.string(), "remote-submix");
2200 }
2201 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002202 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002203 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002204 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2205 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002206
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002207 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002208 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2209 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2210 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2211 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2212 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2213 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002214 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2215 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002216 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2217 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002218 } else {
2219 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002220 }
2221 break;
2222 }
2223 }
2224
2225 if (res != NO_ERROR) {
2226 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002227 i, device, address.string());
2228 res = INVALID_OPERATION;
2229 break;
2230 } else if (!foundOutput) {
2231 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2232 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002233 res = INVALID_OPERATION;
2234 break;
2235 }
Eric Laurentc722f302014-12-10 11:21:49 -08002236 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002237 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002238 if (res != NO_ERROR) {
2239 unregisterPolicyMixes(mixes);
2240 }
2241 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002242}
2243
2244status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2245{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002246 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002247 status_t res = NO_ERROR;
2248 sp<HwModule> rSubmixModule;
2249 // examine each mix's route type
Eric Laurent275e8e92014-11-30 15:14:47 -08002250 for (size_t i = 0; i < mixes.size(); i++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002251 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002252
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002253 if (rSubmixModule == 0) {
2254 for (size_t j = 0; i < mHwModules.size(); j++) {
2255 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2256 && mHwModules[j]->mHandle != 0) {
2257 rSubmixModule = mHwModules[j];
2258 break;
2259 }
2260 }
2261 }
2262 if (rSubmixModule == 0) {
2263 res = INVALID_OPERATION;
2264 continue;
2265 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002266
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002267 String8 address = mixes[i].mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002268
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002269 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2270 res = INVALID_OPERATION;
2271 continue;
2272 }
2273
2274 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2275 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2276 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2277 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2278 address.string(), "remote-submix");
2279 }
2280 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2281 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2282 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2283 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2284 address.string(), "remote-submix");
2285 }
2286 rSubmixModule->removeOutputProfile(address);
2287 rSubmixModule->removeInputProfile(address);
2288
2289 } if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2290 if (mPolicyMixes.unregisterMix(mixes[i].mDeviceAddress) != NO_ERROR) {
2291 res = INVALID_OPERATION;
2292 continue;
2293 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002294 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002295 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002296 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002297}
2298
Eric Laurente552edb2014-03-10 17:42:56 -07002299
Eric Laurente0720872014-03-11 09:30:41 -07002300status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002301{
2302 const size_t SIZE = 256;
2303 char buffer[SIZE];
2304 String8 result;
2305
2306 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2307 result.append(buffer);
2308
Eric Laurent87ffa392015-05-22 10:32:38 -07002309 snprintf(buffer, SIZE, " Primary Output: %d\n",
2310 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002311 result.append(buffer);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002312 std::string stateLiteral;
2313 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
2314 snprintf(buffer, SIZE, " Phone state: %s\n", stateLiteral.c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002315 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002316 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002317 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002318 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002319 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002320 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002321 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002322 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002323 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002324 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002325 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002326 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002327 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002328 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002329 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002330 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2331 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2332 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002333 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2334 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002335 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2336 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002337
François Gaffie2110e042015-03-24 08:41:51 +01002338 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002339
François Gaffie112b0af2015-11-19 16:13:25 +01002340 mAvailableOutputDevices.dump(fd, String8("Available output"));
2341 mAvailableInputDevices.dump(fd, String8("Available input"));
François Gaffie53615e22015-03-19 09:24:12 +01002342 mHwModules.dump(fd);
2343 mOutputs.dump(fd);
2344 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002345 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002346 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002347 mAudioPatches.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002348
2349 return NO_ERROR;
2350}
2351
2352// This function checks for the parameters which can be offloaded.
2353// This can be enhanced depending on the capability of the DSP and policy
2354// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002355bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002356{
2357 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002358 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002359 offloadInfo.sample_rate, offloadInfo.channel_mask,
2360 offloadInfo.format,
2361 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2362 offloadInfo.has_video);
2363
Andy Hung2ddee192015-12-18 17:34:44 -08002364 if (mMasterMono) {
2365 return false; // no offloading if mono is set.
2366 }
2367
Eric Laurente552edb2014-03-10 17:42:56 -07002368 // Check if offload has been disabled
2369 char propValue[PROPERTY_VALUE_MAX];
2370 if (property_get("audio.offload.disable", propValue, "0")) {
2371 if (atoi(propValue) != 0) {
2372 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2373 return false;
2374 }
2375 }
2376
2377 // Check if stream type is music, then only allow offload as of now.
2378 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2379 {
2380 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2381 return false;
2382 }
2383
2384 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002385 const bool allowOffloadWithVideo =
2386 property_get_bool("audio.offload.video", false /* default_value */);
2387 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002388 ALOGV("isOffloadSupported: has_video == true, returning false");
2389 return false;
2390 }
2391
2392 //If duration is less than minimum value defined in property, return false
2393 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2394 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2395 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2396 return false;
2397 }
2398 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2399 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2400 return false;
2401 }
2402
2403 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2404 // creating an offloaded track and tearing it down immediately after start when audioflinger
2405 // detects there is an active non offloadable effect.
2406 // FIXME: We should check the audio session here but we do not have it in this context.
2407 // This may prevent offloading in rare situations where effects are left active by apps
2408 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002409 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002410 return false;
2411 }
2412
2413 // See if there is a profile to support this.
2414 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002415 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002416 offloadInfo.sample_rate,
2417 offloadInfo.format,
2418 offloadInfo.channel_mask,
2419 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002420 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2421 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002422}
2423
Eric Laurent6a94d692014-05-20 11:18:06 -07002424status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2425 audio_port_type_t type,
2426 unsigned int *num_ports,
2427 struct audio_port *ports,
2428 unsigned int *generation)
2429{
2430 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2431 generation == NULL) {
2432 return BAD_VALUE;
2433 }
2434 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2435 if (ports == NULL) {
2436 *num_ports = 0;
2437 }
2438
2439 size_t portsWritten = 0;
2440 size_t portsMax = *num_ports;
2441 *num_ports = 0;
2442 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002443 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2444 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002445 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002446 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
2447 if (mAvailableOutputDevices[i]->type() == AUDIO_DEVICE_OUT_STUB) {
2448 continue;
2449 }
2450 if (portsWritten < portsMax) {
2451 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2452 }
2453 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002454 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002455 }
2456 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002457 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2458 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_STUB) {
2459 continue;
2460 }
2461 if (portsWritten < portsMax) {
2462 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2463 }
2464 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002465 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002466 }
2467 }
2468 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2469 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2470 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2471 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2472 }
2473 *num_ports += mInputs.size();
2474 }
2475 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002476 size_t numOutputs = 0;
2477 for (size_t i = 0; i < mOutputs.size(); i++) {
2478 if (!mOutputs[i]->isDuplicated()) {
2479 numOutputs++;
2480 if (portsWritten < portsMax) {
2481 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2482 }
2483 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002484 }
Eric Laurent84c70242014-06-23 08:46:27 -07002485 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002486 }
2487 }
2488 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002489 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002490 return NO_ERROR;
2491}
2492
2493status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2494{
2495 return NO_ERROR;
2496}
2497
Eric Laurent6a94d692014-05-20 11:18:06 -07002498status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2499 audio_patch_handle_t *handle,
2500 uid_t uid)
2501{
2502 ALOGV("createAudioPatch()");
2503
2504 if (handle == NULL || patch == NULL) {
2505 return BAD_VALUE;
2506 }
2507 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2508
Eric Laurent874c42872014-08-08 15:13:39 -07002509 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2510 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2511 return BAD_VALUE;
2512 }
2513 // only one source per audio patch supported for now
2514 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002515 return INVALID_OPERATION;
2516 }
Eric Laurent874c42872014-08-08 15:13:39 -07002517
2518 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002519 return INVALID_OPERATION;
2520 }
Eric Laurent874c42872014-08-08 15:13:39 -07002521 for (size_t i = 0; i < patch->num_sinks; i++) {
2522 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2523 return INVALID_OPERATION;
2524 }
2525 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002526
2527 sp<AudioPatch> patchDesc;
2528 ssize_t index = mAudioPatches.indexOfKey(*handle);
2529
Eric Laurent6a94d692014-05-20 11:18:06 -07002530 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2531 patch->sources[0].role,
2532 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002533#if LOG_NDEBUG == 0
2534 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002535 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002536 patch->sinks[i].role,
2537 patch->sinks[i].type);
2538 }
2539#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002540
2541 if (index >= 0) {
2542 patchDesc = mAudioPatches.valueAt(index);
2543 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2544 mUidCached, patchDesc->mUid, uid);
2545 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2546 return INVALID_OPERATION;
2547 }
2548 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002549 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002550 }
2551
2552 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002553 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002554 if (outputDesc == NULL) {
2555 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2556 return BAD_VALUE;
2557 }
Eric Laurent84c70242014-06-23 08:46:27 -07002558 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2559 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002560 if (patchDesc != 0) {
2561 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2562 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2563 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2564 return BAD_VALUE;
2565 }
2566 }
Eric Laurent874c42872014-08-08 15:13:39 -07002567 DeviceVector devices;
2568 for (size_t i = 0; i < patch->num_sinks; i++) {
2569 // Only support mix to devices connection
2570 // TODO add support for mix to mix connection
2571 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2572 ALOGV("createAudioPatch() source mix but sink is not a device");
2573 return INVALID_OPERATION;
2574 }
2575 sp<DeviceDescriptor> devDesc =
2576 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2577 if (devDesc == 0) {
2578 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2579 return BAD_VALUE;
2580 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002581
François Gaffie53615e22015-03-19 09:24:12 +01002582 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002583 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002584 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002585 NULL, // updatedSamplingRate
2586 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002587 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002588 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002589 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002590 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002591 ALOGV("createAudioPatch() profile not supported for device %08x",
2592 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002593 return INVALID_OPERATION;
2594 }
2595 devices.add(devDesc);
2596 }
2597 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002598 return INVALID_OPERATION;
2599 }
Eric Laurent874c42872014-08-08 15:13:39 -07002600
Eric Laurent6a94d692014-05-20 11:18:06 -07002601 // TODO: reconfigure output format and channels here
2602 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002603 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002604 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002605 index = mAudioPatches.indexOfKey(*handle);
2606 if (index >= 0) {
2607 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2608 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2609 }
2610 patchDesc = mAudioPatches.valueAt(index);
2611 patchDesc->mUid = uid;
2612 ALOGV("createAudioPatch() success");
2613 } else {
2614 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2615 return INVALID_OPERATION;
2616 }
2617 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2618 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2619 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002620 // only one sink supported when connecting an input device to a mix
2621 if (patch->num_sinks > 1) {
2622 return INVALID_OPERATION;
2623 }
François Gaffie53615e22015-03-19 09:24:12 +01002624 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002625 if (inputDesc == NULL) {
2626 return BAD_VALUE;
2627 }
2628 if (patchDesc != 0) {
2629 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2630 return BAD_VALUE;
2631 }
2632 }
2633 sp<DeviceDescriptor> devDesc =
2634 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2635 if (devDesc == 0) {
2636 return BAD_VALUE;
2637 }
2638
François Gaffie53615e22015-03-19 09:24:12 +01002639 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002640 devDesc->mAddress,
2641 patch->sinks[0].sample_rate,
2642 NULL, /*updatedSampleRate*/
2643 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002644 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002645 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002646 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002647 // FIXME for the parameter type,
2648 // and the NONE
2649 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002650 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002651 return INVALID_OPERATION;
2652 }
2653 // TODO: reconfigure output format and channels here
2654 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002655 devDesc->type(), inputDesc->mIoHandle);
2656 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002657 index = mAudioPatches.indexOfKey(*handle);
2658 if (index >= 0) {
2659 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2660 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2661 }
2662 patchDesc = mAudioPatches.valueAt(index);
2663 patchDesc->mUid = uid;
2664 ALOGV("createAudioPatch() success");
2665 } else {
2666 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2667 return INVALID_OPERATION;
2668 }
2669 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2670 // device to device connection
2671 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002672 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002673 return BAD_VALUE;
2674 }
2675 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002676 sp<DeviceDescriptor> srcDeviceDesc =
2677 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002678 if (srcDeviceDesc == 0) {
2679 return BAD_VALUE;
2680 }
Eric Laurent874c42872014-08-08 15:13:39 -07002681
Eric Laurent6a94d692014-05-20 11:18:06 -07002682 //update source and sink with our own data as the data passed in the patch may
2683 // be incomplete.
2684 struct audio_patch newPatch = *patch;
2685 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002686
Eric Laurent874c42872014-08-08 15:13:39 -07002687 for (size_t i = 0; i < patch->num_sinks; i++) {
2688 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2689 ALOGV("createAudioPatch() source device but one sink is not a device");
2690 return INVALID_OPERATION;
2691 }
2692
2693 sp<DeviceDescriptor> sinkDeviceDesc =
2694 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2695 if (sinkDeviceDesc == 0) {
2696 return BAD_VALUE;
2697 }
2698 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2699
Eric Laurent3bcf8592015-04-03 12:13:24 -07002700 // create a software bridge in PatchPanel if:
2701 // - source and sink devices are on differnt HW modules OR
2702 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08002703 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002704 (srcDeviceDesc->mModule->getHalVersion() < AUDIO_DEVICE_API_VERSION_3_0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002705 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002706 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002707 return INVALID_OPERATION;
2708 }
Eric Laurent874c42872014-08-08 15:13:39 -07002709 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002710 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002711 // if the sink device is reachable via an opened output stream, request to go via
2712 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002713 audio_io_handle_t output = selectOutput(outputs,
2714 AUDIO_OUTPUT_FLAG_NONE,
2715 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002716 if (output != AUDIO_IO_HANDLE_NONE) {
2717 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2718 if (outputDesc->isDuplicated()) {
2719 return INVALID_OPERATION;
2720 }
2721 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07002722 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07002723 newPatch.num_sources = 2;
2724 }
Eric Laurent83b88082014-06-20 18:31:16 -07002725 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002726 }
2727 // TODO: check from routing capabilities in config file and other conflicting patches
2728
2729 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2730 if (index >= 0) {
2731 afPatchHandle = patchDesc->mAfPatchHandle;
2732 }
2733
2734 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2735 &afPatchHandle,
2736 0);
2737 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2738 status, afPatchHandle);
2739 if (status == NO_ERROR) {
2740 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01002741 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002742 addAudioPatch(patchDesc->mHandle, patchDesc);
2743 } else {
2744 patchDesc->mPatch = newPatch;
2745 }
2746 patchDesc->mAfPatchHandle = afPatchHandle;
2747 *handle = patchDesc->mHandle;
2748 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002749 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002750 } else {
2751 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2752 status);
2753 return INVALID_OPERATION;
2754 }
2755 } else {
2756 return BAD_VALUE;
2757 }
2758 } else {
2759 return BAD_VALUE;
2760 }
2761 return NO_ERROR;
2762}
2763
2764status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2765 uid_t uid)
2766{
2767 ALOGV("releaseAudioPatch() patch %d", handle);
2768
2769 ssize_t index = mAudioPatches.indexOfKey(handle);
2770
2771 if (index < 0) {
2772 return BAD_VALUE;
2773 }
2774 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2775 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2776 mUidCached, patchDesc->mUid, uid);
2777 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2778 return INVALID_OPERATION;
2779 }
2780
2781 struct audio_patch *patch = &patchDesc->mPatch;
2782 patchDesc->mUid = mUidCached;
2783 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002784 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002785 if (outputDesc == NULL) {
2786 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2787 return BAD_VALUE;
2788 }
2789
Eric Laurentc75307b2015-03-17 15:29:32 -07002790 setOutputDevice(outputDesc,
2791 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07002792 true,
2793 0,
2794 NULL);
2795 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2796 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01002797 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002798 if (inputDesc == NULL) {
2799 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2800 return BAD_VALUE;
2801 }
2802 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08002803 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07002804 true,
2805 NULL);
2806 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002807 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2808 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2809 status, patchDesc->mAfPatchHandle);
2810 removeAudioPatch(patchDesc->mHandle);
2811 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002812 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002813 } else {
2814 return BAD_VALUE;
2815 }
2816 } else {
2817 return BAD_VALUE;
2818 }
2819 return NO_ERROR;
2820}
2821
2822status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2823 struct audio_patch *patches,
2824 unsigned int *generation)
2825{
François Gaffie53615e22015-03-19 09:24:12 +01002826 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002827 return BAD_VALUE;
2828 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002829 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01002830 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002831}
2832
Eric Laurente1715a42014-05-20 11:30:42 -07002833status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002834{
Eric Laurente1715a42014-05-20 11:30:42 -07002835 ALOGV("setAudioPortConfig()");
2836
2837 if (config == NULL) {
2838 return BAD_VALUE;
2839 }
2840 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2841 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002842 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2843 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002844 }
2845
Eric Laurenta121f902014-06-03 13:32:54 -07002846 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002847 if (config->type == AUDIO_PORT_TYPE_MIX) {
2848 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002849 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002850 if (outputDesc == NULL) {
2851 return BAD_VALUE;
2852 }
Eric Laurent84c70242014-06-23 08:46:27 -07002853 ALOG_ASSERT(!outputDesc->isDuplicated(),
2854 "setAudioPortConfig() called on duplicated output %d",
2855 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002856 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002857 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01002858 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002859 if (inputDesc == NULL) {
2860 return BAD_VALUE;
2861 }
Eric Laurenta121f902014-06-03 13:32:54 -07002862 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002863 } else {
2864 return BAD_VALUE;
2865 }
2866 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2867 sp<DeviceDescriptor> deviceDesc;
2868 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2869 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2870 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2871 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2872 } else {
2873 return BAD_VALUE;
2874 }
2875 if (deviceDesc == NULL) {
2876 return BAD_VALUE;
2877 }
Eric Laurenta121f902014-06-03 13:32:54 -07002878 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002879 } else {
2880 return BAD_VALUE;
2881 }
2882
Eric Laurenta121f902014-06-03 13:32:54 -07002883 struct audio_port_config backupConfig;
2884 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2885 if (status == NO_ERROR) {
2886 struct audio_port_config newConfig;
2887 audioPortConfig->toAudioPortConfig(&newConfig, config);
2888 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002889 }
Eric Laurenta121f902014-06-03 13:32:54 -07002890 if (status != NO_ERROR) {
2891 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002892 }
Eric Laurente1715a42014-05-20 11:30:42 -07002893
2894 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002895}
2896
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002897void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
2898{
Eric Laurentd60560a2015-04-10 11:31:20 -07002899 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002900 clearAudioPatches(uid);
2901 clearSessionRoutes(uid);
2902}
2903
Eric Laurent6a94d692014-05-20 11:18:06 -07002904void AudioPolicyManager::clearAudioPatches(uid_t uid)
2905{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002906 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002907 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2908 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002909 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002910 }
2911 }
2912}
2913
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002914void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
2915 audio_io_handle_t ouptutToSkip)
2916{
2917 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2918 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
2919 for (size_t j = 0; j < mOutputs.size(); j++) {
2920 if (mOutputs.keyAt(j) == ouptutToSkip) {
2921 continue;
2922 }
2923 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
2924 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
2925 continue;
2926 }
2927 // If the default device for this strategy is on another output mix,
2928 // invalidate all tracks in this strategy to force re connection.
2929 // Otherwise select new device on the output mix.
2930 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08002931 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002932 if (getStrategy((audio_stream_type_t)stream) == strategy) {
2933 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
2934 }
2935 }
2936 } else {
2937 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
2938 setOutputDevice(outputDesc, newDevice, false);
2939 }
2940 }
2941}
2942
2943void AudioPolicyManager::clearSessionRoutes(uid_t uid)
2944{
2945 // remove output routes associated with this uid
2946 SortedVector<routing_strategy> affectedStrategies;
2947 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
2948 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
2949 if (route->mUid == uid) {
2950 mOutputRoutes.removeItemsAt(i);
2951 if (route->mDeviceDescriptor != 0) {
2952 affectedStrategies.add(getStrategy(route->mStreamType));
2953 }
2954 }
2955 }
2956 // reroute outputs if necessary
2957 for (size_t i = 0; i < affectedStrategies.size(); i++) {
2958 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
2959 }
2960
2961 // remove input routes associated with this uid
2962 SortedVector<audio_source_t> affectedSources;
2963 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
2964 sp<SessionRoute> route = mInputRoutes.valueAt(i);
2965 if (route->mUid == uid) {
2966 mInputRoutes.removeItemsAt(i);
2967 if (route->mDeviceDescriptor != 0) {
2968 affectedSources.add(route->mSource);
2969 }
2970 }
2971 }
2972 // reroute inputs if necessary
2973 SortedVector<audio_io_handle_t> inputsToClose;
2974 for (size_t i = 0; i < mInputs.size(); i++) {
2975 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002976 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002977 inputsToClose.add(inputDesc->mIoHandle);
2978 }
2979 }
2980 for (size_t i = 0; i < inputsToClose.size(); i++) {
2981 closeInput(inputsToClose[i]);
2982 }
2983}
2984
Eric Laurentd60560a2015-04-10 11:31:20 -07002985void AudioPolicyManager::clearAudioSources(uid_t uid)
2986{
2987 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
2988 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
2989 if (sourceDesc->mUid == uid) {
2990 stopAudioSource(mAudioSources.keyAt(i));
2991 }
2992 }
2993}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002994
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002995status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2996 audio_io_handle_t *ioHandle,
2997 audio_devices_t *device)
2998{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08002999 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3000 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003001 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003002
François Gaffiedf372692015-03-19 10:43:27 +01003003 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003004}
3005
Eric Laurentd60560a2015-04-10 11:31:20 -07003006status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3007 const audio_attributes_t *attributes,
3008 audio_io_handle_t *handle,
3009 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003010{
Eric Laurentd60560a2015-04-10 11:31:20 -07003011 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3012 if (source == NULL || attributes == NULL || handle == NULL) {
3013 return BAD_VALUE;
3014 }
3015
3016 *handle = AUDIO_IO_HANDLE_NONE;
3017
3018 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3019 source->type != AUDIO_PORT_TYPE_DEVICE) {
3020 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3021 return INVALID_OPERATION;
3022 }
3023
3024 sp<DeviceDescriptor> srcDeviceDesc =
3025 mAvailableInputDevices.getDevice(source->ext.device.type,
3026 String8(source->ext.device.address));
3027 if (srcDeviceDesc == 0) {
3028 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3029 return BAD_VALUE;
3030 }
3031 sp<AudioSourceDescriptor> sourceDesc =
3032 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3033
3034 struct audio_patch dummyPatch;
3035 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3036 sourceDesc->mPatchDesc = patchDesc;
3037
3038 status_t status = connectAudioSource(sourceDesc);
3039 if (status == NO_ERROR) {
3040 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3041 *handle = sourceDesc->getHandle();
3042 }
3043 return status;
3044}
3045
3046status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3047{
3048 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3049
3050 // make sure we only have one patch per source.
3051 disconnectAudioSource(sourceDesc);
3052
3053 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003054 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003055 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3056
3057 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3058 sp<DeviceDescriptor> sinkDeviceDesc =
3059 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3060
3061 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3062 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3063
3064 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3065 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003066 srcDeviceDesc->getAudioPort()->mModule->getHalVersion() >= AUDIO_DEVICE_API_VERSION_3_0 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003067 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3068 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3069 // create patch between src device and output device
3070 // create Hwoutput and add to mHwOutputs
3071 } else {
3072 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3073 audio_io_handle_t output =
3074 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3075 if (output == AUDIO_IO_HANDLE_NONE) {
3076 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3077 return INVALID_OPERATION;
3078 }
3079 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3080 if (outputDesc->isDuplicated()) {
3081 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3082 return INVALID_OPERATION;
3083 }
3084 // create a special patch with no sink and two sources:
3085 // - the second source indicates to PatchPanel through which output mix this patch should
3086 // be connected as well as the stream type for volume control
3087 // - the sink is defined by whatever output device is currently selected for the output
3088 // though which this patch is routed.
3089 patch->num_sinks = 0;
3090 patch->num_sources = 2;
3091 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3092 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3093 patch->sources[1].ext.mix.usecase.stream = stream;
3094 status_t status = mpClientInterface->createAudioPatch(patch,
3095 &afPatchHandle,
3096 0);
3097 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3098 status, afPatchHandle);
3099 if (status != NO_ERROR) {
3100 ALOGW("%s patch panel could not connect device patch, error %d",
3101 __FUNCTION__, status);
3102 return INVALID_OPERATION;
3103 }
3104 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003105 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003106
3107 if (status != NO_ERROR) {
3108 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3109 return status;
3110 }
3111 sourceDesc->mSwOutput = outputDesc;
3112 if (delayMs != 0) {
3113 usleep(delayMs * 1000);
3114 }
3115 }
3116
3117 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3118 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3119
3120 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003121}
3122
Eric Laurent493404d2015-04-21 15:07:36 -07003123status_t AudioPolicyManager::stopAudioSource(audio_io_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003124{
Eric Laurentd60560a2015-04-10 11:31:20 -07003125 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3126 ALOGV("%s handle %d", __FUNCTION__, handle);
3127 if (sourceDesc == 0) {
3128 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3129 return BAD_VALUE;
3130 }
3131 status_t status = disconnectAudioSource(sourceDesc);
3132
3133 mAudioSources.removeItem(handle);
3134 return status;
3135}
3136
Andy Hung2ddee192015-12-18 17:34:44 -08003137status_t AudioPolicyManager::setMasterMono(bool mono)
3138{
3139 if (mMasterMono == mono) {
3140 return NO_ERROR;
3141 }
3142 mMasterMono = mono;
3143 // if enabling mono we close all offloaded devices, which will invalidate the
3144 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3145 // for recreating the new AudioTrack as non-offloaded PCM.
3146 //
3147 // If disabling mono, we leave all tracks as is: we don't know which clients
3148 // and tracks are able to be recreated as offloaded. The next "song" should
3149 // play back offloaded.
3150 if (mMasterMono) {
3151 Vector<audio_io_handle_t> offloaded;
3152 for (size_t i = 0; i < mOutputs.size(); ++i) {
3153 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3154 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3155 offloaded.push(desc->mIoHandle);
3156 }
3157 }
3158 for (size_t i = 0; i < offloaded.size(); ++i) {
3159 closeOutput(offloaded[i]);
3160 }
3161 }
3162 // update master mono for all remaining outputs
3163 for (size_t i = 0; i < mOutputs.size(); ++i) {
3164 updateMono(mOutputs.keyAt(i));
3165 }
3166 return NO_ERROR;
3167}
3168
3169status_t AudioPolicyManager::getMasterMono(bool *mono)
3170{
3171 *mono = mMasterMono;
3172 return NO_ERROR;
3173}
3174
Eric Laurentd60560a2015-04-10 11:31:20 -07003175status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3176{
3177 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3178
3179 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3180 if (patchDesc == 0) {
3181 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3182 sourceDesc->mPatchDesc->mHandle);
3183 return BAD_VALUE;
3184 }
3185 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3186
Eric Laurent28d09f02016-03-08 10:43:05 -08003187 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003188 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3189 if (swOutputDesc != 0) {
3190 stopSource(swOutputDesc, stream, false);
3191 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3192 } else {
3193 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3194 if (hwOutputDesc != 0) {
3195 // release patch between src device and output device
3196 // close Hwoutput and remove from mHwOutputs
3197 } else {
3198 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3199 }
3200 }
3201 return NO_ERROR;
3202}
3203
3204sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3205 audio_io_handle_t output, routing_strategy strategy)
3206{
3207 sp<AudioSourceDescriptor> source;
3208 for (size_t i = 0; i < mAudioSources.size(); i++) {
3209 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3210 routing_strategy sourceStrategy =
3211 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3212 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3213 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3214 source = sourceDesc;
3215 break;
3216 }
3217 }
3218 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003219}
3220
Eric Laurente552edb2014-03-10 17:42:56 -07003221// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003222// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003223// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003224uint32_t AudioPolicyManager::nextAudioPortGeneration()
3225{
3226 return android_atomic_inc(&mAudioPortGeneration);
3227}
3228
Eric Laurente0720872014-03-11 09:30:41 -07003229AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003230 :
3231#ifdef AUDIO_POLICY_TEST
3232 Thread(false),
3233#endif //AUDIO_POLICY_TEST
Eric Laurente552edb2014-03-10 17:42:56 -07003234 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003235 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003236 mAudioPortGeneration(1),
3237 mBeaconMuteRefCount(0),
3238 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003239 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003240 mTtsOutputAvailable(false),
3241 mMasterMono(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003242{
François Gaffied1ab2bd2015-12-02 18:20:06 +01003243 mUidCached = getuid();
3244 mpClientInterface = clientInterface;
3245
3246 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
3247 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
3248 // Note: remove also speaker_drc_enabled from global configuration of XML config file.
3249 bool speakerDrcEnabled = false;
3250
3251#ifdef USE_XML_AUDIO_POLICY_CONF
3252 mVolumeCurves = new VolumeCurvesCollection();
3253 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3254 mDefaultOutputDevice, speakerDrcEnabled,
3255 static_cast<VolumeCurvesCollection *>(mVolumeCurves));
3256 PolicySerializer serializer;
3257 if (serializer.deserialize(AUDIO_POLICY_XML_CONFIG_FILE, config) != NO_ERROR) {
3258#else
3259 mVolumeCurves = new StreamDescriptorCollection();
3260 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3261 mDefaultOutputDevice, speakerDrcEnabled);
3262 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3263 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3264#endif
3265 ALOGE("could not load audio policy configuration file, setting defaults");
3266 config.setDefault();
3267 }
3268 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3269 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
3270
3271 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003272 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3273 if (!engineInstance) {
3274 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3275 return;
3276 }
3277 // Retrieve the Policy Manager Interface
3278 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3279 if (mEngine == NULL) {
3280 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3281 return;
3282 }
3283 mEngine->setObserver(this);
3284 status_t status = mEngine->initCheck();
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07003285 (void) status;
François Gaffie2110e042015-03-24 08:41:51 +01003286 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3287
Eric Laurent3a4311c2014-03-17 12:00:47 -07003288 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003289 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003290 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3291 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003292 for (size_t i = 0; i < mHwModules.size(); i++) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003293 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003294 if (mHwModules[i]->mHandle == 0) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003295 ALOGW("could not open HW module %s", mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003296 continue;
3297 }
3298 // open all output streams needed to access attached devices
3299 // except for direct output streams that are only opened when they are actually
3300 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003301 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003302 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3303 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003304 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003305
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003306 if (!outProfile->hasSupportedDevices()) {
3307 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003308 continue;
3309 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003310 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003311 mTtsOutputAvailable = true;
3312 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003313
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003314 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003315 continue;
3316 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003317 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003318 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3319 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003320 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003321 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003322 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003323 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003324 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003325 if ((profileType & outputDeviceTypes) == 0) {
3326 continue;
3327 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003328 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3329 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003330 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3331 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
3332 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3333 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003334
3335 outputDesc->mDevice = profileType;
3336 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3337 config.sample_rate = outputDesc->mSamplingRate;
3338 config.channel_mask = outputDesc->mChannelMask;
3339 config.format = outputDesc->mFormat;
3340 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003341 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003342 &output,
3343 &config,
3344 &outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003345 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003346 &outputDesc->mLatency,
3347 outputDesc->mFlags);
3348
3349 if (status != NO_ERROR) {
3350 ALOGW("Cannot open output stream for device %08x on hw module %s",
3351 outputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003352 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003353 } else {
3354 outputDesc->mSamplingRate = config.sample_rate;
3355 outputDesc->mChannelMask = config.channel_mask;
3356 outputDesc->mFormat = config.format;
3357
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003358 for (size_t k = 0; k < supportedDevices.size(); k++) {
3359 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003360 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003361 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3362 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003363 }
3364 }
3365 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003366 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003367 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003368 }
3369 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003370 setOutputDevice(outputDesc,
Eric Laurentd78f1532014-09-16 16:38:20 -07003371 outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003372 true,
3373 0,
3374 NULL,
3375 address.string());
Eric Laurentd78f1532014-09-16 16:38:20 -07003376 }
Eric Laurente552edb2014-03-10 17:42:56 -07003377 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003378 // open input streams needed to access attached devices to validate
3379 // mAvailableInputDevices list
3380 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3381 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003382 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003383
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003384 if (!inProfile->hasSupportedDevices()) {
3385 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003386 continue;
3387 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003388 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003389 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003390 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3391
Eric Laurentd78f1532014-09-16 16:38:20 -07003392 if ((profileType & inputDeviceTypes) == 0) {
3393 continue;
3394 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003395 sp<AudioInputDescriptor> inputDesc =
3396 new AudioInputDescriptor(inProfile);
Eric Laurentd78f1532014-09-16 16:38:20 -07003397
Eric Laurentd78f1532014-09-16 16:38:20 -07003398 inputDesc->mDevice = profileType;
3399
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003400 // find the address
3401 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3402 // the inputs vector must be of size 1, but we don't want to crash here
3403 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3404 : String8("");
3405 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3406 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3407
Eric Laurentd78f1532014-09-16 16:38:20 -07003408 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3409 config.sample_rate = inputDesc->mSamplingRate;
3410 config.channel_mask = inputDesc->mChannelMask;
3411 config.format = inputDesc->mFormat;
3412 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003413 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003414 &input,
3415 &config,
3416 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003417 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003418 AUDIO_SOURCE_MIC,
3419 AUDIO_INPUT_FLAG_NONE);
3420
3421 if (status == NO_ERROR) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003422 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3423 for (size_t k = 0; k < supportedDevices.size(); k++) {
3424 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003425 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003426 if (index >= 0) {
3427 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3428 if (!devDesc->isAttached()) {
3429 devDesc->attach(mHwModules[i]);
3430 devDesc->importAudioPort(inProfile);
3431 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003432 }
3433 }
3434 mpClientInterface->closeInput(input);
3435 } else {
3436 ALOGW("Cannot open input stream for device %08x on hw module %s",
3437 inputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003438 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003439 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003440 }
3441 }
3442 // make sure all attached devices have been allocated a unique ID
3443 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003444 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003445 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003446 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3447 continue;
3448 }
François Gaffie2110e042015-03-24 08:41:51 +01003449 // The device is now validated and can be appended to the available devices of the engine
3450 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3451 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003452 i++;
3453 }
3454 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003455 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003456 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003457 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3458 continue;
3459 }
François Gaffie2110e042015-03-24 08:41:51 +01003460 // The device is now validated and can be appended to the available devices of the engine
3461 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3462 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003463 i++;
3464 }
3465 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003466 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003467 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003468 }
Eric Laurente552edb2014-03-10 17:42:56 -07003469
3470 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3471
3472 updateDevicesAndOutputs();
3473
3474#ifdef AUDIO_POLICY_TEST
3475 if (mPrimaryOutput != 0) {
3476 AudioParameter outputCmd = AudioParameter();
3477 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003478 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
Eric Laurente552edb2014-03-10 17:42:56 -07003479
3480 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3481 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003482 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3483 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003484 mTestLatencyMs = 0;
3485 mCurOutput = 0;
3486 mDirectOutput = false;
3487 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3488 mTestOutputs[i] = 0;
3489 }
3490
3491 const size_t SIZE = 256;
3492 char buffer[SIZE];
3493 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3494 run(buffer, ANDROID_PRIORITY_AUDIO);
3495 }
3496#endif //AUDIO_POLICY_TEST
3497}
3498
Eric Laurente0720872014-03-11 09:30:41 -07003499AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003500{
3501#ifdef AUDIO_POLICY_TEST
3502 exit();
3503#endif //AUDIO_POLICY_TEST
3504 for (size_t i = 0; i < mOutputs.size(); i++) {
3505 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003506 }
3507 for (size_t i = 0; i < mInputs.size(); i++) {
3508 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003509 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003510 mAvailableOutputDevices.clear();
3511 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003512 mOutputs.clear();
3513 mInputs.clear();
3514 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003515}
3516
Eric Laurente0720872014-03-11 09:30:41 -07003517status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003518{
Eric Laurent87ffa392015-05-22 10:32:38 -07003519 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003520}
3521
3522#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003523bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003524{
3525 ALOGV("entering threadLoop()");
3526 while (!exitPending())
3527 {
3528 String8 command;
3529 int valueInt;
3530 String8 value;
3531
3532 Mutex::Autolock _l(mLock);
3533 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3534
3535 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3536 AudioParameter param = AudioParameter(command);
3537
3538 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3539 valueInt != 0) {
3540 ALOGV("Test command %s received", command.string());
3541 String8 target;
3542 if (param.get(String8("target"), target) != NO_ERROR) {
3543 target = "Manager";
3544 }
3545 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3546 param.remove(String8("test_cmd_policy_output"));
3547 mCurOutput = valueInt;
3548 }
3549 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3550 param.remove(String8("test_cmd_policy_direct"));
3551 if (value == "false") {
3552 mDirectOutput = false;
3553 } else if (value == "true") {
3554 mDirectOutput = true;
3555 }
3556 }
3557 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3558 param.remove(String8("test_cmd_policy_input"));
3559 mTestInput = valueInt;
3560 }
3561
3562 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3563 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003564 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003565 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003566 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003567 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003568 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003569 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003570 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003571 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003572 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003573 if (target == "Manager") {
3574 mTestFormat = format;
3575 } else if (mTestOutputs[mCurOutput] != 0) {
3576 AudioParameter outputParam = AudioParameter();
3577 outputParam.addInt(String8("format"), format);
3578 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3579 }
3580 }
3581 }
3582 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3583 param.remove(String8("test_cmd_policy_channels"));
3584 int channels = 0;
3585
3586 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003587 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003588 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003589 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003590 }
3591 if (channels != 0) {
3592 if (target == "Manager") {
3593 mTestChannels = channels;
3594 } else if (mTestOutputs[mCurOutput] != 0) {
3595 AudioParameter outputParam = AudioParameter();
3596 outputParam.addInt(String8("channels"), channels);
3597 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3598 }
3599 }
3600 }
3601 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3602 param.remove(String8("test_cmd_policy_sampleRate"));
3603 if (valueInt >= 0 && valueInt <= 96000) {
3604 int samplingRate = valueInt;
3605 if (target == "Manager") {
3606 mTestSamplingRate = samplingRate;
3607 } else if (mTestOutputs[mCurOutput] != 0) {
3608 AudioParameter outputParam = AudioParameter();
3609 outputParam.addInt(String8("sampling_rate"), samplingRate);
3610 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3611 }
3612 }
3613 }
3614
3615 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3616 param.remove(String8("test_cmd_policy_reopen"));
3617
Eric Laurentc75307b2015-03-17 15:29:32 -07003618 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
Eric Laurente552edb2014-03-10 17:42:56 -07003619
Eric Laurentc75307b2015-03-17 15:29:32 -07003620 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
Eric Laurente552edb2014-03-10 17:42:56 -07003621
Eric Laurentc75307b2015-03-17 15:29:32 -07003622 removeOutput(mPrimaryOutput->mIoHandle);
3623 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
3624 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003625 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003626 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3627 config.sample_rate = outputDesc->mSamplingRate;
3628 config.channel_mask = outputDesc->mChannelMask;
3629 config.format = outputDesc->mFormat;
Eric Laurentc75307b2015-03-17 15:29:32 -07003630 audio_io_handle_t handle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003631 status_t status = mpClientInterface->openOutput(moduleHandle,
Eric Laurentc75307b2015-03-17 15:29:32 -07003632 &handle,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003633 &config,
3634 &outputDesc->mDevice,
3635 String8(""),
3636 &outputDesc->mLatency,
3637 outputDesc->mFlags);
3638 if (status != NO_ERROR) {
3639 ALOGE("Failed to reopen hardware output stream, "
3640 "samplingRate: %d, format %d, channels %d",
3641 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003642 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003643 outputDesc->mSamplingRate = config.sample_rate;
3644 outputDesc->mChannelMask = config.channel_mask;
3645 outputDesc->mFormat = config.format;
Eric Laurentc75307b2015-03-17 15:29:32 -07003646 mPrimaryOutput = outputDesc;
Eric Laurente552edb2014-03-10 17:42:56 -07003647 AudioParameter outputCmd = AudioParameter();
3648 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003649 mpClientInterface->setParameters(handle, outputCmd.toString());
3650 addOutput(handle, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07003651 }
3652 }
3653
3654
3655 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3656 }
3657 }
3658 return false;
3659}
3660
Eric Laurente0720872014-03-11 09:30:41 -07003661void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003662{
3663 {
3664 AutoMutex _l(mLock);
3665 requestExit();
3666 mWaitWorkCV.signal();
3667 }
3668 requestExitAndWait();
3669}
3670
Eric Laurente0720872014-03-11 09:30:41 -07003671int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003672{
3673 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3674 if (output == mTestOutputs[i]) return i;
3675 }
3676 return 0;
3677}
3678#endif //AUDIO_POLICY_TEST
3679
3680// ---
3681
Eric Laurentc75307b2015-03-17 15:29:32 -07003682void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<SwAudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003683{
François Gaffie98cc1912015-03-18 17:52:40 +01003684 outputDesc->setIoHandle(output);
Eric Laurent1c333e22014-05-20 10:48:17 -07003685 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08003686 updateMono(output); // update mono status when adding to output list
Eric Laurent6a94d692014-05-20 11:18:06 -07003687 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003688}
3689
François Gaffie53615e22015-03-19 09:24:12 +01003690void AudioPolicyManager::removeOutput(audio_io_handle_t output)
3691{
3692 mOutputs.removeItem(output);
3693}
3694
Eric Laurent1f2f2232014-06-02 12:01:23 -07003695void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003696{
François Gaffie98cc1912015-03-18 17:52:40 +01003697 inputDesc->setIoHandle(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003698 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003699 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003700}
Eric Laurente552edb2014-03-10 17:42:56 -07003701
Eric Laurentc75307b2015-03-17 15:29:32 -07003702void AudioPolicyManager::findIoHandlesByAddress(sp<SwAudioOutputDescriptor> desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003703 const audio_devices_t device /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003704 const String8 address /*in*/,
3705 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003706 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003707 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08003708 if (devDesc != 0) {
3709 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3710 desc->mIoHandle, address.string());
3711 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003712 }
3713}
3714
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003715status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003716 audio_policy_dev_state_t state,
3717 SortedVector<audio_io_handle_t>& outputs,
3718 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003719{
François Gaffie53615e22015-03-19 09:24:12 +01003720 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07003721 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003722
3723 if (audio_device_is_digital(device)) {
3724 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003725 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003726 }
Eric Laurente552edb2014-03-10 17:42:56 -07003727
Eric Laurent3b73df72014-03-11 09:06:29 -07003728 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003729 // first list already open outputs that can be routed to this device
3730 for (size_t i = 0; i < mOutputs.size(); i++) {
3731 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07003732 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003733 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003734 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3735 outputs.add(mOutputs.keyAt(i));
3736 } else {
3737 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003738 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003739 }
Eric Laurente552edb2014-03-10 17:42:56 -07003740 }
3741 }
3742 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003743 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003744 for (size_t i = 0; i < mHwModules.size(); i++)
3745 {
3746 if (mHwModules[i]->mHandle == 0) {
3747 continue;
3748 }
3749 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3750 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003751 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003752 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003753 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003754 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003755 profiles.add(profile);
3756 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3757 }
Eric Laurente552edb2014-03-10 17:42:56 -07003758 }
3759 }
3760 }
3761
Eric Laurent7b279bb2015-12-14 10:18:23 -08003762 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003763
Eric Laurente552edb2014-03-10 17:42:56 -07003764 if (profiles.isEmpty() && outputs.isEmpty()) {
3765 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3766 return BAD_VALUE;
3767 }
3768
3769 // open outputs for matching profiles if needed. Direct outputs are also opened to
3770 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3771 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003772 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003773
3774 // nothing to do if one output is already opened for this profile
3775 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003776 for (j = 0; j < outputs.size(); j++) {
3777 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003778 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003779 // matching profile: save the sample rates, format and channel masks supported
3780 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07003781 if (audio_device_is_digital(device)) {
3782 devDesc->importAudioPort(profile);
3783 }
Eric Laurente552edb2014-03-10 17:42:56 -07003784 break;
3785 }
3786 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003787 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003788 continue;
3789 }
3790
Eric Laurent83b88082014-06-20 18:31:16 -07003791 ALOGV("opening output for device %08x with params %s profile %p",
3792 device, address.string(), profile.get());
Eric Laurentc75307b2015-03-17 15:29:32 -07003793 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003794 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003795 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3796 config.sample_rate = desc->mSamplingRate;
3797 config.channel_mask = desc->mChannelMask;
3798 config.format = desc->mFormat;
3799 config.offload_info.sample_rate = desc->mSamplingRate;
3800 config.offload_info.channel_mask = desc->mChannelMask;
3801 config.offload_info.format = desc->mFormat;
3802 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003803 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003804 &output,
3805 &config,
3806 &desc->mDevice,
3807 address,
3808 &desc->mLatency,
3809 desc->mFlags);
3810 if (status == NO_ERROR) {
3811 desc->mSamplingRate = config.sample_rate;
3812 desc->mChannelMask = config.channel_mask;
3813 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003814
Eric Laurentd4692962014-05-05 18:13:44 -07003815 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003816 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003817 char *param = audio_device_address_to_parameter(device, address);
3818 mpClientInterface->setParameters(output, String8(param));
3819 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003820 }
Phil Burk00eeb322016-03-31 12:41:00 -07003821 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01003822 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003823 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003824 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003825 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003826 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07003827 mpClientInterface->closeOutput(output);
Phil Burk702b1052016-03-02 16:38:26 -08003828 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003829 profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003830 config.offload_info.sample_rate = config.sample_rate;
3831 config.offload_info.channel_mask = config.channel_mask;
3832 config.offload_info.format = config.format;
Eric Laurent322b4d22015-04-03 15:57:54 -07003833 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003834 &output,
3835 &config,
3836 &desc->mDevice,
3837 address,
3838 &desc->mLatency,
3839 desc->mFlags);
3840 if (status == NO_ERROR) {
3841 desc->mSamplingRate = config.sample_rate;
3842 desc->mChannelMask = config.channel_mask;
3843 desc->mFormat = config.format;
3844 } else {
3845 output = AUDIO_IO_HANDLE_NONE;
3846 }
Eric Laurentd4692962014-05-05 18:13:44 -07003847 }
3848
Eric Laurentcf2c0212014-07-25 16:20:43 -07003849 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003850 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01003851 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01003852 sp<AudioPolicyMix> policyMix;
3853 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003854 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3855 address.string());
3856 }
François Gaffie036e1e92015-03-19 10:16:24 +01003857 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07003858 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01003859
Eric Laurent87ffa392015-05-22 10:32:38 -07003860 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
3861 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08003862 // no duplicated output for direct outputs and
3863 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003864 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003865
Eric Laurentd4692962014-05-05 18:13:44 -07003866 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07003867 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003868
Eric Laurentd4692962014-05-05 18:13:44 -07003869 //TODO: configure audio effect output stage here
3870
3871 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07003872 duplicatedOutput =
3873 mpClientInterface->openDuplicateOutput(output,
3874 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003875 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003876 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07003877 sp<SwAudioOutputDescriptor> dupOutputDesc =
3878 new SwAudioOutputDescriptor(NULL, mpClientInterface);
3879 dupOutputDesc->mOutput1 = mPrimaryOutput;
3880 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003881 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3882 dupOutputDesc->mFormat = desc->mFormat;
3883 dupOutputDesc->mChannelMask = desc->mChannelMask;
3884 dupOutputDesc->mLatency = desc->mLatency;
3885 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003886 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07003887 } else {
3888 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07003889 mPrimaryOutput->mIoHandle, output);
Eric Laurentd4692962014-05-05 18:13:44 -07003890 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01003891 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003892 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003893 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003894 }
Eric Laurente552edb2014-03-10 17:42:56 -07003895 }
3896 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003897 } else {
3898 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003899 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003900 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003901 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003902 profiles.removeAt(profile_index);
3903 profile_index--;
3904 } else {
3905 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07003906 // Load digital format info only for digital devices
3907 if (audio_device_is_digital(device)) {
3908 devDesc->importAudioPort(profile);
3909 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003910
François Gaffie53615e22015-03-19 09:24:12 +01003911 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003912 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3913 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07003914 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003915 NULL/*patch handle*/, address.string());
3916 }
Eric Laurente552edb2014-03-10 17:42:56 -07003917 ALOGV("checkOutputsForDevice(): adding output %d", output);
3918 }
3919 }
3920
3921 if (profiles.isEmpty()) {
3922 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3923 return BAD_VALUE;
3924 }
Eric Laurentd4692962014-05-05 18:13:44 -07003925 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003926 // check if one opened output is not needed any more after disconnecting one device
3927 for (size_t i = 0; i < mOutputs.size(); i++) {
3928 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003929 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003930 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01003931 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07003932 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08003933 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003934 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003935 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3936 mOutputs.keyAt(i));
3937 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003938 }
Eric Laurente552edb2014-03-10 17:42:56 -07003939 }
3940 }
Eric Laurentd4692962014-05-05 18:13:44 -07003941 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003942 for (size_t i = 0; i < mHwModules.size(); i++)
3943 {
3944 if (mHwModules[i]->mHandle == 0) {
3945 continue;
3946 }
3947 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3948 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003949 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003950 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003951 ALOGV("checkOutputsForDevice(): "
3952 "clearing direct output profile %zu on module %zu", j, i);
François Gaffie112b0af2015-11-19 16:13:25 +01003953 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07003954 }
3955 }
3956 }
3957 }
3958 return NO_ERROR;
3959}
3960
Paul McLean9080a4c2015-06-18 08:24:02 -07003961status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor> devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003962 audio_policy_dev_state_t state,
3963 SortedVector<audio_io_handle_t>& inputs,
3964 const String8 address)
Eric Laurentd4692962014-05-05 18:13:44 -07003965{
Paul McLean9080a4c2015-06-18 08:24:02 -07003966 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003967 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003968
3969 if (audio_device_is_digital(device)) {
3970 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003971 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003972 }
3973
Eric Laurentd4692962014-05-05 18:13:44 -07003974 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3975 // first list already open inputs that can be routed to this device
3976 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3977 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003978 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003979 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3980 inputs.add(mInputs.keyAt(input_index));
3981 }
3982 }
3983
3984 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003985 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003986 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3987 {
3988 if (mHwModules[module_idx]->mHandle == 0) {
3989 continue;
3990 }
3991 for (size_t profile_index = 0;
3992 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3993 profile_index++)
3994 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003995 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
3996
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003997 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003998 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003999 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004000 profiles.add(profile);
4001 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
4002 profile_index, module_idx);
4003 }
Eric Laurentd4692962014-05-05 18:13:44 -07004004 }
4005 }
4006 }
4007
4008 if (profiles.isEmpty() && inputs.isEmpty()) {
4009 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4010 return BAD_VALUE;
4011 }
4012
4013 // open inputs for matching profiles if needed. Direct inputs are also opened to
4014 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4015 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4016
Eric Laurent1c333e22014-05-20 10:48:17 -07004017 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07004018 // nothing to do if one input is already opened for this profile
4019 size_t input_index;
4020 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4021 desc = mInputs.valueAt(input_index);
4022 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004023 if (audio_device_is_digital(device)) {
4024 devDesc->importAudioPort(profile);
4025 }
Eric Laurentd4692962014-05-05 18:13:44 -07004026 break;
4027 }
4028 }
4029 if (input_index != mInputs.size()) {
4030 continue;
4031 }
4032
4033 ALOGV("opening input for device 0x%X with params %s", device, address.string());
4034 desc = new AudioInputDescriptor(profile);
4035 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07004036 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4037 config.sample_rate = desc->mSamplingRate;
4038 config.channel_mask = desc->mChannelMask;
4039 config.format = desc->mFormat;
4040 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07004041 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004042 &input,
4043 &config,
4044 &desc->mDevice,
4045 address,
4046 AUDIO_SOURCE_MIC,
4047 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07004048
Eric Laurentcf2c0212014-07-25 16:20:43 -07004049 if (status == NO_ERROR) {
4050 desc->mSamplingRate = config.sample_rate;
4051 desc->mChannelMask = config.channel_mask;
4052 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07004053
Eric Laurentd4692962014-05-05 18:13:44 -07004054 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004055 char *param = audio_device_address_to_parameter(device, address);
4056 mpClientInterface->setParameters(input, String8(param));
4057 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004058 }
Phil Burk00eeb322016-03-31 12:41:00 -07004059 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004060 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004061 ALOGW("checkInputsForDevice() direct input missing param");
4062 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004063 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004064 }
4065
4066 if (input != 0) {
4067 addInput(input, desc);
4068 }
4069 } // endif input != 0
4070
Eric Laurentcf2c0212014-07-25 16:20:43 -07004071 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004072 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004073 profiles.removeAt(profile_index);
4074 profile_index--;
4075 } else {
4076 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004077 if (audio_device_is_digital(device)) {
4078 devDesc->importAudioPort(profile);
4079 }
Eric Laurentd4692962014-05-05 18:13:44 -07004080 ALOGV("checkInputsForDevice(): adding input %d", input);
4081 }
4082 } // end scan profiles
4083
4084 if (profiles.isEmpty()) {
4085 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4086 return BAD_VALUE;
4087 }
4088 } else {
4089 // Disconnect
4090 // check if one opened input is not needed any more after disconnecting one device
4091 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4092 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004093 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004094 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4095 mInputs.keyAt(input_index));
4096 inputs.add(mInputs.keyAt(input_index));
4097 }
4098 }
4099 // Clear any profiles associated with the disconnected device.
4100 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
4101 if (mHwModules[module_index]->mHandle == 0) {
4102 continue;
4103 }
4104 for (size_t profile_index = 0;
4105 profile_index < mHwModules[module_index]->mInputProfiles.size();
4106 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004107 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004108 if (profile->supportDevice(device)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004109 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07004110 profile_index, module_index);
François Gaffie112b0af2015-11-19 16:13:25 +01004111 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004112 }
4113 }
4114 }
4115 } // end disconnect
4116
4117 return NO_ERROR;
4118}
4119
4120
Eric Laurente0720872014-03-11 09:30:41 -07004121void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004122{
4123 ALOGV("closeOutput(%d)", output);
4124
Eric Laurentc75307b2015-03-17 15:29:32 -07004125 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004126 if (outputDesc == NULL) {
4127 ALOGW("closeOutput() unknown output %d", output);
4128 return;
4129 }
François Gaffie036e1e92015-03-19 10:16:24 +01004130 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004131
Eric Laurente552edb2014-03-10 17:42:56 -07004132 // look for duplicated outputs connected to the output being removed.
4133 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004134 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004135 if (dupOutputDesc->isDuplicated() &&
4136 (dupOutputDesc->mOutput1 == outputDesc ||
4137 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004138 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004139 if (dupOutputDesc->mOutput1 == outputDesc) {
4140 outputDesc2 = dupOutputDesc->mOutput2;
4141 } else {
4142 outputDesc2 = dupOutputDesc->mOutput1;
4143 }
4144 // As all active tracks on duplicated output will be deleted,
4145 // and as they were also referenced on the other output, the reference
4146 // count for their stream type must be adjusted accordingly on
4147 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07004148 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004149 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004150 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004151 }
4152 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4153 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4154
4155 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004156 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004157 }
4158 }
4159
Eric Laurent05b90f82014-08-27 15:32:29 -07004160 nextAudioPortGeneration();
4161
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004162 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004163 if (index >= 0) {
4164 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004165 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004166 mAudioPatches.removeItemsAt(index);
4167 mpClientInterface->onAudioPatchListUpdate();
4168 }
4169
Eric Laurente552edb2014-03-10 17:42:56 -07004170 AudioParameter param;
4171 param.add(String8("closing"), String8("true"));
4172 mpClientInterface->setParameters(output, param.toString());
4173
4174 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004175 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004176 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004177}
4178
4179void AudioPolicyManager::closeInput(audio_io_handle_t input)
4180{
4181 ALOGV("closeInput(%d)", input);
4182
4183 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4184 if (inputDesc == NULL) {
4185 ALOGW("closeInput() unknown input %d", input);
4186 return;
4187 }
4188
Eric Laurent6a94d692014-05-20 11:18:06 -07004189 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004190
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004191 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004192 if (index >= 0) {
4193 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004194 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004195 mAudioPatches.removeItemsAt(index);
4196 mpClientInterface->onAudioPatchListUpdate();
4197 }
4198
4199 mpClientInterface->closeInput(input);
4200 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004201}
4202
Eric Laurentc75307b2015-03-17 15:29:32 -07004203SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4204 audio_devices_t device,
4205 SwAudioOutputCollection openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004206{
4207 SortedVector<audio_io_handle_t> outputs;
4208
4209 ALOGVV("getOutputsForDevice() device %04x", device);
4210 for (size_t i = 0; i < openOutputs.size(); i++) {
4211 ALOGVV("output %d isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004212 i, openOutputs.valueAt(i)->isDuplicated(),
4213 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004214 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4215 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4216 outputs.add(openOutputs.keyAt(i));
4217 }
4218 }
4219 return outputs;
4220}
4221
Eric Laurente0720872014-03-11 09:30:41 -07004222bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004223 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004224{
4225 if (outputs1.size() != outputs2.size()) {
4226 return false;
4227 }
4228 for (size_t i = 0; i < outputs1.size(); i++) {
4229 if (outputs1[i] != outputs2[i]) {
4230 return false;
4231 }
4232 }
4233 return true;
4234}
4235
Eric Laurente0720872014-03-11 09:30:41 -07004236void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004237{
4238 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4239 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4240 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4241 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4242
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004243 // also take into account external policy-related changes: add all outputs which are
4244 // associated with policies in the "before" and "after" output vectors
4245 ALOGVV("checkOutputForStrategy(): policy related outputs");
4246 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004247 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004248 if (desc != 0 && desc->mPolicyMix != NULL) {
4249 srcOutputs.add(desc->mIoHandle);
4250 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4251 }
4252 }
4253 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004254 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004255 if (desc != 0 && desc->mPolicyMix != NULL) {
4256 dstOutputs.add(desc->mIoHandle);
4257 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4258 }
4259 }
4260
Eric Laurente552edb2014-03-10 17:42:56 -07004261 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4262 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4263 strategy, srcOutputs[0], dstOutputs[0]);
4264 // mute strategy while moving tracks from one output to another
4265 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004266 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004267 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004268 setStrategyMute(strategy, true, desc);
4269 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004270 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004271 sp<AudioSourceDescriptor> source =
4272 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4273 if (source != 0){
4274 connectAudioSource(source);
4275 }
Eric Laurente552edb2014-03-10 17:42:56 -07004276 }
4277
4278 // Move effects associated to this strategy from previous output to new output
4279 if (strategy == STRATEGY_MEDIA) {
4280 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4281 SortedVector<audio_io_handle_t> moved;
4282 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004283 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4284 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4285 effectDesc->mIo != fxOutput) {
4286 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004287 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4288 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004289 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004290 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004291 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004292 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004293 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004294 }
4295 }
4296 }
4297 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004298 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004299 if (getStrategy((audio_stream_type_t)i) == strategy) {
4300 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004301 }
4302 }
4303 }
4304}
4305
Eric Laurente0720872014-03-11 09:30:41 -07004306void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004307{
François Gaffie2110e042015-03-24 08:41:51 +01004308 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004309 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004310 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004311 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004312 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004313 checkOutputForStrategy(STRATEGY_SONIFICATION);
4314 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004315 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004316 checkOutputForStrategy(STRATEGY_MEDIA);
4317 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004318 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004319}
4320
Eric Laurente0720872014-03-11 09:30:41 -07004321void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004322{
François Gaffie53615e22015-03-19 09:24:12 +01004323 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07004324 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004325 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004326 return;
4327 }
4328
Eric Laurent3a4311c2014-03-17 12:00:47 -07004329 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004330 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4331 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4332 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07004333 // suspend A2DP output if:
4334 // (NOT already suspended) &&
4335 // ((SCO device is connected &&
4336 // (forced usage for communication || for record is SCO))) ||
4337 // (phone state is ringing || in call)
4338 //
4339 // restore A2DP output if:
4340 // (Already suspended) &&
4341 // ((SCO device is NOT connected ||
4342 // (forced usage NOT for communication && NOT for record is SCO))) &&
4343 // (phone state is NOT ringing && NOT in call)
4344 //
4345 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004346 if ((!isScoConnected ||
François Gaffie2110e042015-03-24 08:41:51 +01004347 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) != AUDIO_POLICY_FORCE_BT_SCO) &&
4348 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) != AUDIO_POLICY_FORCE_BT_SCO))) &&
4349 ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
4350 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004351
4352 mpClientInterface->restoreOutput(a2dpOutput);
4353 mA2dpSuspended = false;
4354 }
4355 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004356 if ((isScoConnected &&
François Gaffie2110e042015-03-24 08:41:51 +01004357 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) == AUDIO_POLICY_FORCE_BT_SCO) ||
4358 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) == AUDIO_POLICY_FORCE_BT_SCO))) ||
4359 ((mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
4360 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004361
4362 mpClientInterface->suspendOutput(a2dpOutput);
4363 mA2dpSuspended = true;
4364 }
4365 }
4366}
4367
Eric Laurentc75307b2015-03-17 15:29:32 -07004368audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4369 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004370{
4371 audio_devices_t device = AUDIO_DEVICE_NONE;
4372
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004373 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004374 if (index >= 0) {
4375 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4376 if (patchDesc->mUid != mUidCached) {
4377 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004378 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004379 return outputDesc->device();
4380 }
4381 }
4382
Eric Laurente552edb2014-03-10 17:42:56 -07004383 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004384 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004385 // use device for strategy enforced audible
4386 // 2: we are in call or the strategy phone is active on the output:
4387 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004388 // 3: the strategy for enforced audible is active but not enforced on the output:
4389 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004390 // 4: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004391 // use device for strategy sonification
Eric Laurent28d09f02016-03-08 10:43:05 -08004392 // 5: the strategy accessibility is active on the output:
4393 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004394 // 6: the strategy "respectful" sonification is active on the output:
4395 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004396 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004397 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004398 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004399 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004400 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004401 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004402 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004403 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004404 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4405 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004406 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004407 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004408 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
Jon Eklund966095e2014-09-09 15:39:49 -05004409 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004410 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004411 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004412 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4413 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004414 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004415 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004416 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004417 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004418 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004419 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004420 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004421 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004422 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004423 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004424 }
4425
Eric Laurent1c333e22014-05-20 10:48:17 -07004426 ALOGV("getNewOutputDevice() selected device %x", device);
4427 return device;
4428}
4429
Eric Laurentfb66dd92016-01-28 18:32:03 -08004430audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004431{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004432 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004433
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004434 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004435 if (index >= 0) {
4436 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4437 if (patchDesc->mUid != mUidCached) {
4438 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004439 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004440 return inputDesc->mDevice;
4441 }
4442 }
4443
Eric Laurentfb66dd92016-01-28 18:32:03 -08004444 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
4445 if (isInCall()) {
4446 device = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4447 } else if (source != AUDIO_SOURCE_DEFAULT) {
4448 device = getDeviceAndMixForInputSource(source);
4449 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004450
Eric Laurente552edb2014-03-10 17:42:56 -07004451 return device;
4452}
4453
Eric Laurent794fde22016-03-11 09:50:45 -08004454bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4455 audio_stream_type_t stream2) {
4456 return ((stream1 == stream2) ||
4457 ((stream1 == AUDIO_STREAM_ACCESSIBILITY) && (stream2 == AUDIO_STREAM_MUSIC)) ||
4458 ((stream1 == AUDIO_STREAM_MUSIC) && (stream2 == AUDIO_STREAM_ACCESSIBILITY)));
Eric Laurent28d09f02016-03-08 10:43:05 -08004459}
4460
Eric Laurente0720872014-03-11 09:30:41 -07004461uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004462 return (uint32_t)getStrategy(stream);
4463}
4464
Eric Laurente0720872014-03-11 09:30:41 -07004465audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004466 // By checking the range of stream before calling getStrategy, we avoid
4467 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4468 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004469 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004470 return AUDIO_DEVICE_NONE;
4471 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004472 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004473 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4474 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004475 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004476 }
Eric Laurent794fde22016-03-11 09:50:45 -08004477 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004478 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004479 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurent28d09f02016-03-08 10:43:05 -08004480 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(curDevices, mOutputs);
4481 for (size_t i = 0; i < outputs.size(); i++) {
4482 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent794fde22016-03-11 09:50:45 -08004483 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004484 curDevices |= outputDesc->device();
4485 }
4486 }
4487 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004488 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004489
4490 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4491 and doesn't really need to.*/
4492 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4493 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4494 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4495 }
Eric Laurente552edb2014-03-10 17:42:56 -07004496 return devices;
4497}
4498
François Gaffie2110e042015-03-24 08:41:51 +01004499routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4500{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004501 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004502 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004503}
4504
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004505uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4506 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004507 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4508 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4509 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004510 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4511 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4512 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004513 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004514 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004515}
4516
Eric Laurente0720872014-03-11 09:30:41 -07004517void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004518 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004519 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004520 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4521 updateDevicesAndOutputs();
4522 break;
4523 default:
4524 break;
4525 }
4526}
4527
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004528uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004529
4530 // skip beacon mute management if a dedicated TTS output is available
4531 if (mTtsOutputAvailable) {
4532 return 0;
4533 }
4534
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004535 switch(event) {
4536 case STARTING_OUTPUT:
4537 mBeaconMuteRefCount++;
4538 break;
4539 case STOPPING_OUTPUT:
4540 if (mBeaconMuteRefCount > 0) {
4541 mBeaconMuteRefCount--;
4542 }
4543 break;
4544 case STARTING_BEACON:
4545 mBeaconPlayingRefCount++;
4546 break;
4547 case STOPPING_BEACON:
4548 if (mBeaconPlayingRefCount > 0) {
4549 mBeaconPlayingRefCount--;
4550 }
4551 break;
4552 }
4553
4554 if (mBeaconMuteRefCount > 0) {
4555 // any playback causes beacon to be muted
4556 return setBeaconMute(true);
4557 } else {
4558 // no other playback: unmute when beacon starts playing, mute when it stops
4559 return setBeaconMute(mBeaconPlayingRefCount == 0);
4560 }
4561}
4562
4563uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4564 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4565 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4566 // keep track of muted state to avoid repeating mute/unmute operations
4567 if (mBeaconMuted != mute) {
4568 // mute/unmute AUDIO_STREAM_TTS on all outputs
4569 ALOGV("\t muting %d", mute);
4570 uint32_t maxLatency = 0;
4571 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004572 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004573 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004574 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004575 0 /*delay*/, AUDIO_DEVICE_NONE);
4576 const uint32_t latency = desc->latency() * 2;
4577 if (latency > maxLatency) {
4578 maxLatency = latency;
4579 }
4580 }
4581 mBeaconMuted = mute;
4582 return maxLatency;
4583 }
4584 return 0;
4585}
4586
Eric Laurente0720872014-03-11 09:30:41 -07004587audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004588 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004589{
Paul McLeanaa981192015-03-21 09:55:15 -07004590 // Routing
4591 // see if we have an explicit route
4592 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4593 // (getStrategy(stream)).
4594 // if the strategy from the stream type in the RouteMap is the same as the argument above,
4595 // and activity count is non-zero
4596 // the device = the device from the descriptor in the RouteMap, and exit.
4597 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4598 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08004599 routing_strategy routeStrategy = getStrategy(route->mStreamType);
4600 if ((routeStrategy == strategy) && route->isActive()) {
Paul McLeanaa981192015-03-21 09:55:15 -07004601 return route->mDeviceDescriptor->type();
4602 }
4603 }
4604
Eric Laurente552edb2014-03-10 17:42:56 -07004605 if (fromCache) {
4606 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4607 strategy, mDeviceForStrategy[strategy]);
4608 return mDeviceForStrategy[strategy];
4609 }
François Gaffie2110e042015-03-24 08:41:51 +01004610 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004611}
4612
Eric Laurente0720872014-03-11 09:30:41 -07004613void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004614{
4615 for (int i = 0; i < NUM_STRATEGIES; i++) {
4616 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4617 }
4618 mPreviousOutputs = mOutputs;
4619}
4620
Eric Laurent1f2f2232014-06-02 12:01:23 -07004621uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004622 audio_devices_t prevDevice,
4623 uint32_t delayMs)
4624{
4625 // mute/unmute strategies using an incompatible device combination
4626 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4627 // if unmuting, unmute only after the specified delay
4628 if (outputDesc->isDuplicated()) {
4629 return 0;
4630 }
4631
4632 uint32_t muteWaitMs = 0;
4633 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004634 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004635
4636 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4637 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004638 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004639 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4640 bool doMute = false;
4641
4642 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4643 doMute = true;
4644 outputDesc->mStrategyMutedByDevice[i] = true;
4645 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4646 doMute = true;
4647 outputDesc->mStrategyMutedByDevice[i] = false;
4648 }
Eric Laurent99401132014-05-07 19:48:15 -07004649 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004650 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004651 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004652 // skip output if it does not share any device with current output
4653 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4654 == AUDIO_DEVICE_NONE) {
4655 continue;
4656 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004657 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x)",
4658 mute ? "muting" : "unmuting", i, curDevice);
4659 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01004660 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004661 if (mute) {
4662 // FIXME: should not need to double latency if volume could be applied
4663 // immediately by the audioflinger mixer. We must account for the delay
4664 // between now and the next time the audioflinger thread for this output
4665 // will process a buffer (which corresponds to one buffer size,
4666 // usually 1/2 or 1/4 of the latency).
4667 if (muteWaitMs < desc->latency() * 2) {
4668 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004669 }
4670 }
4671 }
4672 }
4673 }
4674 }
4675
Eric Laurent99401132014-05-07 19:48:15 -07004676 // temporary mute output if device selection changes to avoid volume bursts due to
4677 // different per device volumes
4678 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004679 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
4680 // temporary mute duration is conservatively set to 4 times the reported latency
4681 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
4682 if (muteWaitMs < tempMuteWaitMs) {
4683 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07004684 }
Eric Laurentdc462862016-07-19 12:29:53 -07004685
Eric Laurent99401132014-05-07 19:48:15 -07004686 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01004687 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004688 // make sure that we do not start the temporary mute period too early in case of
4689 // delayed device change
4690 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004691 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07004692 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07004693 }
4694 }
4695 }
4696
Eric Laurente552edb2014-03-10 17:42:56 -07004697 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4698 if (muteWaitMs > delayMs) {
4699 muteWaitMs -= delayMs;
4700 usleep(muteWaitMs * 1000);
4701 return muteWaitMs;
4702 }
4703 return 0;
4704}
4705
Eric Laurentc75307b2015-03-17 15:29:32 -07004706uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004707 audio_devices_t device,
4708 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004709 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004710 audio_patch_handle_t *patchHandle,
4711 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004712{
Eric Laurentc75307b2015-03-17 15:29:32 -07004713 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004714 AudioParameter param;
4715 uint32_t muteWaitMs;
4716
4717 if (outputDesc->isDuplicated()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004718 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
4719 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004720 return muteWaitMs;
4721 }
4722 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4723 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07004724 if ((device != AUDIO_DEVICE_NONE) &&
4725 ((device & outputDesc->supportedDevices()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004726 return 0;
4727 }
4728
4729 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07004730 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004731
4732 audio_devices_t prevDevice = outputDesc->mDevice;
4733
Paul McLeanaa981192015-03-21 09:55:15 -07004734 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004735
4736 if (device != AUDIO_DEVICE_NONE) {
4737 outputDesc->mDevice = device;
4738 }
4739 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4740
4741 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004742 // the requested device is AUDIO_DEVICE_NONE
4743 // OR the requested device is the same as current device
4744 // AND force is not specified
4745 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004746 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07004747 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
4748 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004749 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004750 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004751 return muteWaitMs;
4752 }
4753
4754 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004755
Eric Laurente552edb2014-03-10 17:42:56 -07004756 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004757 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004758 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004759 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07004760 DeviceVector deviceList;
4761 if ((address == NULL) || (strlen(address) == 0)) {
4762 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
4763 } else {
4764 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
4765 }
4766
Eric Laurent1c333e22014-05-20 10:48:17 -07004767 if (!deviceList.isEmpty()) {
4768 struct audio_patch patch;
4769 outputDesc->toAudioPortConfig(&patch.sources[0]);
4770 patch.num_sources = 1;
4771 patch.num_sinks = 0;
4772 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4773 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004774 patch.num_sinks++;
4775 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004776 ssize_t index;
4777 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4778 index = mAudioPatches.indexOfKey(*patchHandle);
4779 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004780 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004781 }
4782 sp< AudioPatch> patchDesc;
4783 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4784 if (index >= 0) {
4785 patchDesc = mAudioPatches.valueAt(index);
4786 afPatchHandle = patchDesc->mAfPatchHandle;
4787 }
4788
Eric Laurent1c333e22014-05-20 10:48:17 -07004789 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004790 &afPatchHandle,
4791 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004792 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4793 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004794 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004795 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004796 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004797 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004798 addAudioPatch(patchDesc->mHandle, patchDesc);
4799 } else {
4800 patchDesc->mPatch = patch;
4801 }
4802 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004803 if (patchHandle) {
4804 *patchHandle = patchDesc->mHandle;
4805 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004806 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004807 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004808 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004809 }
4810 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004811
4812 // inform all input as well
4813 for (size_t i = 0; i < mInputs.size(); i++) {
4814 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01004815 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08004816 AudioParameter inputCmd = AudioParameter();
4817 ALOGV("%s: inform input %d of device:%d", __func__,
4818 inputDescriptor->mIoHandle, device);
4819 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4820 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4821 inputCmd.toString(),
4822 delayMs);
4823 }
4824 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004825 }
Eric Laurente552edb2014-03-10 17:42:56 -07004826
4827 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07004828 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004829
4830 return muteWaitMs;
4831}
4832
Eric Laurentc75307b2015-03-17 15:29:32 -07004833status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07004834 int delayMs,
4835 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004836{
Eric Laurent6a94d692014-05-20 11:18:06 -07004837 ssize_t index;
4838 if (patchHandle) {
4839 index = mAudioPatches.indexOfKey(*patchHandle);
4840 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004841 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004842 }
4843 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004844 return INVALID_OPERATION;
4845 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004846 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4847 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004848 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004849 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004850 removeAudioPatch(patchDesc->mHandle);
4851 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004852 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004853 return status;
4854}
4855
4856status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4857 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004858 bool force,
4859 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004860{
4861 status_t status = NO_ERROR;
4862
Eric Laurent1f2f2232014-06-02 12:01:23 -07004863 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004864 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4865 inputDesc->mDevice = device;
4866
4867 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4868 if (!deviceList.isEmpty()) {
4869 struct audio_patch patch;
4870 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004871 // AUDIO_SOURCE_HOTWORD is for internal use only:
4872 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004873 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08004874 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004875 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4876 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004877 patch.num_sinks = 1;
4878 //only one input device for now
4879 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004880 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004881 ssize_t index;
4882 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4883 index = mAudioPatches.indexOfKey(*patchHandle);
4884 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004885 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004886 }
4887 sp< AudioPatch> patchDesc;
4888 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4889 if (index >= 0) {
4890 patchDesc = mAudioPatches.valueAt(index);
4891 afPatchHandle = patchDesc->mAfPatchHandle;
4892 }
4893
Eric Laurent1c333e22014-05-20 10:48:17 -07004894 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004895 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004896 0);
4897 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004898 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004899 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004900 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004901 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004902 addAudioPatch(patchDesc->mHandle, patchDesc);
4903 } else {
4904 patchDesc->mPatch = patch;
4905 }
4906 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004907 if (patchHandle) {
4908 *patchHandle = patchDesc->mHandle;
4909 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004910 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004911 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004912 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004913 }
4914 }
4915 }
4916 return status;
4917}
4918
Eric Laurent6a94d692014-05-20 11:18:06 -07004919status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4920 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004921{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004922 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004923 ssize_t index;
4924 if (patchHandle) {
4925 index = mAudioPatches.indexOfKey(*patchHandle);
4926 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004927 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004928 }
4929 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004930 return INVALID_OPERATION;
4931 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004932 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4933 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004934 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004935 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004936 removeAudioPatch(patchDesc->mHandle);
4937 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004938 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004939 return status;
4940}
4941
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08004942sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +01004943 String8 address,
4944 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07004945 audio_format_t& format,
4946 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01004947 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004948{
4949 // Choose an input profile based on the requested capture parameters: select the first available
4950 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07004951 //
4952 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
4953 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07004954
4955 for (size_t i = 0; i < mHwModules.size(); i++)
4956 {
4957 if (mHwModules[i]->mHandle == 0) {
4958 continue;
4959 }
4960 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4961 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004962 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004963 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08004964 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07004965 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07004966 format,
4967 &format /*updatedFormat*/,
4968 channelMask,
4969 &channelMask /*updatedChannelMask*/,
4970 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004971
Eric Laurente552edb2014-03-10 17:42:56 -07004972 return profile;
4973 }
4974 }
4975 }
4976 return NULL;
4977}
4978
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004979
4980audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01004981 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07004982{
François Gaffie036e1e92015-03-19 10:16:24 +01004983 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
4984 audio_devices_t selectedDeviceFromMix =
4985 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08004986
François Gaffie036e1e92015-03-19 10:16:24 +01004987 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
4988 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08004989 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004990 return getDeviceForInputSource(inputSource);
4991}
4992
4993audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
4994{
Paul McLean466dc8e2015-04-17 13:15:36 -06004995 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
4996 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004997 if (inputSource == route->mSource && route->isActive()) {
Paul McLean466dc8e2015-04-17 13:15:36 -06004998 return route->mDeviceDescriptor->type();
4999 }
5000 }
5001
5002 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005003}
5004
Eric Laurente0720872014-03-11 09:30:41 -07005005float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005006 int index,
5007 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005008{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005009 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Eric Laurente552edb2014-03-10 17:42:56 -07005010 // if a headset is connected, apply the following rules to ring tones and notifications
5011 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005012 // - always attenuate notifications volume by 6dB
5013 // - attenuate ring tones volume by 6dB unless music is not playing and
5014 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005015 // - if music is playing, always limit the volume to current music volume,
5016 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005017 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005018 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5019 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5020 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5021 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5022 ((stream_strategy == STRATEGY_SONIFICATION)
5023 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005024 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005025 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005026 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005027 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005028 // when the phone is ringing we must consider that music could have been paused just before
5029 // by the music application and behave as if music was active if the last music track was
5030 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005031 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005032 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005033 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005034 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005035 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005036 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5037 musicDevice),
5038 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005039 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5040 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005041 if (volumeDB > minVolDB) {
5042 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005043 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005044 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005045 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5046 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5047 // on A2DP, also ensure notification volume is not too low compared to media when
5048 // intended to be played
5049 if ((volumeDB > -96.0f) &&
5050 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5051 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5052 stream, device,
5053 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5054 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5055 }
5056 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005057 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5058 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005059 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005060 }
5061 }
5062
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005063 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005064}
5065
Eric Laurente0720872014-03-11 09:30:41 -07005066status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005067 int index,
5068 const sp<AudioOutputDescriptor>& outputDesc,
5069 audio_devices_t device,
5070 int delayMs,
5071 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005072{
Eric Laurente552edb2014-03-10 17:42:56 -07005073 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005074 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005075 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005076 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005077 return NO_ERROR;
5078 }
François Gaffie2110e042015-03-24 08:41:51 +01005079 audio_policy_forced_cfg_t forceUseForComm =
5080 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005081 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005082 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5083 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005084 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005085 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005086 return INVALID_OPERATION;
5087 }
5088
Eric Laurentc75307b2015-03-17 15:29:32 -07005089 if (device == AUDIO_DEVICE_NONE) {
5090 device = outputDesc->device();
5091 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005092
Eric Laurentffbc80f2015-03-18 18:30:19 -07005093 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07005094 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005095 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005096 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005097
Eric Laurentffbc80f2015-03-18 18:30:19 -07005098 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005099
Eric Laurent3b73df72014-03-11 09:06:29 -07005100 if (stream == AUDIO_STREAM_VOICE_CALL ||
5101 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005102 float voiceVolume;
5103 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005104 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005105 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005106 } else {
5107 voiceVolume = 1.0;
5108 }
5109
Eric Laurent18fba842016-03-31 14:41:26 -07005110 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005111 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5112 mLastVoiceVolume = voiceVolume;
5113 }
5114 }
5115
5116 return NO_ERROR;
5117}
5118
Eric Laurentc75307b2015-03-17 15:29:32 -07005119void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5120 audio_devices_t device,
5121 int delayMs,
5122 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005123{
Eric Laurentc75307b2015-03-17 15:29:32 -07005124 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005125
Eric Laurent794fde22016-03-11 09:50:45 -08005126 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005127 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005128 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005129 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005130 device,
5131 delayMs,
5132 force);
5133 }
5134}
5135
Eric Laurente0720872014-03-11 09:30:41 -07005136void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005137 bool on,
5138 const sp<AudioOutputDescriptor>& outputDesc,
5139 int delayMs,
5140 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005141{
Eric Laurent72249d52015-06-08 11:12:15 -07005142 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5143 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005144 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005145 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005146 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005147 }
5148 }
5149}
5150
Eric Laurente0720872014-03-11 09:30:41 -07005151void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005152 bool on,
5153 const sp<AudioOutputDescriptor>& outputDesc,
5154 int delayMs,
5155 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005156{
Eric Laurente552edb2014-03-10 17:42:56 -07005157 if (device == AUDIO_DEVICE_NONE) {
5158 device = outputDesc->device();
5159 }
5160
Eric Laurentc75307b2015-03-17 15:29:32 -07005161 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5162 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005163
5164 if (on) {
5165 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005166 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005167 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005168 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005169 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005170 }
5171 }
5172 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5173 outputDesc->mMuteCount[stream]++;
5174 } else {
5175 if (outputDesc->mMuteCount[stream] == 0) {
5176 ALOGV("setStreamMute() unmuting non muted stream!");
5177 return;
5178 }
5179 if (--outputDesc->mMuteCount[stream] == 0) {
5180 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005181 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005182 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005183 device,
5184 delayMs);
5185 }
5186 }
5187}
5188
Eric Laurente0720872014-03-11 09:30:41 -07005189void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005190 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005191{
Eric Laurent87ffa392015-05-22 10:32:38 -07005192 if(!hasPrimaryOutput()) {
5193 return;
5194 }
5195
Eric Laurente552edb2014-03-10 17:42:56 -07005196 // if the stream pertains to sonification strategy and we are in call we must
5197 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5198 // in the device used for phone strategy and play the tone if the selected device does not
5199 // interfere with the device used for phone strategy
5200 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5201 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005202 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005203 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5204 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005205 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005206 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5207 stream, starting, outputDesc->mDevice, stateChange);
5208 if (outputDesc->mRefCount[stream]) {
5209 int muteCount = 1;
5210 if (stateChange) {
5211 muteCount = outputDesc->mRefCount[stream];
5212 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005213 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005214 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5215 for (int i = 0; i < muteCount; i++) {
5216 setStreamMute(stream, starting, mPrimaryOutput);
5217 }
5218 } else {
5219 ALOGV("handleIncallSonification() high visibility");
5220 if (outputDesc->device() &
5221 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5222 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5223 for (int i = 0; i < muteCount; i++) {
5224 setStreamMute(stream, starting, mPrimaryOutput);
5225 }
5226 }
5227 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005228 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5229 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005230 } else {
5231 mpClientInterface->stopTone();
5232 }
5233 }
5234 }
5235 }
5236}
5237
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005238audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5239{
5240 // flags to stream type mapping
5241 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5242 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5243 }
5244 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5245 return AUDIO_STREAM_BLUETOOTH_SCO;
5246 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005247 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5248 return AUDIO_STREAM_TTS;
5249 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005250
5251 // usage to stream type mapping
5252 switch (attr->usage) {
5253 case AUDIO_USAGE_MEDIA:
5254 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005255 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5256 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005257 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5258 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005259 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5260 return AUDIO_STREAM_SYSTEM;
5261 case AUDIO_USAGE_VOICE_COMMUNICATION:
5262 return AUDIO_STREAM_VOICE_CALL;
5263
5264 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5265 return AUDIO_STREAM_DTMF;
5266
5267 case AUDIO_USAGE_ALARM:
5268 return AUDIO_STREAM_ALARM;
5269 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5270 return AUDIO_STREAM_RING;
5271
5272 case AUDIO_USAGE_NOTIFICATION:
5273 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5274 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5275 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5276 case AUDIO_USAGE_NOTIFICATION_EVENT:
5277 return AUDIO_STREAM_NOTIFICATION;
5278
5279 case AUDIO_USAGE_UNKNOWN:
5280 default:
5281 return AUDIO_STREAM_MUSIC;
5282 }
5283}
Eric Laurente83b55d2014-11-14 10:06:21 -08005284
François Gaffie53615e22015-03-19 09:24:12 +01005285bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5286{
Eric Laurente83b55d2014-11-14 10:06:21 -08005287 // has flags that map to a strategy?
5288 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5289 return true;
5290 }
5291
5292 // has known usage?
5293 switch (paa->usage) {
5294 case AUDIO_USAGE_UNKNOWN:
5295 case AUDIO_USAGE_MEDIA:
5296 case AUDIO_USAGE_VOICE_COMMUNICATION:
5297 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5298 case AUDIO_USAGE_ALARM:
5299 case AUDIO_USAGE_NOTIFICATION:
5300 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5301 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5302 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5303 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5304 case AUDIO_USAGE_NOTIFICATION_EVENT:
5305 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5306 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5307 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5308 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005309 case AUDIO_USAGE_VIRTUAL_SOURCE:
Eric Laurente83b55d2014-11-14 10:06:21 -08005310 break;
5311 default:
5312 return false;
5313 }
5314 return true;
5315}
5316
François Gaffiead3183e2015-03-18 16:55:35 +01005317bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor> outputDesc,
5318 routing_strategy strategy, uint32_t inPastMs,
5319 nsecs_t sysTime) const
5320{
5321 if ((sysTime == 0) && (inPastMs != 0)) {
5322 sysTime = systemTime();
5323 }
Eric Laurent794fde22016-03-11 09:50:45 -08005324 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005325 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5326 (NUM_STRATEGIES == strategy)) &&
5327 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5328 return true;
5329 }
5330 }
5331 return false;
5332}
5333
François Gaffie2110e042015-03-24 08:41:51 +01005334audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5335{
5336 return mEngine->getForceUse(usage);
5337}
5338
5339bool AudioPolicyManager::isInCall()
5340{
5341 return isStateInCall(mEngine->getPhoneState());
5342}
5343
5344bool AudioPolicyManager::isStateInCall(int state)
5345{
5346 return is_state_in_call(state);
5347}
5348
Eric Laurentd60560a2015-04-10 11:31:20 -07005349void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5350{
5351 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5352 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5353 if (sourceDesc->mDevice->equals(deviceDesc)) {
5354 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5355 stopAudioSource(sourceDesc->getHandle());
5356 }
5357 }
5358
5359 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5360 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5361 bool release = false;
5362 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5363 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5364 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5365 source->ext.device.type == deviceDesc->type()) {
5366 release = true;
5367 }
5368 }
5369 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5370 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5371 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5372 sink->ext.device.type == deviceDesc->type()) {
5373 release = true;
5374 }
5375 }
5376 if (release) {
5377 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5378 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5379 }
5380 }
5381}
5382
Phil Burk09bc4612016-02-24 15:58:15 -08005383// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005384void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5385 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005386 // TODO Set this based on Config properties.
5387 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005388
5389 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5390 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005391 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005392
5393 // Analyze original support for various formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005394 bool supportsAC3 = false;
5395 bool supportsOtherSurround = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005396 bool supportsIEC61937 = false;
5397 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5398 audio_format_t format = formats[formatIndex];
Phil Burk09bc4612016-02-24 15:58:15 -08005399 switch (format) {
5400 case AUDIO_FORMAT_AC3:
Phil Burk07ac1142016-03-25 13:39:29 -07005401 supportsAC3 = true;
5402 break;
Phil Burk09bc4612016-02-24 15:58:15 -08005403 case AUDIO_FORMAT_E_AC3:
5404 case AUDIO_FORMAT_DTS:
5405 case AUDIO_FORMAT_DTS_HD:
Phil Burk07ac1142016-03-25 13:39:29 -07005406 supportsOtherSurround = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005407 break;
5408 case AUDIO_FORMAT_IEC61937:
5409 supportsIEC61937 = true;
5410 break;
5411 default:
5412 break;
5413 }
5414 }
Phil Burk09bc4612016-02-24 15:58:15 -08005415
5416 // Modify formats based on surround preferences.
5417 // If NEVER, remove support for surround formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005418 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5419 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5420 // Remove surround sound related formats.
5421 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5422 audio_format_t format = formats[formatIndex];
5423 switch(format) {
5424 case AUDIO_FORMAT_AC3:
5425 case AUDIO_FORMAT_E_AC3:
5426 case AUDIO_FORMAT_DTS:
5427 case AUDIO_FORMAT_DTS_HD:
5428 case AUDIO_FORMAT_IEC61937:
Phil Burk07ac1142016-03-25 13:39:29 -07005429 formats.removeAt(formatIndex);
5430 break;
5431 default:
5432 formatIndex++; // keep it
5433 break;
5434 }
Phil Burk09bc4612016-02-24 15:58:15 -08005435 }
Phil Burk07ac1142016-03-25 13:39:29 -07005436 supportsAC3 = false;
5437 supportsOtherSurround = false;
5438 supportsIEC61937 = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005439 }
Phil Burk07ac1142016-03-25 13:39:29 -07005440 } else { // AUTO or ALWAYS
5441 // Most TVs support AC3 even if they do not report it in the EDID.
5442 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5443 && !supportsAC3) {
5444 formats.add(AUDIO_FORMAT_AC3);
5445 supportsAC3 = true;
5446 }
5447
5448 // If ALWAYS, add support for raw surround formats if all are missing.
5449 // This assumes that if any of these formats are reported by the HAL
5450 // then the report is valid and should not be modified.
5451 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS)
5452 && !supportsOtherSurround) {
5453 formats.add(AUDIO_FORMAT_E_AC3);
5454 formats.add(AUDIO_FORMAT_DTS);
5455 formats.add(AUDIO_FORMAT_DTS_HD);
5456 supportsOtherSurround = true;
5457 }
5458
5459 // Add support for IEC61937 if any raw surround supported.
5460 // The HAL could do this but add it here, just in case.
5461 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5462 formats.add(AUDIO_FORMAT_IEC61937);
5463 supportsIEC61937 = true;
5464 }
Phil Burk09bc4612016-02-24 15:58:15 -08005465 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005466}
5467
5468// Modify the list of channel masks supported.
5469void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5470 ChannelsVector &channelMasks = *channelMasksPtr;
5471 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5472 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5473
5474 // If NEVER, then remove support for channelMasks > stereo.
5475 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5476 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5477 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5478 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5479 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5480 channelMasks.removeAt(maskIndex);
5481 } else {
5482 maskIndex++;
5483 }
5484 }
5485 // If ALWAYS, then make sure we at least support 5.1
5486 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5487 bool supports5dot1 = false;
5488 // Are there any channel masks that can be considered "surround"?
5489 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); maskIndex++) {
5490 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5491 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5492 supports5dot1 = true;
5493 break;
5494 }
5495 }
5496 // If not then add 5.1 support.
5497 if (!supports5dot1) {
5498 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5499 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5500 }
Phil Burk09bc4612016-02-24 15:58:15 -08005501 }
5502}
5503
Phil Burk00eeb322016-03-31 12:41:00 -07005504void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5505 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005506 AudioProfileVector &profiles)
5507{
5508 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005509
François Gaffie112b0af2015-11-19 16:13:25 +01005510 // Format MUST be checked first to update the list of AudioProfile
5511 if (profiles.hasDynamicFormat()) {
5512 reply = mpClientInterface->getParameters(ioHandle,
5513 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Phil Burk0709b0a2016-03-31 12:54:57 -07005514 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005515 AudioParameter repliedParameters(reply);
5516 if (repliedParameters.get(
5517 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005518 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5519 return;
5520 }
Phil Burk09bc4612016-02-24 15:58:15 -08005521 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005522 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005523 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005524 }
Phil Burk09bc4612016-02-24 15:58:15 -08005525 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005526 }
5527 const FormatVector &supportedFormats = profiles.getSupportedFormats();
5528
Eric Laurent20eb3a42016-01-26 18:39:17 -08005529 for (size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
François Gaffie112b0af2015-11-19 16:13:25 +01005530 audio_format_t format = supportedFormats[formatIndex];
Eric Laurent20eb3a42016-01-26 18:39:17 -08005531 ChannelsVector channelMasks;
5532 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005533 AudioParameter requestedParameters;
5534 requestedParameters.addInt(String8(AUDIO_PARAMETER_STREAM_FORMAT), format);
5535
5536 if (profiles.hasDynamicRateFor(format)) {
5537 reply = mpClientInterface->getParameters(ioHandle,
5538 requestedParameters.toString() + ";" +
5539 AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES);
5540 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005541 AudioParameter repliedParameters(reply);
5542 if (repliedParameters.get(
5543 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES), reply) == NO_ERROR) {
5544 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005545 }
5546 }
5547 if (profiles.hasDynamicChannelsFor(format)) {
5548 reply = mpClientInterface->getParameters(ioHandle,
5549 requestedParameters.toString() + ";" +
5550 AUDIO_PARAMETER_STREAM_SUP_CHANNELS);
5551 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005552 AudioParameter repliedParameters(reply);
5553 if (repliedParameters.get(
5554 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS), reply) == NO_ERROR) {
5555 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005556 if (device == AUDIO_DEVICE_OUT_HDMI) {
5557 filterSurroundChannelMasks(&channelMasks);
5558 }
François Gaffie112b0af2015-11-19 16:13:25 +01005559 }
5560 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005561 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005562 }
5563}
Eric Laurentd60560a2015-04-10 11:31:20 -07005564
Eric Laurente552edb2014-03-10 17:42:56 -07005565}; // namespace android